repo
string | commit
string | message
string | diff
string |
---|---|---|---|
rickclare/apache2-conf
|
8086bcabb866e86c689872649e6fbcfaec77571d
|
upgrading passenger
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index 8272231..81c43f2 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,227 +1,227 @@
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
# Tools-Drinkaware (Rails Passenger, Ruby1.8)
<VirtualHost *:80>
ServerAlias tools.drinkaware.localhost.enableinteractive.co.uk
ServerAlias tools.drinkaware.dev.enableinteractive.co.uk
DocumentRoot "/Users/Shared/Dev/workspace/tools-drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/tools-drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/tools_drinkaware_error.log
CustomLog /opt/local/apache2/logs/tools_drinkaware_access.log combined
RailsBaseURI /
PassengerDefaultUser root
RailsEnv development
# Enable ETag
#FileETag MTime Size
# Enable Compression (GZIP) of shown content-types
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/xhtml+xml application/javascript
# enable expirations
ExpiresActive On
# far future expires headers
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf)$">
ExpiresDefault "access plus 10 years"
</FilesMatch>
<FilesMatch "\.(js|css)$">
ExpiresDefault "now"
</FilesMatch>
<Location />
- # enable tracking uploads in /
- TrackUploads On
+ # enable tracking uploads in /
+ TrackUploads On
</Location>
<Location /progress>
- # enable upload progress reports in /progress
- ReportUploads On
+ # enable upload progress reports in /progress
+ ReportUploads On
</Location>
</VirtualHost>
# Magento Sandbox local
<VirtualHost *:80>
ServerName magento.localhost
DocumentRoot "/Users/Shared/Dev/workspace/magento"
DirectoryIndex index.php
<Directory "/Users/Shared/Dev/workspace/magento">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/magento_error.log
CustomLog /opt/local/apache2/logs/magento_access.log combined
php_flag log_errors on
php_value error_log /opt/local/apache2/logs/magento_php_error.log
php_flag display_errors on
# E_ALL & ~E_NOTICE
php_value error_reporting 6135
</VirtualHost>
## Because it's Good (Rails Passenger)
# <VirtualHost *:80>
# ServerName because-enable.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/because-enable/public"
# <Directory "/Users/Shared/Dev/workspace/because-enable/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/because-enable_error.log
# CustomLog /opt/local/apache2/logs/because-enable_access.log combined
# RailsBaseURI /
# RailsEnv staging
# </VirtualHost>
## Football Prototype (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName fans.drinkaware.co.uk
# ServerAlias wvvw.drinkaware.co.uk
# DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
# <Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
## Redmine (Rails Passenger)
# <VirtualHost *:80>
# ServerName redmine.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/redmine/public"
# <Directory "/Users/Shared/Dev/workspace/redmine/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/redmine_error.log
# CustomLog /opt/local/apache2/logs/redmine_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
## Ultimate Day (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName ultimateday.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development_mysql
# </VirtualHost>
############################
## YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
# <VirtualHost *:80>
# ServerName drinkdiary.localhost
# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
#
# DirectoryIndex index.php
# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
# AllowOverride All
# Allow from All
# #AuthType Basic
# #AuthName "Restricted Files"
# #AuthUserFile /usr/local/apache/passwd/passwords
# #Require user rick
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
## Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
## Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
diff --git a/extra/mod_php.conf b/extra/mod_php.conf
new file mode 100755
index 0000000..f51b0df
--- /dev/null
+++ b/extra/mod_php.conf
@@ -0,0 +1,6 @@
+<IfModule mod_php5.c>
+
+AddType application/x-httpd-php .php
+AddType application/x-httpd-php-source .phps
+
+</IfModule>
diff --git a/httpd.conf b/httpd.conf
index 369e640..5e71d15 100644
--- a/httpd.conf
+++ b/httpd.conf
@@ -1,503 +1,504 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
# server as "/opt/local/apache2/logs/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/opt/local/apache2"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule php5_module modules/libphp5.so
LoadModule upload_progress_module modules/mod_upload_progress.so
-# LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.10/ext/apache2/mod_passenger.so
-# PassengerRoot /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.10
+# LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.11/ext/apache2/mod_passenger.so
+# PassengerRoot /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.11
# PassengerRuby /Users/rick/.rvm/bin/ruby-1.8.7-p249
-LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.9.1-p378/gems/passenger-2.2.10/ext/apache2/mod_passenger.so
-PassengerRoot /Users/rick/.rvm/gems/ruby-1.9.1-p378/gems/passenger-2.2.10
+LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.9.1-p378/gems/passenger-2.2.11/ext/apache2/mod_passenger.so
+PassengerRoot /Users/rick/.rvm/gems/ruby-1.9.1-p378/gems/passenger-2.2.11
PassengerRuby /Users/rick/.rvm/bin/passenger_ruby
+
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User rick
Group wheel
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/opt/local/apache2/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/opt/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
#
# The following lines prevent .htaccess files from being viewed by
# Web clients. Since .htaccess files often contain authorization
# information, access is disallowed for security reasons. Comment
# these lines out if you want Web visitors to see the contents of
# .htaccess files.
#
# Also, folks tend to use names such as .htpasswd for password
# files, so this will protect those as well.
#
<Files ~ "^<.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</Files>
#
# Apple specific filesystem protection.
#
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<Directory ~ ".\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</Directory>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock logs/cgisock
</IfModule>
#
# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/opt/local/apache2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
Include conf/extra/httpd-info.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
|
rickclare/apache2-conf
|
4e917ffd78ecc33330530507e86d58518a1b57f3
|
adding upload stuff
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index 716ac1c..8272231 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,224 +1,227 @@
-
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
# Tools-Drinkaware (Rails Passenger, Ruby1.8)
<VirtualHost *:80>
ServerAlias tools.drinkaware.localhost.enableinteractive.co.uk
ServerAlias tools.drinkaware.dev.enableinteractive.co.uk
DocumentRoot "/Users/Shared/Dev/workspace/tools-drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/tools-drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/tools_drinkaware_error.log
CustomLog /opt/local/apache2/logs/tools_drinkaware_access.log combined
RailsBaseURI /
PassengerDefaultUser root
RailsEnv development
# Enable ETag
#FileETag MTime Size
# Enable Compression (GZIP) of shown content-types
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/xhtml+xml application/javascript
# enable expirations
ExpiresActive On
# far future expires headers
- <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
+ <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf)$">
ExpiresDefault "access plus 10 years"
</FilesMatch>
+ <FilesMatch "\.(js|css)$">
+ ExpiresDefault "now"
+ </FilesMatch>
+
<Location />
# enable tracking uploads in /
TrackUploads On
</Location>
<Location /progress>
# enable upload progress reports in /progress
ReportUploads On
</Location>
</VirtualHost>
# Magento Sandbox local
<VirtualHost *:80>
ServerName magento.localhost
DocumentRoot "/Users/Shared/Dev/workspace/magento"
DirectoryIndex index.php
<Directory "/Users/Shared/Dev/workspace/magento">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/magento_error.log
CustomLog /opt/local/apache2/logs/magento_access.log combined
php_flag log_errors on
php_value error_log /opt/local/apache2/logs/magento_php_error.log
php_flag display_errors on
# E_ALL & ~E_NOTICE
php_value error_reporting 6135
</VirtualHost>
## Because it's Good (Rails Passenger)
# <VirtualHost *:80>
# ServerName because-enable.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/because-enable/public"
# <Directory "/Users/Shared/Dev/workspace/because-enable/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/because-enable_error.log
# CustomLog /opt/local/apache2/logs/because-enable_access.log combined
# RailsBaseURI /
# RailsEnv staging
# </VirtualHost>
## Football Prototype (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName fans.drinkaware.co.uk
# ServerAlias wvvw.drinkaware.co.uk
# DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
# <Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
## Redmine (Rails Passenger)
# <VirtualHost *:80>
# ServerName redmine.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/redmine/public"
# <Directory "/Users/Shared/Dev/workspace/redmine/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/redmine_error.log
# CustomLog /opt/local/apache2/logs/redmine_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
## Ultimate Day (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName ultimateday.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development_mysql
# </VirtualHost>
############################
## YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
# <VirtualHost *:80>
# ServerName drinkdiary.localhost
# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
#
# DirectoryIndex index.php
# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
# AllowOverride All
# Allow from All
# #AuthType Basic
# #AuthName "Restricted Files"
# #AuthUserFile /usr/local/apache/passwd/passwords
# #Require user rick
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
## Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
## Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
diff --git a/upload_progress.conf b/upload_progress.conf
new file mode 100644
index 0000000..e69de29
|
rickclare/apache2-conf
|
cbe01f3e177f52c5e98846b02cf2b2e45257007d
|
updating to ruby1.9.1
|
diff --git a/httpd.conf b/httpd.conf
index b18f389..369e640 100644
--- a/httpd.conf
+++ b/httpd.conf
@@ -1,500 +1,503 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
# server as "/opt/local/apache2/logs/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/opt/local/apache2"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule php5_module modules/libphp5.so
-LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.10/ext/apache2/mod_passenger.so
LoadModule upload_progress_module modules/mod_upload_progress.so
-PassengerRoot /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.10
-PassengerRuby /Users/rick/.rvm/bin/ruby-1.8.7-p249
+# LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.10/ext/apache2/mod_passenger.so
+# PassengerRoot /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.10
+# PassengerRuby /Users/rick/.rvm/bin/ruby-1.8.7-p249
+LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.9.1-p378/gems/passenger-2.2.10/ext/apache2/mod_passenger.so
+PassengerRoot /Users/rick/.rvm/gems/ruby-1.9.1-p378/gems/passenger-2.2.10
+PassengerRuby /Users/rick/.rvm/bin/passenger_ruby
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User rick
Group wheel
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/opt/local/apache2/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/opt/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
#
# The following lines prevent .htaccess files from being viewed by
# Web clients. Since .htaccess files often contain authorization
# information, access is disallowed for security reasons. Comment
# these lines out if you want Web visitors to see the contents of
# .htaccess files.
#
# Also, folks tend to use names such as .htpasswd for password
# files, so this will protect those as well.
#
<Files ~ "^<.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</Files>
#
# Apple specific filesystem protection.
#
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<Directory ~ ".\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</Directory>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock logs/cgisock
</IfModule>
#
# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/opt/local/apache2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
Include conf/extra/httpd-info.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
diff --git a/httpd.conf.bak b/httpd.conf.bak
index 1146f6f..b18f389 100644
--- a/httpd.conf.bak
+++ b/httpd.conf.bak
@@ -1,499 +1,500 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
# server as "/opt/local/apache2/logs/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/opt/local/apache2"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule php5_module modules/libphp5.so
-LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
-PassengerRoot /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9
+LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.10/ext/apache2/mod_passenger.so
+LoadModule upload_progress_module modules/mod_upload_progress.so
+PassengerRoot /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.10
PassengerRuby /Users/rick/.rvm/bin/ruby-1.8.7-p249
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User rick
Group wheel
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/opt/local/apache2/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/opt/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
#
# The following lines prevent .htaccess files from being viewed by
# Web clients. Since .htaccess files often contain authorization
# information, access is disallowed for security reasons. Comment
# these lines out if you want Web visitors to see the contents of
# .htaccess files.
#
# Also, folks tend to use names such as .htpasswd for password
# files, so this will protect those as well.
#
<Files ~ "^<.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</Files>
#
# Apple specific filesystem protection.
#
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<Directory ~ ".\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</Directory>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock logs/cgisock
</IfModule>
#
# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/opt/local/apache2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
Include conf/extra/httpd-info.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
|
rickclare/apache2-conf
|
6ff0500001b8c49ab298b3be3aba501898126bdf
|
updating passenger
|
diff --git a/httpd.conf b/httpd.conf
index 1fb3221..b18f389 100644
--- a/httpd.conf
+++ b/httpd.conf
@@ -1,500 +1,500 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
# server as "/opt/local/apache2/logs/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/opt/local/apache2"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule php5_module modules/libphp5.so
-LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
+LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.10/ext/apache2/mod_passenger.so
LoadModule upload_progress_module modules/mod_upload_progress.so
-PassengerRoot /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9
+PassengerRoot /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.10
PassengerRuby /Users/rick/.rvm/bin/ruby-1.8.7-p249
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User rick
Group wheel
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/opt/local/apache2/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/opt/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
#
# The following lines prevent .htaccess files from being viewed by
# Web clients. Since .htaccess files often contain authorization
# information, access is disallowed for security reasons. Comment
# these lines out if you want Web visitors to see the contents of
# .htaccess files.
#
# Also, folks tend to use names such as .htpasswd for password
# files, so this will protect those as well.
#
<Files ~ "^<.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</Files>
#
# Apple specific filesystem protection.
#
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<Directory ~ ".\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</Directory>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock logs/cgisock
</IfModule>
#
# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/opt/local/apache2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
Include conf/extra/httpd-info.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
|
rickclare/apache2-conf
|
30affa0c59c5faf8cccf72e85206ca21614e6f37
|
adding progress upload
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index 108cbf4..716ac1c 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,214 +1,224 @@
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
# Tools-Drinkaware (Rails Passenger, Ruby1.8)
<VirtualHost *:80>
ServerAlias tools.drinkaware.localhost.enableinteractive.co.uk
ServerAlias tools.drinkaware.dev.enableinteractive.co.uk
DocumentRoot "/Users/Shared/Dev/workspace/tools-drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/tools-drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/tools_drinkaware_error.log
CustomLog /opt/local/apache2/logs/tools_drinkaware_access.log combined
RailsBaseURI /
PassengerDefaultUser root
RailsEnv development
# Enable ETag
#FileETag MTime Size
# Enable Compression (GZIP) of shown content-types
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/xhtml+xml application/javascript
# enable expirations
ExpiresActive On
# far future expires headers
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
ExpiresDefault "access plus 10 years"
</FilesMatch>
+ <Location />
+ # enable tracking uploads in /
+ TrackUploads On
+ </Location>
+
+ <Location /progress>
+ # enable upload progress reports in /progress
+ ReportUploads On
+ </Location>
+
</VirtualHost>
# Magento Sandbox local
<VirtualHost *:80>
ServerName magento.localhost
DocumentRoot "/Users/Shared/Dev/workspace/magento"
DirectoryIndex index.php
<Directory "/Users/Shared/Dev/workspace/magento">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/magento_error.log
CustomLog /opt/local/apache2/logs/magento_access.log combined
php_flag log_errors on
php_value error_log /opt/local/apache2/logs/magento_php_error.log
php_flag display_errors on
# E_ALL & ~E_NOTICE
php_value error_reporting 6135
</VirtualHost>
## Because it's Good (Rails Passenger)
# <VirtualHost *:80>
# ServerName because-enable.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/because-enable/public"
# <Directory "/Users/Shared/Dev/workspace/because-enable/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/because-enable_error.log
# CustomLog /opt/local/apache2/logs/because-enable_access.log combined
# RailsBaseURI /
# RailsEnv staging
# </VirtualHost>
## Football Prototype (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName fans.drinkaware.co.uk
# ServerAlias wvvw.drinkaware.co.uk
# DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
# <Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
## Redmine (Rails Passenger)
# <VirtualHost *:80>
# ServerName redmine.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/redmine/public"
# <Directory "/Users/Shared/Dev/workspace/redmine/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/redmine_error.log
# CustomLog /opt/local/apache2/logs/redmine_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
## Ultimate Day (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName ultimateday.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development_mysql
# </VirtualHost>
############################
## YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
# <VirtualHost *:80>
# ServerName drinkdiary.localhost
# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
#
# DirectoryIndex index.php
# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
# AllowOverride All
# Allow from All
# #AuthType Basic
# #AuthName "Restricted Files"
# #AuthUserFile /usr/local/apache/passwd/passwords
# #Require user rick
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
## Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
## Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
diff --git a/httpd.conf b/httpd.conf
index 1146f6f..1fb3221 100644
--- a/httpd.conf
+++ b/httpd.conf
@@ -1,499 +1,500 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
# server as "/opt/local/apache2/logs/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/opt/local/apache2"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule php5_module modules/libphp5.so
LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
+LoadModule upload_progress_module modules/mod_upload_progress.so
PassengerRoot /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9
PassengerRuby /Users/rick/.rvm/bin/ruby-1.8.7-p249
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User rick
Group wheel
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/opt/local/apache2/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/opt/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
#
# The following lines prevent .htaccess files from being viewed by
# Web clients. Since .htaccess files often contain authorization
# information, access is disallowed for security reasons. Comment
# these lines out if you want Web visitors to see the contents of
# .htaccess files.
#
# Also, folks tend to use names such as .htpasswd for password
# files, so this will protect those as well.
#
<Files ~ "^<.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</Files>
#
# Apple specific filesystem protection.
#
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<Directory ~ ".\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</Directory>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock logs/cgisock
</IfModule>
#
# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/opt/local/apache2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
Include conf/extra/httpd-info.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
|
rickclare/apache2-conf
|
aae5e22b8ab91b2656fb401d2c1230bc4080280c
|
adding magento 2
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index 8203683..e6b2f2a 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,216 +1,215 @@
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
# Tools-Drinkaware (Rails Passenger, Ruby1.8)
<VirtualHost *:80>
ServerAlias tools.drinkaware.localhost.enableinteractive.co.uk
ServerAlias tools.drinkaware.dev.enableinteractive.co.uk
DocumentRoot "/Users/Shared/Dev/workspace/tools-drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/tools-drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/tools_drinkaware_error.log
CustomLog /opt/local/apache2/logs/tools_drinkaware_access.log combined
RailsBaseURI /
PassengerDefaultUser root
RailsEnv development
# Enable ETag
#FileETag MTime Size
# Enable Compression (GZIP) of shown content-types
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/xhtml+xml application/javascript
# enable expirations
ExpiresActive On
# far future expires headers
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
ExpiresDefault "access plus 10 years"
</FilesMatch>
</VirtualHost>
-# Because it's Good (Rails Passenger)
+############################
+#Magento Sandbox local
+<VirtualHost *:80>
+ ServerName magento.localhost
+ DocumentRoot "/Users/Shared/Dev/workspace/magento"
+ DirectoryIndex index.php
+ <Directory "/Users/Shared/Dev/workspace/magento">
+ AllowOverride All
+ Allow from All
+ </Directory>
+ ErrorLog /opt/local/apache2/logs/magento_error.log
+ CustomLog /opt/local/apache2/logs/magento_access.log combined
+ php_flag log_errors on
+ php_value error_log /opt/local/apache2/logs/magento_php_error.log
+ php_flag display_errors on
+
+ # E_ALL & ~E_NOTICE
+ php_value error_reporting 6135
+</VirtualHost>
+
+## Because it's Good (Rails Passenger)
# <VirtualHost *:80>
# ServerName because-enable.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/because-enable/public"
# <Directory "/Users/Shared/Dev/workspace/because-enable/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/because-enable_error.log
# CustomLog /opt/local/apache2/logs/because-enable_access.log combined
# RailsBaseURI /
# RailsEnv staging
# </VirtualHost>
-# Football Prototype (Drinkaware) (Rails Passenger)
+## Football Prototype (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName fans.drinkaware.co.uk
# ServerAlias wvvw.drinkaware.co.uk
# DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
# <Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
-# Redmine (Rails Passenger)
+## Redmine (Rails Passenger)
# <VirtualHost *:80>
# ServerName redmine.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/redmine/public"
# <Directory "/Users/Shared/Dev/workspace/redmine/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/redmine_error.log
# CustomLog /opt/local/apache2/logs/redmine_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
-# Ultimate Day (Drinkaware) (Rails Passenger)
+## Ultimate Day (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName ultimateday.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development_mysql
# </VirtualHost>
############################
-# YanleyFarm (Joomla) local
+## YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
<VirtualHost *:80>
ServerName drinkdiary.localhost
DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
DirectoryIndex index.php
<Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
AllowOverride All
Allow from All
#AuthType Basic
#AuthName "Restricted Files"
#AuthUserFile /usr/local/apache/passwd/passwords
#Require user rick
</Directory>
ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
php_flag log_errors on
php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
php_flag display_errors on
# E_ALL & ~E_NOTICE
php_value error_reporting 6135
</VirtualHost>
############################
-# Homelesslink (Drupal) local
+## Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
-# Drinkware Sandbox local
-#<VirtualHost *:80>
-# ServerName drinkaware.localhost
-# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
-# DirectoryIndex index.php index.html
-# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
-# AllowOverride All
-# Allow from All
-# </Directory>
-# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
-# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
-# php_flag log_errors on
-# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
-# php_flag display_errors on
-#
-# # E_ALL & ~E_NOTICE
-# php_value error_reporting 6135
-#</VirtualHost>
-
-
-############################
-# Joomla Sandbox local
+## Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
diff --git a/extra/mod_php.conf b/extra/mod_php.conf
deleted file mode 100755
index f51b0df..0000000
--- a/extra/mod_php.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-<IfModule mod_php5.c>
-
-AddType application/x-httpd-php .php
-AddType application/x-httpd-php-source .phps
-
-</IfModule>
diff --git a/httpd.conf.bak b/httpd.conf.bak
index ae06288..1146f6f 100644
--- a/httpd.conf.bak
+++ b/httpd.conf.bak
@@ -1,510 +1,499 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
# server as "/opt/local/apache2/logs/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/opt/local/apache2"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule php5_module modules/libphp5.so
-LoadModule passenger_module /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so
-PassengerRoot /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5
-PassengerRuby /opt/local/bin/ruby
+LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
+PassengerRoot /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9
+PassengerRuby /Users/rick/.rvm/bin/ruby-1.8.7-p249
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User rick
Group wheel
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/opt/local/apache2/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/opt/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
#
# The following lines prevent .htaccess files from being viewed by
# Web clients. Since .htaccess files often contain authorization
# information, access is disallowed for security reasons. Comment
# these lines out if you want Web visitors to see the contents of
# .htaccess files.
#
# Also, folks tend to use names such as .htpasswd for password
# files, so this will protect those as well.
#
<Files ~ "^<.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</Files>
#
# Apple specific filesystem protection.
#
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<Directory ~ ".\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</Directory>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock logs/cgisock
</IfModule>
#
# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/opt/local/apache2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
Include conf/extra/httpd-info.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
-
-# Uncomment following lines to enable Compression (GZIP) of shown content-types
-AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/xhtml+xml application/javascript
-
-# enable expirations
-ExpiresActive On
-
-# far future expires headers
-<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
- ExpiresDefault "access plus 10 years"
-</FilesMatch>
|
rickclare/apache2-conf
|
ecc6321cbb5d162f30c195d6668968a939be59d5
|
adding magento
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index 8203683..52aa593 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,216 +1,238 @@
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
# Tools-Drinkaware (Rails Passenger, Ruby1.8)
<VirtualHost *:80>
ServerAlias tools.drinkaware.localhost.enableinteractive.co.uk
ServerAlias tools.drinkaware.dev.enableinteractive.co.uk
DocumentRoot "/Users/Shared/Dev/workspace/tools-drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/tools-drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/tools_drinkaware_error.log
CustomLog /opt/local/apache2/logs/tools_drinkaware_access.log combined
RailsBaseURI /
PassengerDefaultUser root
RailsEnv development
# Enable ETag
#FileETag MTime Size
# Enable Compression (GZIP) of shown content-types
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/xhtml+xml application/javascript
# enable expirations
ExpiresActive On
# far future expires headers
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
ExpiresDefault "access plus 10 years"
</FilesMatch>
</VirtualHost>
+############################
+# Magento Sandbox local
+<VirtualHost *:80>
+ ServerName magento.localhost
+ DocumentRoot "/Users/Shared/Dev/workspace/magento"
+ DirectoryIndex index.php
+ <Directory "/Users/Shared/Dev/workspace/magento">
+ AllowOverride All
+ Allow from All
+ </Directory>
+ ErrorLog /opt/local/apache2/logs/magento_error.log
+ CustomLog /opt/local/apache2/logs/magento_access.log combined
+ php_flag log_errors on
+ php_value error_log /opt/local/apache2/logs/magento_php_error.log
+ php_flag display_errors on
+
+ # E_ALL & ~E_NOTICE
+ php_value error_reporting 6135
+</VirtualHost>
+
+
+
# Because it's Good (Rails Passenger)
# <VirtualHost *:80>
# ServerName because-enable.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/because-enable/public"
# <Directory "/Users/Shared/Dev/workspace/because-enable/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/because-enable_error.log
# CustomLog /opt/local/apache2/logs/because-enable_access.log combined
# RailsBaseURI /
# RailsEnv staging
# </VirtualHost>
# Football Prototype (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName fans.drinkaware.co.uk
# ServerAlias wvvw.drinkaware.co.uk
# DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
# <Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
# Redmine (Rails Passenger)
# <VirtualHost *:80>
# ServerName redmine.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/redmine/public"
# <Directory "/Users/Shared/Dev/workspace/redmine/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/redmine_error.log
# CustomLog /opt/local/apache2/logs/redmine_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
# Ultimate Day (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName ultimateday.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development_mysql
# </VirtualHost>
############################
# YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
<VirtualHost *:80>
ServerName drinkdiary.localhost
DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
DirectoryIndex index.php
<Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
AllowOverride All
Allow from All
#AuthType Basic
#AuthName "Restricted Files"
#AuthUserFile /usr/local/apache/passwd/passwords
#Require user rick
</Directory>
ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
php_flag log_errors on
php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
php_flag display_errors on
# E_ALL & ~E_NOTICE
php_value error_reporting 6135
</VirtualHost>
############################
# Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkware Sandbox local
#<VirtualHost *:80>
# ServerName drinkaware.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
# DirectoryIndex index.php index.html
# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
#</VirtualHost>
############################
# Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
diff --git a/extra/mod_php.conf b/extra/mod_php.conf
deleted file mode 100755
index f51b0df..0000000
--- a/extra/mod_php.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-<IfModule mod_php5.c>
-
-AddType application/x-httpd-php .php
-AddType application/x-httpd-php-source .phps
-
-</IfModule>
diff --git a/httpd.conf.bak b/httpd.conf.bak
index ae06288..1146f6f 100644
--- a/httpd.conf.bak
+++ b/httpd.conf.bak
@@ -1,510 +1,499 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
# server as "/opt/local/apache2/logs/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/opt/local/apache2"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule php5_module modules/libphp5.so
-LoadModule passenger_module /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so
-PassengerRoot /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5
-PassengerRuby /opt/local/bin/ruby
+LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
+PassengerRoot /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9
+PassengerRuby /Users/rick/.rvm/bin/ruby-1.8.7-p249
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User rick
Group wheel
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/opt/local/apache2/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/opt/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
#
# The following lines prevent .htaccess files from being viewed by
# Web clients. Since .htaccess files often contain authorization
# information, access is disallowed for security reasons. Comment
# these lines out if you want Web visitors to see the contents of
# .htaccess files.
#
# Also, folks tend to use names such as .htpasswd for password
# files, so this will protect those as well.
#
<Files ~ "^<.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</Files>
#
# Apple specific filesystem protection.
#
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<Directory ~ ".\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</Directory>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock logs/cgisock
</IfModule>
#
# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/opt/local/apache2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
Include conf/extra/httpd-info.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
-
-# Uncomment following lines to enable Compression (GZIP) of shown content-types
-AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/xhtml+xml application/javascript
-
-# enable expirations
-ExpiresActive On
-
-# far future expires headers
-<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
- ExpiresDefault "access plus 10 years"
-</FilesMatch>
|
rickclare/apache2-conf
|
63f17cfa332fc326307d548d8b65a8a6db54f275
|
updating passenger
|
diff --git a/httpd.conf b/httpd.conf
index 9a4da23..1146f6f 100644
--- a/httpd.conf
+++ b/httpd.conf
@@ -1,499 +1,499 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
# server as "/opt/local/apache2/logs/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/opt/local/apache2"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule php5_module modules/libphp5.so
LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
PassengerRoot /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9
-PassengerRuby /Users/rick/.rvm/rubies/ruby-1.8.7-p249/bin/ruby
+PassengerRuby /Users/rick/.rvm/bin/ruby-1.8.7-p249
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User rick
Group wheel
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/opt/local/apache2/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/opt/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
#
# The following lines prevent .htaccess files from being viewed by
# Web clients. Since .htaccess files often contain authorization
# information, access is disallowed for security reasons. Comment
# these lines out if you want Web visitors to see the contents of
# .htaccess files.
#
# Also, folks tend to use names such as .htpasswd for password
# files, so this will protect those as well.
#
<Files ~ "^<.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</Files>
#
# Apple specific filesystem protection.
#
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<Directory ~ ".\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</Directory>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock logs/cgisock
</IfModule>
#
# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/opt/local/apache2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
Include conf/extra/httpd-info.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
|
rickclare/apache2-conf
|
6c5bba8cdfc13fde6c980f02d94f0fbc3a745e0c
|
updating to use rvm
|
diff --git a/httpd.conf b/httpd.conf
index c9624bd..9a4da23 100644
--- a/httpd.conf
+++ b/httpd.conf
@@ -1,502 +1,499 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
# server as "/opt/local/apache2/logs/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/opt/local/apache2"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule php5_module modules/libphp5.so
-LoadModule passenger_module /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
-PassengerRoot /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.9
-PassengerRuby /opt/local/bin/ruby1.8
-#LoadModule passenger_module /opt/local/lib/ruby1.9/gems/1.9.1/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
-#PassengerRoot /opt/local/lib/ruby1.9/gems/1.9.1/gems/passenger-2.2.9
-#PassengerRuby /opt/local/bin/ruby1.9
+LoadModule passenger_module /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
+PassengerRoot /Users/rick/.rvm/gems/ruby-1.8.7-p249/gems/passenger-2.2.9
+PassengerRuby /Users/rick/.rvm/rubies/ruby-1.8.7-p249/bin/ruby
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User rick
Group wheel
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/opt/local/apache2/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/opt/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
#
# The following lines prevent .htaccess files from being viewed by
# Web clients. Since .htaccess files often contain authorization
# information, access is disallowed for security reasons. Comment
# these lines out if you want Web visitors to see the contents of
# .htaccess files.
#
# Also, folks tend to use names such as .htpasswd for password
# files, so this will protect those as well.
#
<Files ~ "^<.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</Files>
#
# Apple specific filesystem protection.
#
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<Directory ~ ".\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</Directory>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock logs/cgisock
</IfModule>
#
# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/opt/local/apache2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
Include conf/extra/httpd-info.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
|
rickclare/apache2-conf
|
7c3af1e7a6ffe8280954f8fe64e3c293c5a603eb
|
updating to passenger 2.2.9
|
diff --git a/httpd.conf b/httpd.conf
index a64f305..c9624bd 100644
--- a/httpd.conf
+++ b/httpd.conf
@@ -1,502 +1,502 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
# server as "/opt/local/apache2/logs/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/opt/local/apache2"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule php5_module modules/libphp5.so
-LoadModule passenger_module /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so
-PassengerRoot /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5
-PassengerRuby /opt/local/bin/ruby
+LoadModule passenger_module /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
+PassengerRoot /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.9
+PassengerRuby /opt/local/bin/ruby1.8
#LoadModule passenger_module /opt/local/lib/ruby1.9/gems/1.9.1/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
#PassengerRoot /opt/local/lib/ruby1.9/gems/1.9.1/gems/passenger-2.2.9
#PassengerRuby /opt/local/bin/ruby1.9
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User rick
Group wheel
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/opt/local/apache2/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/opt/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
#
# The following lines prevent .htaccess files from being viewed by
# Web clients. Since .htaccess files often contain authorization
# information, access is disallowed for security reasons. Comment
# these lines out if you want Web visitors to see the contents of
# .htaccess files.
#
# Also, folks tend to use names such as .htpasswd for password
# files, so this will protect those as well.
#
<Files ~ "^<.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</Files>
#
# Apple specific filesystem protection.
#
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<Directory ~ ".\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</Directory>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock logs/cgisock
</IfModule>
#
# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/opt/local/apache2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
Include conf/extra/httpd-info.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
|
rickclare/apache2-conf
|
ca205c962585d872a0d75643ccbb5329c7098424
|
updating vhosts
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index aef4187..e0d66dd 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,203 +1,201 @@
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
-# Rails-Drinkaware (Rails Passenger)
+# Tools-Drinkaware (Rails Passenger)
<VirtualHost *:80>
- ServerName rails-drinkaware.localhost
- ServerAlias dev.tools.drinkaware
ServerAlias tools.drinkaware.localhost.enableinteractive.co.uk
ServerAlias tools.drinkaware.dev.enableinteractive.co.uk
- DocumentRoot "/Users/Shared/Dev/workspace/rails-drinkaware/public"
- <Directory "/Users/Shared/Dev/workspace/rails-drinkaware/public">
+ DocumentRoot "/Users/Shared/Dev/workspace/tools-drinkaware/public"
+ <Directory "/Users/Shared/Dev/workspace/tools-drinkaware/public">
AllowOverride All
Allow from All
</Directory>
- ErrorLog /opt/local/apache2/logs/rails_drinkaware_error.log
- CustomLog /opt/local/apache2/logs/rails_drinkaware_access.log combined
+ ErrorLog /opt/local/apache2/logs/tools_drinkaware_error.log
+ CustomLog /opt/local/apache2/logs/tools_drinkaware_access.log combined
RailsBaseURI /
PassengerDefaultUser root
RailsEnv development
</VirtualHost>
# Because it's Good (Rails Passenger)
# <VirtualHost *:80>
# ServerName because-enable.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/because-enable/public"
# <Directory "/Users/Shared/Dev/workspace/because-enable/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/because-enable_error.log
# CustomLog /opt/local/apache2/logs/because-enable_access.log combined
# RailsBaseURI /
# RailsEnv staging
# </VirtualHost>
# Football Prototype (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName fans.drinkaware.co.uk
# ServerAlias wvvw.drinkaware.co.uk
# DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
# <Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
# Redmine (Rails Passenger)
# <VirtualHost *:80>
# ServerName redmine.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/redmine/public"
# <Directory "/Users/Shared/Dev/workspace/redmine/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/redmine_error.log
# CustomLog /opt/local/apache2/logs/redmine_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
# Ultimate Day (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName ultimateday.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development_mysql
# </VirtualHost>
############################
# YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
<VirtualHost *:80>
ServerName drinkdiary.localhost
DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
DirectoryIndex index.php
<Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
AllowOverride All
Allow from All
#AuthType Basic
#AuthName "Restricted Files"
#AuthUserFile /usr/local/apache/passwd/passwords
#Require user rick
</Directory>
ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
php_flag log_errors on
php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
php_flag display_errors on
# E_ALL & ~E_NOTICE
php_value error_reporting 6135
</VirtualHost>
############################
# Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkware Sandbox local
#<VirtualHost *:80>
# ServerName drinkaware.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
# DirectoryIndex index.php index.html
# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
#</VirtualHost>
############################
# Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
|
rickclare/apache2-conf
|
1a8af13b5b5fd8abebf69e48d5997009af3e4f39
|
updating passenger to ruby1.9
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index 60e2d1c..aef4187 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,200 +1,203 @@
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
-# Football (Drinkaware) (Rails Passenger)
+# Rails-Drinkaware (Rails Passenger)
<VirtualHost *:80>
ServerName rails-drinkaware.localhost
+ ServerAlias dev.tools.drinkaware
+ ServerAlias tools.drinkaware.localhost.enableinteractive.co.uk
+ ServerAlias tools.drinkaware.dev.enableinteractive.co.uk
DocumentRoot "/Users/Shared/Dev/workspace/rails-drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/rails-drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/rails_drinkaware_error.log
CustomLog /opt/local/apache2/logs/rails_drinkaware_access.log combined
RailsBaseURI /
PassengerDefaultUser root
RailsEnv development
</VirtualHost>
# Because it's Good (Rails Passenger)
# <VirtualHost *:80>
# ServerName because-enable.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/because-enable/public"
# <Directory "/Users/Shared/Dev/workspace/because-enable/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/because-enable_error.log
# CustomLog /opt/local/apache2/logs/because-enable_access.log combined
# RailsBaseURI /
# RailsEnv staging
# </VirtualHost>
# Football Prototype (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName fans.drinkaware.co.uk
# ServerAlias wvvw.drinkaware.co.uk
# DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
# <Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
# Redmine (Rails Passenger)
# <VirtualHost *:80>
# ServerName redmine.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/redmine/public"
# <Directory "/Users/Shared/Dev/workspace/redmine/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/redmine_error.log
# CustomLog /opt/local/apache2/logs/redmine_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
# Ultimate Day (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName ultimateday.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development_mysql
# </VirtualHost>
############################
# YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
<VirtualHost *:80>
ServerName drinkdiary.localhost
DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
DirectoryIndex index.php
<Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
AllowOverride All
Allow from All
#AuthType Basic
#AuthName "Restricted Files"
#AuthUserFile /usr/local/apache/passwd/passwords
#Require user rick
</Directory>
ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
php_flag log_errors on
php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
php_flag display_errors on
# E_ALL & ~E_NOTICE
php_value error_reporting 6135
</VirtualHost>
############################
# Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkware Sandbox local
#<VirtualHost *:80>
# ServerName drinkaware.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
# DirectoryIndex index.php index.html
# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
#</VirtualHost>
############################
# Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
diff --git a/httpd.conf b/httpd.conf
index ae06288..fd43f36 100644
--- a/httpd.conf
+++ b/httpd.conf
@@ -1,510 +1,513 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
# server as "/opt/local/apache2/logs/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/opt/local/apache2"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule php5_module modules/libphp5.so
-LoadModule passenger_module /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so
-PassengerRoot /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5
-PassengerRuby /opt/local/bin/ruby
+#LoadModule passenger_module /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so
+#PassengerRoot /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5
+#PassengerRuby /opt/local/bin/ruby
+LoadModule passenger_module /opt/local/lib/ruby1.9/gems/1.9.1/gems/passenger-2.2.9/ext/apache2/mod_passenger.so
+PassengerRoot /opt/local/lib/ruby1.9/gems/1.9.1/gems/passenger-2.2.9
+PassengerRuby /opt/local/bin/ruby1.9
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User rick
Group wheel
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/opt/local/apache2/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/opt/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
#
# The following lines prevent .htaccess files from being viewed by
# Web clients. Since .htaccess files often contain authorization
# information, access is disallowed for security reasons. Comment
# these lines out if you want Web visitors to see the contents of
# .htaccess files.
#
# Also, folks tend to use names such as .htpasswd for password
# files, so this will protect those as well.
#
<Files ~ "^<.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</Files>
#
# Apple specific filesystem protection.
#
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<Directory ~ ".\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</Directory>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock logs/cgisock
</IfModule>
#
# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/opt/local/apache2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
Include conf/extra/httpd-info.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
# Uncomment following lines to enable Compression (GZIP) of shown content-types
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/xhtml+xml application/javascript
# enable expirations
ExpiresActive On
# far future expires headers
<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
ExpiresDefault "access plus 10 years"
</FilesMatch>
diff --git a/original/httpd.conf b/original/httpd.conf
index 68ba8ad..d6d6236 100644
--- a/original/httpd.conf
+++ b/original/httpd.conf
@@ -1,480 +1,481 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
# server as "/opt/local/apache2/logs/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/opt/local/apache2"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
+LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User www
Group www
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/opt/local/apache2/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/opt/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html
</IfModule>
#
# The following lines prevent .htaccess, .htpasswd and .DS_Store files and
# Mac resource forks and named forks from being viewed by Web clients.
#
<Files ~ "^\.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</Files>
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<DirectoryMatch ".*\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</DirectoryMatch>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock logs/cgisock
</IfModule>
#
# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/opt/local/apache2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
#Include conf/extra/httpd-info.conf
# Virtual hosts
#Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
|
rickclare/apache2-conf
|
9a60006c5ba39696b89d7df71589af0fb2fa4f9b
|
configuring v-hosts
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index 86d615c..60e2d1c 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,200 +1,200 @@
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
# Football (Drinkaware) (Rails Passenger)
<VirtualHost *:80>
ServerName rails-drinkaware.localhost
- ServerAlias football.drinkaware.localhost
DocumentRoot "/Users/Shared/Dev/workspace/rails-drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/rails-drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/rails_drinkaware_error.log
CustomLog /opt/local/apache2/logs/rails_drinkaware_access.log combined
RailsBaseURI /
+ PassengerDefaultUser root
RailsEnv development
</VirtualHost>
# Because it's Good (Rails Passenger)
# <VirtualHost *:80>
# ServerName because-enable.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/because-enable/public"
# <Directory "/Users/Shared/Dev/workspace/because-enable/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/because-enable_error.log
# CustomLog /opt/local/apache2/logs/because-enable_access.log combined
# RailsBaseURI /
# RailsEnv staging
# </VirtualHost>
# Football Prototype (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName fans.drinkaware.co.uk
# ServerAlias wvvw.drinkaware.co.uk
# DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
# <Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
# Redmine (Rails Passenger)
# <VirtualHost *:80>
# ServerName redmine.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/redmine/public"
# <Directory "/Users/Shared/Dev/workspace/redmine/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/redmine_error.log
# CustomLog /opt/local/apache2/logs/redmine_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
# Ultimate Day (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName ultimateday.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development_mysql
# </VirtualHost>
############################
# YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
-# <VirtualHost *:80>
-# ServerName drinkdiary.localhost
-# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
-#
-# DirectoryIndex index.php
-# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
-# AllowOverride All
-# Allow from All
-# #AuthType Basic
-# #AuthName "Restricted Files"
-# #AuthUserFile /usr/local/apache/passwd/passwords
-# #Require user rick
-# </Directory>
-# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
-# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
-# php_flag log_errors on
-# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
-# php_flag display_errors on
-#
-# # E_ALL & ~E_NOTICE
-# php_value error_reporting 6135
-# </VirtualHost>
+<VirtualHost *:80>
+ ServerName drinkdiary.localhost
+ DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
+
+ DirectoryIndex index.php
+ <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
+ AllowOverride All
+ Allow from All
+ #AuthType Basic
+ #AuthName "Restricted Files"
+ #AuthUserFile /usr/local/apache/passwd/passwords
+ #Require user rick
+ </Directory>
+ ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
+ CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
+ php_flag log_errors on
+ php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
+ php_flag display_errors on
+
+ # E_ALL & ~E_NOTICE
+ php_value error_reporting 6135
+</VirtualHost>
############################
# Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkware Sandbox local
#<VirtualHost *:80>
# ServerName drinkaware.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
# DirectoryIndex index.php index.html
# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
#</VirtualHost>
############################
# Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
diff --git a/extras-conf/mod_php.conf b/extras-conf/mod_php.conf
deleted file mode 100755
index f51b0df..0000000
--- a/extras-conf/mod_php.conf
+++ /dev/null
@@ -1,6 +0,0 @@
-<IfModule mod_php5.c>
-
-AddType application/x-httpd-php .php
-AddType application/x-httpd-php-source .phps
-
-</IfModule>
|
rickclare/apache2-conf
|
488ca84bec76038dc66c09338c64b6c0c1b7c95d
|
disabling some vhosts
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index 464546b..86d615c 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,200 +1,200 @@
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
# Football (Drinkaware) (Rails Passenger)
<VirtualHost *:80>
ServerName rails-drinkaware.localhost
ServerAlias football.drinkaware.localhost
DocumentRoot "/Users/Shared/Dev/workspace/rails-drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/rails-drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/rails_drinkaware_error.log
CustomLog /opt/local/apache2/logs/rails_drinkaware_access.log combined
RailsBaseURI /
RailsEnv development
</VirtualHost>
# Because it's Good (Rails Passenger)
# <VirtualHost *:80>
# ServerName because-enable.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/because-enable/public"
# <Directory "/Users/Shared/Dev/workspace/because-enable/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/because-enable_error.log
# CustomLog /opt/local/apache2/logs/because-enable_access.log combined
# RailsBaseURI /
# RailsEnv staging
# </VirtualHost>
# Football Prototype (Drinkaware) (Rails Passenger)
-<VirtualHost *:80>
- ServerName fans.drinkaware.co.uk
- ServerAlias wvvw.drinkaware.co.uk
- DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
- <Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
- AllowOverride All
- Allow from All
- </Directory>
- ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
- CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
- RailsBaseURI /
- RailsEnv development
-</VirtualHost>
+# <VirtualHost *:80>
+# ServerName fans.drinkaware.co.uk
+# ServerAlias wvvw.drinkaware.co.uk
+# DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
+# <Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
+# AllowOverride All
+# Allow from All
+# </Directory>
+# ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
+# CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
+# RailsBaseURI /
+# RailsEnv development
+# </VirtualHost>
# Redmine (Rails Passenger)
# <VirtualHost *:80>
# ServerName redmine.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/redmine/public"
# <Directory "/Users/Shared/Dev/workspace/redmine/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/redmine_error.log
# CustomLog /opt/local/apache2/logs/redmine_access.log combined
# RailsBaseURI /
# RailsEnv development
# </VirtualHost>
# Ultimate Day (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName ultimateday.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development_mysql
# </VirtualHost>
############################
# YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
-<VirtualHost *:80>
- ServerName drinkdiary.localhost
- DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
-
- DirectoryIndex index.php
- <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
- AllowOverride All
- Allow from All
- #AuthType Basic
- #AuthName "Restricted Files"
- #AuthUserFile /usr/local/apache/passwd/passwords
- #Require user rick
- </Directory>
- ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
- CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
- php_flag log_errors on
- php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
- php_flag display_errors on
-
- # E_ALL & ~E_NOTICE
- php_value error_reporting 6135
-</VirtualHost>
+# <VirtualHost *:80>
+# ServerName drinkdiary.localhost
+# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
+#
+# DirectoryIndex index.php
+# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
+# AllowOverride All
+# Allow from All
+# #AuthType Basic
+# #AuthName "Restricted Files"
+# #AuthUserFile /usr/local/apache/passwd/passwords
+# #Require user rick
+# </Directory>
+# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
+# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
+# php_flag log_errors on
+# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
+# php_flag display_errors on
+#
+# # E_ALL & ~E_NOTICE
+# php_value error_reporting 6135
+# </VirtualHost>
############################
# Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkware Sandbox local
#<VirtualHost *:80>
# ServerName drinkaware.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
# DirectoryIndex index.php index.html
# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
#</VirtualHost>
############################
# Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
|
rickclare/apache2-conf
|
dc76fb7cc0a0c63a6f3c19703e82945f328ec774
|
adding expires and more gzip
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index 00a817b..ee38b2c 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,186 +1,186 @@
#
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
# Football (Drinkaware) (Rails Passenger)
<VirtualHost *:80>
ServerName rails-drinkaware.localhost
ServerAlias football.drinkaware.localhost
DocumentRoot "/Users/Shared/Dev/workspace/rails-drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/rails-drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/rails_drinkaware_error.log
CustomLog /opt/local/apache2/logs/rails_drinkaware_access.log combined
RailsBaseURI /
RailsEnv development
</VirtualHost>
# Because it's Good (Rails Passenger)
# <VirtualHost *:80>
# ServerName because-enable.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/because-enable/public"
# <Directory "/Users/Shared/Dev/workspace/because-enable/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/because-enable_error.log
# CustomLog /opt/local/apache2/logs/because-enable_access.log combined
# RailsBaseURI /
# RailsEnv staging
# </VirtualHost>
# Football Prototype (Drinkaware) (Rails Passenger)
<VirtualHost *:80>
ServerName fans.drinkaware.co.uk
ServerAlias wvvw.drinkaware.co.uk
DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
RailsBaseURI /
RailsEnv development
</VirtualHost>
# Ultimate Day (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName ultimateday.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development_mysql
# </VirtualHost>
############################
# YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
-# <VirtualHost *:80>
-# ServerName drinkdiary.localhost
-# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
-#
-# DirectoryIndex index.php
-# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
-# AllowOverride All
-# Allow from All
-# #AuthType Basic
-# #AuthName "Restricted Files"
-# #AuthUserFile /usr/local/apache/passwd/passwords
-# #Require user rick
-# </Directory>
-# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
-# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
-# php_flag log_errors on
-# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
-# php_flag display_errors on
-#
-# # E_ALL & ~E_NOTICE
-# php_value error_reporting 6135
-# </VirtualHost>
+<VirtualHost *:80>
+ ServerName drinkdiary.localhost
+ DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
+
+ DirectoryIndex index.php
+ <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
+ AllowOverride All
+ Allow from All
+ #AuthType Basic
+ #AuthName "Restricted Files"
+ #AuthUserFile /usr/local/apache/passwd/passwords
+ #Require user rick
+ </Directory>
+ ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
+ CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
+ php_flag log_errors on
+ php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
+ php_flag display_errors on
+
+ # E_ALL & ~E_NOTICE
+ php_value error_reporting 6135
+</VirtualHost>
############################
# Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkware Sandbox local
#<VirtualHost *:80>
# ServerName drinkaware.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
# DirectoryIndex index.php index.html
# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
#</VirtualHost>
############################
# Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
diff --git a/httpd.conf b/httpd.conf
index d41440e..ae06288 100644
--- a/httpd.conf
+++ b/httpd.conf
@@ -1,502 +1,510 @@
#
# This is the main Apache HTTP server configuration file. It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do. They're here only as hints or reminders. If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path. If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
# server as "/opt/local/apache2/logs/foo_log".
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path. If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk. If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/opt/local/apache2"
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80
#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule cache_module modules/mod_cache.so
LoadModule disk_cache_module modules/mod_disk_cache.so
LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule include_module modules/mod_include.so
LoadModule filter_module modules/mod_filter.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule logio_module modules/mod_logio.so
LoadModule env_module modules/mod_env.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule expires_module modules/mod_expires.so
LoadModule headers_module modules/mod_headers.so
LoadModule ident_module modules/mod_ident.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule version_module modules/mod_version.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule mime_module modules/mod_mime.so
LoadModule dav_module modules/mod_dav.so
LoadModule status_module modules/mod_status.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule asis_module modules/mod_asis.so
LoadModule info_module modules/mod_info.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule dir_module modules/mod_dir.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule actions_module modules/mod_actions.so
LoadModule speling_module modules/mod_speling.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule alias_module modules/mod_alias.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule php5_module modules/libphp5.so
LoadModule passenger_module /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so
PassengerRoot /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5
PassengerRuby /opt/local/bin/ruby
<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>
#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User rick
Group wheel
</IfModule>
</IfModule>
# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition. These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed. This address appears on some server-generated pages, such
# as error documents. e.g. admin@your-domain.com
#
ServerAdmin you@example.com
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/opt/local/apache2/htdocs"
#
# Each directory to which Apache has access can be configured with respect
# to which services and features are allowed and/or disabled in that
# directory (and its subdirectories).
#
# First, we configure the "default" to be a very restrictive set of
# features.
#
<Directory />
Options FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#
#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/opt/local/apache2/htdocs">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride None
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
#
# The following lines prevent .htaccess files from being viewed by
# Web clients. Since .htaccess files often contain authorization
# information, access is disallowed for security reasons. Comment
# these lines out if you want Web visitors to see the contents of
# .htaccess files.
#
# Also, folks tend to use names such as .htpasswd for password
# files, so this will protect those as well.
#
<Files ~ "^<.([Hh][Tt]|[Dd][Ss]_[Ss])">
Order allow,deny
Deny from all
Satisfy All
</Files>
#
# Apple specific filesystem protection.
#
<Files "rsrc">
Order allow,deny
Deny from all
Satisfy All
</Files>
<Directory ~ ".\.\.namedfork">
Order allow,deny
Deny from all
Satisfy All
</Directory>
#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
<IfModule logio_module>
# You need to enable mod_logio.c to use %I and %O
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>
#
# The location and format of the access logfile (Common Logfile Format).
# If you do not define any access logfiles within a <VirtualHost>
# container, they will be logged here. Contrariwise, if you *do*
# define per-<VirtualHost> access logfiles, transactions will be
# logged therein and *not* in this file.
#
CustomLog "logs/access_log" common
#
# If you prefer a logfile with access, agent, and referer information
# (Combined Logfile Format) you can use the following directive.
#
#CustomLog "logs/access_log" combined
</IfModule>
<IfModule alias_module>
#
# Redirect: Allows you to tell clients about documents that used to
# exist in your server's namespace, but do not anymore. The client
# will make a new request for the document at its new location.
# Example:
# Redirect permanent /foo http://www.example.com/bar
#
# Alias: Maps web paths into filesystem paths and is used to
# access content that does not live under the DocumentRoot.
# Example:
# Alias /webpath /full/filesystem/path
#
# If you include a trailing / on /webpath then the server will
# require it to be present in the URL. You will also likely
# need to provide a <Directory> section to allow access to
# the filesystem path.
#
# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client. The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
</IfModule>
<IfModule cgid_module>
#
# ScriptSock: On threaded servers, designate the path to the UNIX
# socket used to communicate with the CGI daemon of mod_cgid.
#
#Scriptsock logs/cgisock
</IfModule>
#
# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/opt/local/apache2/cgi-bin">
AllowOverride None
Options None
Order allow,deny
Allow from all
</Directory>
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value. If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module>
#
# TypesConfig points to the file containing the list of mappings from
# filename extension to MIME-type.
#
TypesConfig conf/mime.types
#
# AddType allows you to add to or override the MIME configuration
# file specified in TypesConfig for specific file types.
#
#AddType application/x-gzip .tgz
#
# AddEncoding allows you to have certain browsers uncompress
# information on the fly. Note: Not all browsers support this.
#
#AddEncoding x-compress .Z
#AddEncoding x-gzip .gz .tgz
#
# If the AddEncoding directives above are commented-out, then you
# probably should define those extensions to indicate media types:
#
AddType application/x-compress .Z
AddType application/x-gzip .gz .tgz
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
#
# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
#AddHandler cgi-script .cgi
# For type maps (negotiated resources):
#AddHandler type-map var
#
# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml
</IfModule>
#
# The mod_mime_magic module allows the server to use various hints from the
# contents of the file itself to determine its type. The MIMEMagicFile
# directive tells the module where the hint definitions are located.
#
#MIMEMagicFile conf/magic
#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#
#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall is used to deliver
# files. This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
#
#EnableMMAP off
#EnableSendfile off
# Supplemental configuration
#
# The configuration files in the conf/extra/ directory can be
# included to add extra features or to modify the default configuration of
# the server, or you may simply copy their contents here and change as
# necessary.
# Server-pool management (MPM specific)
#Include conf/extra/httpd-mpm.conf
# Multi-language error messages
#Include conf/extra/httpd-multilang-errordoc.conf
# Fancy directory listings
#Include conf/extra/httpd-autoindex.conf
# Language settings
#Include conf/extra/httpd-languages.conf
# User home directories
#Include conf/extra/httpd-userdir.conf
# Real-time info on requests and configuration
Include conf/extra/httpd-info.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf
# Local access to the Apache HTTP Server Manual
#Include conf/extra/httpd-manual.conf
# Distributed authoring and versioning (WebDAV)
#Include conf/extra/httpd-dav.conf
# Various default settings
#Include conf/extra/httpd-default.conf
# Secure (SSL/TLS) connections
#Include conf/extra/httpd-ssl.conf
#
# Note: The following must must be present to support
# starting without SSL on platforms with no /dev/random equivalent
# but a statically compiled-in mod_ssl.
#
<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>
# Uncomment following lines to enable Compression (GZIP) of shown content-types
-#AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xhtml+xml application/javascript
+AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/xhtml+xml application/javascript
+
+# enable expirations
+ExpiresActive On
+
+# far future expires headers
+<FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
+ ExpiresDefault "access plus 10 years"
+</FilesMatch>
|
rickclare/apache2-conf
|
35e325c012c904b7987a691395ffb2a09c2188ad
|
adding redmine
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index 00a817b..23f5b1d 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,186 +1,200 @@
-#
+
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
# Football (Drinkaware) (Rails Passenger)
<VirtualHost *:80>
ServerName rails-drinkaware.localhost
ServerAlias football.drinkaware.localhost
DocumentRoot "/Users/Shared/Dev/workspace/rails-drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/rails-drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/rails_drinkaware_error.log
CustomLog /opt/local/apache2/logs/rails_drinkaware_access.log combined
RailsBaseURI /
RailsEnv development
</VirtualHost>
# Because it's Good (Rails Passenger)
# <VirtualHost *:80>
# ServerName because-enable.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/because-enable/public"
# <Directory "/Users/Shared/Dev/workspace/because-enable/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/because-enable_error.log
# CustomLog /opt/local/apache2/logs/because-enable_access.log combined
# RailsBaseURI /
# RailsEnv staging
# </VirtualHost>
# Football Prototype (Drinkaware) (Rails Passenger)
<VirtualHost *:80>
ServerName fans.drinkaware.co.uk
ServerAlias wvvw.drinkaware.co.uk
DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
RailsBaseURI /
RailsEnv development
</VirtualHost>
+# Redmine (Rails Passenger)
+# <VirtualHost *:80>
+# ServerName redmine.localhost
+# DocumentRoot "/Users/Shared/Dev/workspace/redmine/public"
+# <Directory "/Users/Shared/Dev/workspace/redmine/public">
+# AllowOverride All
+# Allow from All
+# </Directory>
+# ErrorLog /opt/local/apache2/logs/redmine_error.log
+# CustomLog /opt/local/apache2/logs/redmine_access.log combined
+# RailsBaseURI /
+# RailsEnv development
+# </VirtualHost>
+
# Ultimate Day (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName ultimateday.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development_mysql
# </VirtualHost>
############################
# YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
# <VirtualHost *:80>
# ServerName drinkdiary.localhost
# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
#
# DirectoryIndex index.php
# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
# AllowOverride All
# Allow from All
# #AuthType Basic
# #AuthName "Restricted Files"
# #AuthUserFile /usr/local/apache/passwd/passwords
# #Require user rick
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkware Sandbox local
#<VirtualHost *:80>
# ServerName drinkaware.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
# DirectoryIndex index.php index.html
# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
#</VirtualHost>
############################
# Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
|
rickclare/apache2-conf
|
169cd264811fad33ded1eb04ce4e874cbc778cd7
|
changing vhost
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index 738e0ea..00a817b 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,185 +1,186 @@
#
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
# Football (Drinkaware) (Rails Passenger)
<VirtualHost *:80>
- ServerName football-drinkaware.localhost
- DocumentRoot "/Users/Shared/Dev/workspace/football-drinkaware/public"
- <Directory "/Users/Shared/Dev/workspace/football-drinkaware/public">
+ ServerName rails-drinkaware.localhost
+ ServerAlias football.drinkaware.localhost
+ DocumentRoot "/Users/Shared/Dev/workspace/rails-drinkaware/public"
+ <Directory "/Users/Shared/Dev/workspace/rails-drinkaware/public">
AllowOverride All
Allow from All
</Directory>
- ErrorLog /opt/local/apache2/logs/football_drinkaware_error.log
- CustomLog /opt/local/apache2/logs/football_drinkaware_access.log combined
+ ErrorLog /opt/local/apache2/logs/rails_drinkaware_error.log
+ CustomLog /opt/local/apache2/logs/rails_drinkaware_access.log combined
RailsBaseURI /
RailsEnv development
</VirtualHost>
# Because it's Good (Rails Passenger)
# <VirtualHost *:80>
# ServerName because-enable.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/because-enable/public"
# <Directory "/Users/Shared/Dev/workspace/because-enable/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/because-enable_error.log
# CustomLog /opt/local/apache2/logs/because-enable_access.log combined
# RailsBaseURI /
# RailsEnv staging
# </VirtualHost>
# Football Prototype (Drinkaware) (Rails Passenger)
<VirtualHost *:80>
ServerName fans.drinkaware.co.uk
ServerAlias wvvw.drinkaware.co.uk
DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
RailsBaseURI /
RailsEnv development
</VirtualHost>
# Ultimate Day (Drinkaware) (Rails Passenger)
# <VirtualHost *:80>
# ServerName ultimateday.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
# RailsBaseURI /
# RailsEnv development_mysql
# </VirtualHost>
############################
# YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
# <VirtualHost *:80>
# ServerName drinkdiary.localhost
# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
#
# DirectoryIndex index.php
# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
# AllowOverride All
# Allow from All
# #AuthType Basic
# #AuthName "Restricted Files"
# #AuthUserFile /usr/local/apache/passwd/passwords
# #Require user rick
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkware Sandbox local
#<VirtualHost *:80>
# ServerName drinkaware.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
# DirectoryIndex index.php index.html
# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
#</VirtualHost>
############################
# Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
|
rickclare/apache2-conf
|
dffaf911108f3dd413c802a2f476ec38db0ab11f
|
adding mod_php
|
diff --git a/extras-conf/mod_php.conf.mp_1253134950 b/extras-conf/mod_php.conf.mp_1253134950
new file mode 100755
index 0000000..f51b0df
--- /dev/null
+++ b/extras-conf/mod_php.conf.mp_1253134950
@@ -0,0 +1,6 @@
+<IfModule mod_php5.c>
+
+AddType application/x-httpd-php .php
+AddType application/x-httpd-php-source .phps
+
+</IfModule>
|
rickclare/apache2-conf
|
a5c54ed541337c21e93c0e8a1c700e795a9afa20
|
adding football.drinkaware
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index d99cb6c..e269c85 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,157 +1,171 @@
#
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
+# Football (Drinkaware) (Rails Passenger)
+<VirtualHost *:80>
+ ServerName football.drinkaware.localhost
+ DocumentRoot "/Users/Shared/Dev/workspace/football.drinkaware/public"
+ <Directory "/Users/Shared/Dev/workspace/football.drinkaware/public">
+ AllowOverride All
+ Allow from All
+ </Directory>
+ ErrorLog /opt/local/apache2/logs/football_drinkaware_error.log
+ CustomLog /opt/local/apache2/logs/football_drinkaware_access.log combined
+ RailsBaseURI /
+ RailsEnv development
+</VirtualHost>
+
# Football Prototype (Drinkaware) (Rails Passenger)
<VirtualHost *:80>
ServerName fans.drinkaware.co.uk
ServerAlias wvvw.drinkaware.co.uk
DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
RailsBaseURI /
RailsEnv development
</VirtualHost>
# Ultimate Day (Drinkaware) (Rails Passenger)
-<VirtualHost *:80>
- ServerName ultimateday.localhost
- DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
- <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
- AllowOverride All
- Allow from All
- </Directory>
- ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
- CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
- RailsBaseURI /
- RailsEnv development_mysql
-</VirtualHost>
+# <VirtualHost *:80>
+# ServerName ultimateday.localhost
+# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
+# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
+# AllowOverride All
+# Allow from All
+# </Directory>
+# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
+# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
+# RailsBaseURI /
+# RailsEnv development_mysql
+# </VirtualHost>
############################
# YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
# <VirtualHost *:80>
# ServerName drinkdiary.localhost
# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
#
# DirectoryIndex index.php
# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
# AllowOverride All
# Allow from All
# #AuthType Basic
# #AuthName "Restricted Files"
# #AuthUserFile /usr/local/apache/passwd/passwords
# #Require user rick
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkware Sandbox local
#<VirtualHost *:80>
# ServerName drinkaware.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
# DirectoryIndex index.php index.html
# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
#</VirtualHost>
############################
# Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
|
rickclare/apache2-conf
|
2cb134436c8b7506ca9538a29798cfd0b8ced3ca
|
adding football_prototype
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index 1b103be..d99cb6c 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,157 +1,157 @@
#
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
-# Football Drinkaware (Rails Passenger)
+# Football Prototype (Drinkaware) (Rails Passenger)
<VirtualHost *:80>
ServerName fans.drinkaware.co.uk
ServerAlias wvvw.drinkaware.co.uk
- DocumentRoot "/Users/Shared/Dev/workspace/football.drinkaware/public"
- <Directory "/Users/Shared/Dev/workspace/football.drinkaware/public">
+ DocumentRoot "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public"
+ <Directory "/Users/Shared/Dev/workspace/football_prototype.drinkaware/public">
AllowOverride All
Allow from All
</Directory>
- ErrorLog /opt/local/apache2/logs/football_drinkaware_error.log
- CustomLog /opt/local/apache2/logs/football_drinkaware_access.log combined
+ ErrorLog /opt/local/apache2/logs/football_prototype_drinkaware_error.log
+ CustomLog /opt/local/apache2/logs/football_prototype_drinkaware_access.log combined
RailsBaseURI /
RailsEnv development
</VirtualHost>
-# Ultimate Day Drinkaware (Rails Passenger)
-# <VirtualHost *:80>
-# ServerName ultimateday.localhost
-# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
-# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
-# AllowOverride All
-# Allow from All
-# </Directory>
-# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
-# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
-# RailsBaseURI /
-# RailsEnv development_mysql
-# </VirtualHost>
+# Ultimate Day (Drinkaware) (Rails Passenger)
+<VirtualHost *:80>
+ ServerName ultimateday.localhost
+ DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
+ <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
+ AllowOverride All
+ Allow from All
+ </Directory>
+ ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
+ CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
+ RailsBaseURI /
+ RailsEnv development_mysql
+</VirtualHost>
############################
# YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
# <VirtualHost *:80>
# ServerName drinkdiary.localhost
# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
#
# DirectoryIndex index.php
# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
# AllowOverride All
# Allow from All
# #AuthType Basic
# #AuthName "Restricted Files"
# #AuthUserFile /usr/local/apache/passwd/passwords
# #Require user rick
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkware Sandbox local
#<VirtualHost *:80>
# ServerName drinkaware.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
# DirectoryIndex index.php index.html
# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
#</VirtualHost>
############################
# Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
|
rickclare/apache2-conf
|
a1d26e758d109f91ffcd60d11c47803f2e28e42b
|
disabling old v-hosts part 3
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index a6b447d..1b103be 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,143 +1,157 @@
#
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
# Football Drinkaware (Rails Passenger)
<VirtualHost *:80>
ServerName fans.drinkaware.co.uk
ServerAlias wvvw.drinkaware.co.uk
DocumentRoot "/Users/Shared/Dev/workspace/football.drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/football.drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/football_drinkaware_error.log
CustomLog /opt/local/apache2/logs/football_drinkaware_access.log combined
RailsBaseURI /
RailsEnv development
</VirtualHost>
+# Ultimate Day Drinkaware (Rails Passenger)
+# <VirtualHost *:80>
+# ServerName ultimateday.localhost
+# DocumentRoot "/Users/Shared/Dev/workspace/ultimateday/public"
+# <Directory "/Users/Shared/Dev/workspace/ultimateday/public">
+# AllowOverride All
+# Allow from All
+# </Directory>
+# ErrorLog /opt/local/apache2/logs/ultimateday_drinkaware_error.log
+# CustomLog /opt/local/apache2/logs/ultimateday_drinkaware_access.log combined
+# RailsBaseURI /
+# RailsEnv development_mysql
+# </VirtualHost>
+
############################
# YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
# <VirtualHost *:80>
# ServerName drinkdiary.localhost
# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
#
# DirectoryIndex index.php
# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
# AllowOverride All
# Allow from All
# #AuthType Basic
# #AuthName "Restricted Files"
# #AuthUserFile /usr/local/apache/passwd/passwords
# #Require user rick
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkware Sandbox local
#<VirtualHost *:80>
# ServerName drinkaware.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
# DirectoryIndex index.php index.html
# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
#</VirtualHost>
############################
# Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
|
rickclare/apache2-conf
|
5347b1d2ea378e25363904a038797d18fcadc6fd
|
disabling old v-hosts part 2
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index 1ada23a..a6b447d 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,143 +1,143 @@
#
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
+# Football Drinkaware (Rails Passenger)
+<VirtualHost *:80>
+ ServerName fans.drinkaware.co.uk
+ ServerAlias wvvw.drinkaware.co.uk
+ DocumentRoot "/Users/Shared/Dev/workspace/football.drinkaware/public"
+ <Directory "/Users/Shared/Dev/workspace/football.drinkaware/public">
+ AllowOverride All
+ Allow from All
+ </Directory>
+ ErrorLog /opt/local/apache2/logs/football_drinkaware_error.log
+ CustomLog /opt/local/apache2/logs/football_drinkaware_access.log combined
+ RailsBaseURI /
+ RailsEnv development
+</VirtualHost>
+
############################
# YanleyFarm (Joomla) local
# <VirtualHost *:80>
# ServerName yanleyFarm.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Drinkdiary local (PHP, Flash)
# <VirtualHost *:80>
# ServerName drinkdiary.localhost
# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
#
# DirectoryIndex index.php
# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
# AllowOverride All
# Allow from All
# #AuthType Basic
# #AuthName "Restricted Files"
# #AuthUserFile /usr/local/apache/passwd/passwords
# #Require user rick
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
############################
# Homelesslink (Drupal) local
# <VirtualHost *:80>
# ServerName homelesslink.mbp
# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/homelesslink">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# # php_value error_reporting 6135
# </VirtualHost>
-# Football Drinkaware (Rails Passenger)
-<VirtualHost *:80>
- ServerName fans.drinkaware.co.uk
- ServerAlias wvvw.drinkaware.co.uk
- DocumentRoot "/Users/Shared/Dev/workspace/football.drinkaware/public"
- <Directory "/Users/Shared/Dev/workspace/football.drinkaware/public">
- AllowOverride All
- Allow from All
- </Directory>
- ErrorLog /opt/local/apache2/logs/football_drinkaware_error.log
- CustomLog /opt/local/apache2/logs/football_drinkaware_access.log combined
- RailsBaseURI /
- RailsEnv development
-</VirtualHost>
-
############################
# Drinkware Sandbox local
#<VirtualHost *:80>
# ServerName drinkaware.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
# DirectoryIndex index.php index.html
# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
#</VirtualHost>
############################
# Joomla Sandbox local
# <VirtualHost *:80>
# ServerName joomlaSandbox.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
# DirectoryIndex index.php
# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
# </VirtualHost>
|
rickclare/apache2-conf
|
6fe81823deeb153ddbdffc9cceedafe92618b056
|
disabling old v-hosts
|
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
index cf0d3fe..1ada23a 100644
--- a/extra/httpd-vhosts.conf
+++ b/extra/httpd-vhosts.conf
@@ -1,147 +1,143 @@
#
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
NameVirtualHost *:80
-
-
############################
# YanleyFarm (Joomla) local
-<VirtualHost *:80>
- ServerName yanleyFarm.localhost
- DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
- DirectoryIndex index.php
- <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
- AllowOverride All
- Allow from All
- </Directory>
- ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
- CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
- php_flag log_errors on
- php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
- php_flag display_errors on
-
- # E_ALL & ~E_NOTICE
- php_value error_reporting 6135
-</VirtualHost>
+# <VirtualHost *:80>
+# ServerName yanleyFarm.localhost
+# DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
+# DirectoryIndex index.php
+# <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
+# AllowOverride All
+# Allow from All
+# </Directory>
+# ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
+# CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
+# php_flag log_errors on
+# php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
+# php_flag display_errors on
+#
+# # E_ALL & ~E_NOTICE
+# php_value error_reporting 6135
+# </VirtualHost>
+############################
+# Drinkdiary local (PHP, Flash)
+# <VirtualHost *:80>
+# ServerName drinkdiary.localhost
+# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
+#
+# DirectoryIndex index.php
+# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
+# AllowOverride All
+# Allow from All
+# #AuthType Basic
+# #AuthName "Restricted Files"
+# #AuthUserFile /usr/local/apache/passwd/passwords
+# #Require user rick
+# </Directory>
+# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
+# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
+# php_flag log_errors on
+# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
+# php_flag display_errors on
+#
+# # E_ALL & ~E_NOTICE
+# php_value error_reporting 6135
+# </VirtualHost>
############################
-# YanleyFarm (Joomla) local
-<VirtualHost *:80>
- ServerName homelesslink.mbp
- DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
- DirectoryIndex index.php
- <Directory "/Users/Shared/Dev/workspace/homelesslink">
- AllowOverride All
- Allow from All
- </Directory>
- ErrorLog /opt/local/apache2/logs/homelesslink_error.log
- CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
- php_flag log_errors on
- php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
- php_flag display_errors on
-
- # E_ALL & ~E_NOTICE
- # php_value error_reporting 6135
-</VirtualHost>
+# Homelesslink (Drupal) local
+# <VirtualHost *:80>
+# ServerName homelesslink.mbp
+# DocumentRoot "/Users/Shared/Dev/workspace/homelesslink"
+# DirectoryIndex index.php
+# <Directory "/Users/Shared/Dev/workspace/homelesslink">
+# AllowOverride All
+# Allow from All
+# </Directory>
+# ErrorLog /opt/local/apache2/logs/homelesslink_error.log
+# CustomLog /opt/local/apache2/logs/homelesslink_access.log combined
+# php_flag log_errors on
+# php_value error_log /opt/local/apache2/logs/homelesslink_php_error.log
+# php_flag display_errors on
+#
+# # E_ALL & ~E_NOTICE
+# # php_value error_reporting 6135
+# </VirtualHost>
# Football Drinkaware (Rails Passenger)
<VirtualHost *:80>
ServerName fans.drinkaware.co.uk
ServerAlias wvvw.drinkaware.co.uk
DocumentRoot "/Users/Shared/Dev/workspace/football.drinkaware/public"
<Directory "/Users/Shared/Dev/workspace/football.drinkaware/public">
AllowOverride All
Allow from All
</Directory>
ErrorLog /opt/local/apache2/logs/football_drinkaware_error.log
CustomLog /opt/local/apache2/logs/football_drinkaware_access.log combined
RailsBaseURI /
RailsEnv development
</VirtualHost>
############################
# Drinkware Sandbox local
#<VirtualHost *:80>
# ServerName drinkaware.localhost
# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
# DirectoryIndex index.php index.html
# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
# AllowOverride All
# Allow from All
# </Directory>
# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
# php_flag log_errors on
# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
# php_flag display_errors on
#
# # E_ALL & ~E_NOTICE
# php_value error_reporting 6135
#</VirtualHost>
############################
# Joomla Sandbox local
-<VirtualHost *:80>
- ServerName joomlaSandbox.localhost
- DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
- DirectoryIndex index.php
- <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
- AllowOverride All
- Allow from All
- </Directory>
- ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
- CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
- php_flag log_errors on
- php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
- php_flag display_errors on
-
- # E_ALL & ~E_NOTICE
- php_value error_reporting 6135
-</VirtualHost>
-
+# <VirtualHost *:80>
+# ServerName joomlaSandbox.localhost
+# DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
+# DirectoryIndex index.php
+# <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
+# AllowOverride All
+# Allow from All
+# </Directory>
+# ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
+# CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
+# php_flag log_errors on
+# php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
+# php_flag display_errors on
+#
+# # E_ALL & ~E_NOTICE
+# php_value error_reporting 6135
+# </VirtualHost>
-############################
-# Drinkdiary local
-#<VirtualHost *:80>
-# ServerName drinkdiary.localhost
-# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
-#
-# DirectoryIndex index.php
-# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
-# AllowOverride All
-# Allow from All
-#
-# #AuthType Basic
-# #AuthName "Restricted Files"
-# #AuthUserFile /usr/local/apache/passwd/passwords
-# #Require user rick
-# </Directory>
-# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
-# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
-# php_flag log_errors on
-# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
-# php_flag display_errors on
-#
-# # E_ALL & ~E_NOTICE
-# php_value error_reporting 6135
-#</VirtualHost>
|
rickclare/apache2-conf
|
ba3b12513ba9728706c87b82858e715ef599b279
|
first cut
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..90ec22b
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+.svn
diff --git a/extra/.turd_apache2 b/extra/.turd_apache2
new file mode 100644
index 0000000..e69de29
diff --git a/extra/httpd-autoindex.conf b/extra/httpd-autoindex.conf
new file mode 100644
index 0000000..c576178
--- /dev/null
+++ b/extra/httpd-autoindex.conf
@@ -0,0 +1,93 @@
+#
+# Directives controlling the display of server-generated directory listings.
+#
+# Required modules: mod_autoindex, mod_alias
+#
+# To see the listing of a directory, the Options directive for the
+# directory must include "Indexes", and the directory must not contain
+# a file matching those listed in the DirectoryIndex directive.
+#
+
+#
+# IndexOptions: Controls the appearance of server-generated directory
+# listings.
+#
+IndexOptions FancyIndexing HTMLTable VersionSort
+
+# We include the /icons/ alias for FancyIndexed directory listings. If
+# you do not use FancyIndexing, you may comment this out.
+#
+Alias /icons/ "/opt/local/apache2/icons/"
+
+<Directory "/opt/local/apache2/icons">
+ Options Indexes MultiViews
+ AllowOverride None
+ Order allow,deny
+ Allow from all
+</Directory>
+
+#
+# AddIcon* directives tell the server which icon to show for different
+# files or filename extensions. These are only displayed for
+# FancyIndexed directories.
+#
+AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip
+
+AddIconByType (TXT,/icons/text.gif) text/*
+AddIconByType (IMG,/icons/image2.gif) image/*
+AddIconByType (SND,/icons/sound2.gif) audio/*
+AddIconByType (VID,/icons/movie.gif) video/*
+
+AddIcon /icons/binary.gif .bin .exe
+AddIcon /icons/binhex.gif .hqx
+AddIcon /icons/tar.gif .tar
+AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv
+AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip
+AddIcon /icons/a.gif .ps .ai .eps
+AddIcon /icons/layout.gif .html .shtml .htm .pdf
+AddIcon /icons/text.gif .txt
+AddIcon /icons/c.gif .c
+AddIcon /icons/p.gif .pl .py
+AddIcon /icons/f.gif .for
+AddIcon /icons/dvi.gif .dvi
+AddIcon /icons/uuencoded.gif .uu
+AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl
+AddIcon /icons/tex.gif .tex
+AddIcon /icons/bomb.gif core
+
+AddIcon /icons/back.gif ..
+AddIcon /icons/hand.right.gif README
+AddIcon /icons/folder.gif ^^DIRECTORY^^
+AddIcon /icons/blank.gif ^^BLANKICON^^
+
+#
+# DefaultIcon is which icon to show for files which do not have an icon
+# explicitly set.
+#
+DefaultIcon /icons/unknown.gif
+
+#
+# AddDescription allows you to place a short description after a file in
+# server-generated indexes. These are only displayed for FancyIndexed
+# directories.
+# Format: AddDescription "description" filename
+#
+#AddDescription "GZIP compressed document" .gz
+#AddDescription "tar archive" .tar
+#AddDescription "GZIP compressed tar archive" .tgz
+
+#
+# ReadmeName is the name of the README file the server will look for by
+# default, and append to directory listings.
+#
+# HeaderName is the name of a file which should be prepended to
+# directory indexes.
+ReadmeName README.html
+HeaderName HEADER.html
+
+#
+# IndexIgnore is a set of filenames which directory indexing should ignore
+# and not include in the listing. Shell-style wildcarding is permitted.
+#
+IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t
+
diff --git a/extra/httpd-dav.conf b/extra/httpd-dav.conf
new file mode 100644
index 0000000..ab7a136
--- /dev/null
+++ b/extra/httpd-dav.conf
@@ -0,0 +1,52 @@
+#
+# Distributed authoring and versioning (WebDAV)
+#
+# Required modules: mod_dav, mod_dav_fs, mod_setenvif, mod_alias
+# mod_auth_digest, mod_authn_file
+#
+
+# The following example gives DAV write access to a directory called
+# "uploads" under the ServerRoot directory.
+#
+# The User/Group specified in httpd.conf needs to have write permissions
+# on the directory where the DavLockDB is placed and on any directory where
+# "Dav On" is specified.
+
+DavLockDB "/opt/local/apache2/var/DavLock"
+
+Alias /uploads "/opt/local/apache2/uploads"
+
+<Directory "/opt/local/apache2/uploads">
+ Dav On
+
+ Order Allow,Deny
+ Allow from all
+
+ AuthType Digest
+ AuthName DAV-upload
+
+ # You can use the htdigest program to create the password database:
+ # htdigest -c "/opt/local/apache2/user.passwd" DAV-upload admin
+ AuthUserFile "/opt/local/apache2/user.passwd"
+ AuthDigestProvider file
+
+ # Allow universal read-access, but writes are restricted
+ # to the admin user.
+ <LimitExcept GET OPTIONS>
+ require user admin
+ </LimitExcept>
+</Directory>
+
+#
+# The following directives disable redirects on non-GET requests for
+# a directory that does not include the trailing slash. This fixes a
+# problem with several clients that do not appropriately handle
+# redirects for folders with DAV methods.
+#
+BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully
+BrowserMatch "MS FrontPage" redirect-carefully
+BrowserMatch "^WebDrive" redirect-carefully
+BrowserMatch "^WebDAVFS/1.[0123]" redirect-carefully
+BrowserMatch "^gnome-vfs/1.0" redirect-carefully
+BrowserMatch "^XML Spy" redirect-carefully
+BrowserMatch "^Dreamweaver-WebDAV-SCM1" redirect-carefully
diff --git a/extra/httpd-default.conf b/extra/httpd-default.conf
new file mode 100644
index 0000000..efeca05
--- /dev/null
+++ b/extra/httpd-default.conf
@@ -0,0 +1,75 @@
+#
+# This configuration file reflects default settings for Apache HTTP Server.
+#
+# You may change these, but chances are that you may not need to.
+#
+
+#
+# Timeout: The number of seconds before receives and sends time out.
+#
+Timeout 300
+
+#
+# KeepAlive: Whether or not to allow persistent connections (more than
+# one request per connection). Set to "Off" to deactivate.
+#
+KeepAlive On
+
+#
+# MaxKeepAliveRequests: The maximum number of requests to allow
+# during a persistent connection. Set to 0 to allow an unlimited amount.
+# We recommend you leave this number high, for maximum performance.
+#
+MaxKeepAliveRequests 100
+
+#
+# KeepAliveTimeout: Number of seconds to wait for the next request from the
+# same client on the same connection.
+#
+KeepAliveTimeout 5
+
+#
+# UseCanonicalName: Determines how Apache constructs self-referencing
+# URLs and the SERVER_NAME and SERVER_PORT variables.
+# When set "Off", Apache will use the Hostname and Port supplied
+# by the client. When set "On", Apache will use the value of the
+# ServerName directive.
+#
+UseCanonicalName Off
+
+#
+# AccessFileName: The name of the file to look for in each directory
+# for additional configuration directives. See also the AllowOverride
+# directive.
+#
+AccessFileName .htaccess
+
+#
+# ServerTokens
+# This directive configures what you return as the Server HTTP response
+# Header. The default is 'Full' which sends information about the OS-Type
+# and compiled in modules.
+# Set to one of: Full | OS | Minor | Minimal | Major | Prod
+# where Full conveys the most information, and Prod the least.
+#
+ServerTokens Full
+
+#
+# Optionally add a line containing the server version and virtual host
+# name to server-generated pages (internal error documents, FTP directory
+# listings, mod_status and mod_info output etc., but not CGI generated
+# documents or custom error documents).
+# Set to "EMail" to also include a mailto: link to the ServerAdmin.
+# Set to one of: On | Off | EMail
+#
+ServerSignature On
+
+#
+# HostnameLookups: Log the names of clients or just their IP addresses
+# e.g., www.apache.org (on) or 204.62.129.132 (off).
+# The default is off because it'd be overall better for the net if people
+# had to knowingly turn this feature on, since enabling it means that
+# each client request will result in AT LEAST one lookup request to the
+# nameserver.
+#
+HostnameLookups Off
diff --git a/extra/httpd-info.conf b/extra/httpd-info.conf
new file mode 100644
index 0000000..db316c0
--- /dev/null
+++ b/extra/httpd-info.conf
@@ -0,0 +1,37 @@
+#
+# Get information about the requests being processed by the server
+# and the configuration of the server.
+#
+# Required modules: mod_status (for the server-status handler),
+# mod_info (for the server-info handler)
+
+#
+# Allow server status reports generated by mod_status,
+# with the URL of http://servername/server-status
+# Change the ".example.com" to match your domain to enable.
+
+<Location /server-status>
+ SetHandler server-status
+ Order deny,allow
+ Deny from all
+ Allow from .example.com
+</Location>
+
+#
+# ExtendedStatus controls whether Apache will generate "full" status
+# information (ExtendedStatus On) or just basic information (ExtendedStatus
+# Off) when the "server-status" handler is called. The default is Off.
+#
+#ExtendedStatus On
+
+#
+# Allow remote server configuration reports, with the URL of
+# http://servername/server-info (requires that mod_info.c be loaded).
+# Change the ".example.com" to match your domain to enable.
+#
+<Location /server-info>
+ SetHandler server-info
+ Order deny,allow
+ Deny from all
+ Allow from .example.com
+</Location>
diff --git a/extra/httpd-languages.conf b/extra/httpd-languages.conf
new file mode 100644
index 0000000..7f66461
--- /dev/null
+++ b/extra/httpd-languages.conf
@@ -0,0 +1,141 @@
+#
+# Settings for hosting different languages.
+#
+# Required modules: mod_mime, mod_negotiation
+
+# DefaultLanguage and AddLanguage allows you to specify the language of
+# a document. You can then use content negotiation to give a browser a
+# file in a language the user can understand.
+#
+# Specify a default language. This means that all data
+# going out without a specific language tag (see below) will
+# be marked with this one. You probably do NOT want to set
+# this unless you are sure it is correct for all cases.
+#
+# * It is generally better to not mark a page as
+# * being a certain language than marking it with the wrong
+# * language!
+#
+# DefaultLanguage nl
+#
+# Note 1: The suffix does not have to be the same as the language
+# keyword --- those with documents in Polish (whose net-standard
+# language code is pl) may wish to use "AddLanguage pl .po" to
+# avoid the ambiguity with the common suffix for perl scripts.
+#
+# Note 2: The example entries below illustrate that in some cases
+# the two character 'Language' abbreviation is not identical to
+# the two character 'Country' code for its country,
+# E.g. 'Danmark/dk' versus 'Danish/da'.
+#
+# Note 3: In the case of 'ltz' we violate the RFC by using a three char
+# specifier. There is 'work in progress' to fix this and get
+# the reference data for rfc1766 cleaned up.
+#
+# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl)
+# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de)
+# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja)
+# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn)
+# Norwegian (no) - Polish (pl) - Portugese (pt)
+# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv)
+# Turkish (tr) - Simplified Chinese (zh-CN) - Spanish (es)
+# Traditional Chinese (zh-TW)
+#
+AddLanguage ca .ca
+AddLanguage cs .cz .cs
+AddLanguage da .dk
+AddLanguage de .de
+AddLanguage el .el
+AddLanguage en .en
+AddLanguage eo .eo
+AddLanguage es .es
+AddLanguage et .et
+AddLanguage fr .fr
+AddLanguage he .he
+AddLanguage hr .hr
+AddLanguage it .it
+AddLanguage ja .ja
+AddLanguage ko .ko
+AddLanguage ltz .ltz
+AddLanguage nl .nl
+AddLanguage nn .nn
+AddLanguage no .no
+AddLanguage pl .po
+AddLanguage pt .pt
+AddLanguage pt-BR .pt-br
+AddLanguage ru .ru
+AddLanguage sv .sv
+AddLanguage tr .tr
+AddLanguage zh-CN .zh-cn
+AddLanguage zh-TW .zh-tw
+
+# LanguagePriority allows you to give precedence to some languages
+# in case of a tie during content negotiation.
+#
+# Just list the languages in decreasing order of preference. We have
+# more or less alphabetized them here. You probably want to change this.
+#
+LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv tr zh-CN zh-TW
+
+#
+# ForceLanguagePriority allows you to serve a result page rather than
+# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback)
+# [in case no accepted languages matched the available variants]
+#
+ForceLanguagePriority Prefer Fallback
+
+#
+# Commonly used filename extensions to character sets. You probably
+# want to avoid clashes with the language extensions, unless you
+# are good at carefully testing your setup after each change.
+# See http://www.iana.org/assignments/character-sets for the
+# official list of charset names and their respective RFCs.
+#
+AddCharset us-ascii.ascii .us-ascii
+AddCharset ISO-8859-1 .iso8859-1 .latin1
+AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen
+AddCharset ISO-8859-3 .iso8859-3 .latin3
+AddCharset ISO-8859-4 .iso8859-4 .latin4
+AddCharset ISO-8859-5 .iso8859-5 .cyr .iso-ru
+AddCharset ISO-8859-6 .iso8859-6 .arb .arabic
+AddCharset ISO-8859-7 .iso8859-7 .grk .greek
+AddCharset ISO-8859-8 .iso8859-8 .heb .hebrew
+AddCharset ISO-8859-9 .iso8859-9 .latin5 .trk
+AddCharset ISO-8859-10 .iso8859-10 .latin6
+AddCharset ISO-8859-13 .iso8859-13
+AddCharset ISO-8859-14 .iso8859-14 .latin8
+AddCharset ISO-8859-15 .iso8859-15 .latin9
+AddCharset ISO-8859-16 .iso8859-16 .latin10
+AddCharset ISO-2022-JP .iso2022-jp .jis
+AddCharset ISO-2022-KR .iso2022-kr .kis
+AddCharset ISO-2022-CN .iso2022-cn .cis
+AddCharset Big5.Big5 .big5 .b5
+AddCharset cn-Big5 .cn-big5
+# For russian, more than one charset is used (depends on client, mostly):
+AddCharset WINDOWS-1251 .cp-1251 .win-1251
+AddCharset CP866 .cp866
+AddCharset KOI8 .koi8
+AddCharset KOI8-E .koi8-e
+AddCharset KOI8-r .koi8-r .koi8-ru
+AddCharset KOI8-U .koi8-u
+AddCharset KOI8-ru .koi8-uk .ua
+AddCharset ISO-10646-UCS-2 .ucs2
+AddCharset ISO-10646-UCS-4 .ucs4
+AddCharset UTF-7 .utf7
+AddCharset UTF-8 .utf8
+AddCharset UTF-16 .utf16
+AddCharset UTF-16BE .utf16be
+AddCharset UTF-16LE .utf16le
+AddCharset UTF-32 .utf32
+AddCharset UTF-32BE .utf32be
+AddCharset UTF-32LE .utf32le
+AddCharset euc-cn .euc-cn
+AddCharset euc-gb .euc-gb
+AddCharset euc-jp .euc-jp
+AddCharset euc-kr .euc-kr
+#Not sure how euc-tw got in - IANA doesn't list it???
+AddCharset EUC-TW .euc-tw
+AddCharset gb2312 .gb2312 .gb
+AddCharset iso-10646-ucs-2 .ucs-2 .iso-10646-ucs-2
+AddCharset iso-10646-ucs-4 .ucs-4 .iso-10646-ucs-4
+AddCharset shift_jis .shift_jis .sjis
diff --git a/extra/httpd-manual.conf b/extra/httpd-manual.conf
new file mode 100644
index 0000000..71e4fc8
--- /dev/null
+++ b/extra/httpd-manual.conf
@@ -0,0 +1,31 @@
+#
+# Provide access to the documentation on your server as
+# http://yourserver.example.com/manual/
+# The documentation is always available at
+# http://httpd.apache.org/docs/2.2/
+#
+# Required modules: mod_alias, mod_setenvif, mod_negotiation
+#
+
+AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|pt-br|ru|tr))?(/.*)?$ "/opt/local/apache2/manual$1"
+
+<Directory "/opt/local/apache2/manual">
+ Options Indexes
+ AllowOverride None
+ Order allow,deny
+ Allow from all
+
+ <Files *.html>
+ SetHandler type-map
+ </Files>
+ # .tr is text/troff in mime.types!
+ <Files *.html.tr.utf8>
+ ForceType text/html
+ </Files>
+
+ SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|pt-br|ru|tr)/ prefer-language=$1
+ RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|pt-br|ru|tr)){2,}(/.*)?$ /manual/$1$2
+
+ LanguagePriority en de es fr ja ko pt-br ru tr
+ ForceLanguagePriority Prefer Fallback
+</Directory>
diff --git a/extra/httpd-mpm.conf b/extra/httpd-mpm.conf
new file mode 100644
index 0000000..8c44c60
--- /dev/null
+++ b/extra/httpd-mpm.conf
@@ -0,0 +1,110 @@
+#
+# Server-Pool Management (MPM specific)
+#
+
+#
+# PidFile: The file in which the server should record its process
+# identification number when it starts.
+#
+# Note that this is the default PidFile for most MPMs.
+#
+<IfModule !mpm_netware_module>
+ PidFile "logs/httpd.pid"
+</IfModule>
+
+#
+# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
+#
+<IfModule !mpm_winnt_module>
+<IfModule !mpm_netware_module>
+LockFile "logs/accept.lock"
+</IfModule>
+</IfModule>
+
+#
+# Only one of the below sections will be relevant on your
+# installed httpd. Use "apachectl -l" to find out the
+# active mpm.
+#
+
+# prefork MPM
+# StartServers: number of server processes to start
+# MinSpareServers: minimum number of server processes which are kept spare
+# MaxSpareServers: maximum number of server processes which are kept spare
+# MaxClients: maximum number of server processes allowed to start
+# MaxRequestsPerChild: maximum number of requests a server process serves
+<IfModule mpm_prefork_module>
+ StartServers 5
+ MinSpareServers 5
+ MaxSpareServers 10
+ MaxClients 150
+ MaxRequestsPerChild 0
+</IfModule>
+
+# worker MPM
+# StartServers: initial number of server processes to start
+# MaxClients: maximum number of simultaneous client connections
+# MinSpareThreads: minimum number of worker threads which are kept spare
+# MaxSpareThreads: maximum number of worker threads which are kept spare
+# ThreadsPerChild: constant number of worker threads in each server process
+# MaxRequestsPerChild: maximum number of requests a server process serves
+<IfModule mpm_worker_module>
+ StartServers 2
+ MaxClients 150
+ MinSpareThreads 25
+ MaxSpareThreads 75
+ ThreadsPerChild 25
+ MaxRequestsPerChild 0
+</IfModule>
+
+# BeOS MPM
+# StartThreads: how many threads do we initially spawn?
+# MaxClients: max number of threads we can have (1 thread == 1 client)
+# MaxRequestsPerThread: maximum number of requests each thread will process
+<IfModule mpm_beos_module>
+ StartThreads 10
+ MaxClients 50
+ MaxRequestsPerThread 10000
+</IfModule>
+
+# NetWare MPM
+# ThreadStackSize: Stack size allocated for each worker thread
+# StartThreads: Number of worker threads launched at server startup
+# MinSpareThreads: Minimum number of idle threads, to handle request spikes
+# MaxSpareThreads: Maximum number of idle threads
+# MaxThreads: Maximum number of worker threads alive at the same time
+# MaxRequestsPerChild: Maximum number of requests a thread serves. It is
+# recommended that the default value of 0 be set for this
+# directive on NetWare. This will allow the thread to
+# continue to service requests indefinitely.
+<IfModule mpm_netware_module>
+ ThreadStackSize 65536
+ StartThreads 250
+ MinSpareThreads 25
+ MaxSpareThreads 250
+ MaxThreads 1000
+ MaxRequestsPerChild 0
+ MaxMemFree 100
+</IfModule>
+
+# OS/2 MPM
+# StartServers: Number of server processes to maintain
+# MinSpareThreads: Minimum number of idle threads per process,
+# to handle request spikes
+# MaxSpareThreads: Maximum number of idle threads per process
+# MaxRequestsPerChild: Maximum number of connections per server process
+<IfModule mpm_mpmt_os2_module>
+ StartServers 2
+ MinSpareThreads 5
+ MaxSpareThreads 10
+ MaxRequestsPerChild 0
+</IfModule>
+
+# WinNT MPM
+# ThreadsPerChild: constant number of worker threads in the server process
+# MaxRequestsPerChild: maximum number of requests a server process serves
+<IfModule mpm_winnt_module>
+ ThreadsPerChild 150
+ MaxRequestsPerChild 0
+</IfModule>
+
diff --git a/extra/httpd-multilang-errordoc.conf b/extra/httpd-multilang-errordoc.conf
new file mode 100644
index 0000000..b45fbe8
--- /dev/null
+++ b/extra/httpd-multilang-errordoc.conf
@@ -0,0 +1,52 @@
+#
+# The configuration below implements multi-language error documents through
+# content-negotiation.
+#
+# Required modules: mod_alias, mod_include, mod_negotiation
+#
+# We use Alias to redirect any /error/HTTP_<error>.html.var response to
+# our collection of by-error message multi-language collections. We use
+# includes to substitute the appropriate text.
+#
+# You can modify the messages' appearance without changing any of the
+# default HTTP_<error>.html.var files by adding the line:
+#
+# Alias /error/include/ "/your/include/path/"
+#
+# which allows you to create your own set of files by starting with the
+# /opt/local/apache2/error/include/ files and copying them to /your/include/path/,
+# even on a per-VirtualHost basis. The default include files will display
+# your Apache version number and your ServerAdmin email address regardless
+# of the setting of ServerSignature.
+
+Alias /error/ "/opt/local/apache2/error/"
+
+<Directory "/opt/local/apache2/error">
+ AllowOverride None
+ Options IncludesNoExec
+ AddOutputFilter Includes html
+ AddHandler type-map var
+ Order allow,deny
+ Allow from all
+ LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr
+ ForceLanguagePriority Prefer Fallback
+</Directory>
+
+ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var
+ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var
+ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var
+ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var
+ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var
+ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var
+ErrorDocument 410 /error/HTTP_GONE.html.var
+ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var
+ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var
+ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var
+ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var
+ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var
+ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var
+ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var
+ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var
+ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var
+ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var
+
diff --git a/extra/httpd-ssl.conf b/extra/httpd-ssl.conf
new file mode 100644
index 0000000..814aa0c
--- /dev/null
+++ b/extra/httpd-ssl.conf
@@ -0,0 +1,231 @@
+#
+# This is the Apache server configuration file providing SSL support.
+# It contains the configuration directives to instruct the server how to
+# serve pages over an https connection. For detailing information about these
+# directives see <URL:http://httpd.apache.org/docs/2.2/mod/mod_ssl.html>
+#
+# Do NOT simply read the instructions in here without understanding
+# what they do. They're here only as hints or reminders. If you are unsure
+# consult the online docs. You have been warned.
+#
+
+#
+# Pseudo Random Number Generator (PRNG):
+# Configure one or more sources to seed the PRNG of the SSL library.
+# The seed data should be of good random quality.
+# WARNING! On some platforms /dev/random blocks if not enough entropy
+# is available. This means you then cannot use the /dev/random device
+# because it would lead to very long connection times (as long as
+# it requires to make more entropy available). But usually those
+# platforms additionally provide a /dev/urandom device which doesn't
+# block. So, if available, use this one instead. Read the mod_ssl User
+# Manual for more details.
+#
+#SSLRandomSeed startup file:/dev/random 512
+#SSLRandomSeed startup file:/dev/urandom 512
+#SSLRandomSeed connect file:/dev/random 512
+#SSLRandomSeed connect file:/dev/urandom 512
+
+
+#
+# When we also provide SSL we have to listen to the
+# standard HTTP port (see above) and to the HTTPS port
+#
+# Note: Configurations that use IPv6 but not IPv4-mapped addresses need two
+# Listen directives: "Listen [::]:443" and "Listen 0.0.0.0:443"
+#
+Listen 443
+
+##
+## SSL Global Context
+##
+## All SSL configuration in this context applies both to
+## the main server and all SSL-enabled virtual hosts.
+##
+
+#
+# Some MIME-types for downloading Certificates and CRLs
+#
+AddType application/x-x509-ca-cert .crt
+AddType application/x-pkcs7-crl .crl
+
+# Pass Phrase Dialog:
+# Configure the pass phrase gathering process.
+# The filtering dialog program (`builtin' is a internal
+# terminal dialog) has to provide the pass phrase on stdout.
+SSLPassPhraseDialog builtin
+
+# Inter-Process Session Cache:
+# Configure the SSL Session Cache: First the mechanism
+# to use and second the expiring timeout (in seconds).
+#SSLSessionCache "dbm:/opt/local/apache2/logs/ssl_scache"
+SSLSessionCache "shmcb:/opt/local/apache2/logs/ssl_scache(512000)"
+SSLSessionCacheTimeout 300
+
+# Semaphore:
+# Configure the path to the mutual exclusion semaphore the
+# SSL engine uses internally for inter-process synchronization.
+SSLMutex "file:/opt/local/apache2/logs/ssl_mutex"
+
+##
+## SSL Virtual Host Context
+##
+
+<VirtualHost _default_:443>
+
+# General setup for the virtual host
+DocumentRoot "/opt/local/apache2/htdocs"
+ServerName www.example.com:443
+ServerAdmin you@example.com
+ErrorLog "/opt/local/apache2/logs/error_log"
+TransferLog "/opt/local/apache2/logs/access_log"
+
+# SSL Engine Switch:
+# Enable/Disable SSL for this virtual host.
+SSLEngine on
+
+# SSL Cipher Suite:
+# List the ciphers that the client is permitted to negotiate.
+# See the mod_ssl documentation for a complete list.
+SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
+
+# Server Certificate:
+# Point SSLCertificateFile at a PEM encoded certificate. If
+# the certificate is encrypted, then you will be prompted for a
+# pass phrase. Note that a kill -HUP will prompt again. Keep
+# in mind that if you have both an RSA and a DSA certificate you
+# can configure both in parallel (to also allow the use of DSA
+# ciphers, etc.)
+SSLCertificateFile "/opt/local/apache2/conf/server.crt"
+#SSLCertificateFile "/opt/local/apache2/conf/server-dsa.crt"
+
+# Server Private Key:
+# If the key is not combined with the certificate, use this
+# directive to point at the key file. Keep in mind that if
+# you've both a RSA and a DSA private key you can configure
+# both in parallel (to also allow the use of DSA ciphers, etc.)
+SSLCertificateKeyFile "/opt/local/apache2/conf/server.key"
+#SSLCertificateKeyFile "/opt/local/apache2/conf/server-dsa.key"
+
+# Server Certificate Chain:
+# Point SSLCertificateChainFile at a file containing the
+# concatenation of PEM encoded CA certificates which form the
+# certificate chain for the server certificate. Alternatively
+# the referenced file can be the same as SSLCertificateFile
+# when the CA certificates are directly appended to the server
+# certificate for convinience.
+#SSLCertificateChainFile "/opt/local/apache2/conf/server-ca.crt"
+
+# Certificate Authority (CA):
+# Set the CA certificate verification path where to find CA
+# certificates for client authentication or alternatively one
+# huge file containing all of them (file must be PEM encoded)
+# Note: Inside SSLCACertificatePath you need hash symlinks
+# to point to the certificate files. Use the provided
+# Makefile to update the hash symlinks after changes.
+#SSLCACertificatePath "/opt/local/apache2/conf/ssl.crt"
+#SSLCACertificateFile "/opt/local/apache2/conf/ssl.crt/ca-bundle.crt"
+
+# Certificate Revocation Lists (CRL):
+# Set the CA revocation path where to find CA CRLs for client
+# authentication or alternatively one huge file containing all
+# of them (file must be PEM encoded)
+# Note: Inside SSLCARevocationPath you need hash symlinks
+# to point to the certificate files. Use the provided
+# Makefile to update the hash symlinks after changes.
+#SSLCARevocationPath "/opt/local/apache2/conf/ssl.crl"
+#SSLCARevocationFile "/opt/local/apache2/conf/ssl.crl/ca-bundle.crl"
+
+# Client Authentication (Type):
+# Client certificate verification type and depth. Types are
+# none, optional, require and optional_no_ca. Depth is a
+# number which specifies how deeply to verify the certificate
+# issuer chain before deciding the certificate is not valid.
+#SSLVerifyClient require
+#SSLVerifyDepth 10
+
+# Access Control:
+# With SSLRequire you can do per-directory access control based
+# on arbitrary complex boolean expressions containing server
+# variable checks and other lookup directives. The syntax is a
+# mixture between C and Perl. See the mod_ssl documentation
+# for more details.
+#<Location />
+#SSLRequire ( %{SSL_CIPHER} !~ m/^(EXP|NULL)/ \
+# and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." \
+# and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} \
+# and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 \
+# and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20 ) \
+# or %{REMOTE_ADDR} =~ m/^192\.76\.162\.[0-9]+$/
+#</Location>
+
+# SSL Engine Options:
+# Set various options for the SSL engine.
+# o FakeBasicAuth:
+# Translate the client X.509 into a Basic Authorisation. This means that
+# the standard Auth/DBMAuth methods can be used for access control. The
+# user name is the `one line' version of the client's X.509 certificate.
+# Note that no password is obtained from the user. Every entry in the user
+# file needs this password: `xxj31ZMTZzkVA'.
+# o ExportCertData:
+# This exports two additional environment variables: SSL_CLIENT_CERT and
+# SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
+# server (always existing) and the client (only existing when client
+# authentication is used). This can be used to import the certificates
+# into CGI scripts.
+# o StdEnvVars:
+# This exports the standard SSL/TLS related `SSL_*' environment variables.
+# Per default this exportation is switched off for performance reasons,
+# because the extraction step is an expensive operation and is usually
+# useless for serving static content. So one usually enables the
+# exportation for CGI and SSI requests only.
+# o StrictRequire:
+# This denies access when "SSLRequireSSL" or "SSLRequire" applied even
+# under a "Satisfy any" situation, i.e. when it applies access is denied
+# and no other module can change it.
+# o OptRenegotiate:
+# This enables optimized SSL connection renegotiation handling when SSL
+# directives are used in per-directory context.
+#SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
+<FilesMatch "\.(cgi|shtml|phtml|php)$">
+ SSLOptions +StdEnvVars
+</FilesMatch>
+<Directory "/opt/local/apache2/cgi-bin">
+ SSLOptions +StdEnvVars
+</Directory>
+
+# SSL Protocol Adjustments:
+# The safe and default but still SSL/TLS standard compliant shutdown
+# approach is that mod_ssl sends the close notify alert but doesn't wait for
+# the close notify alert from client. When you need a different shutdown
+# approach you can use one of the following variables:
+# o ssl-unclean-shutdown:
+# This forces an unclean shutdown when the connection is closed, i.e. no
+# SSL close notify alert is send or allowed to received. This violates
+# the SSL/TLS standard but is needed for some brain-dead browsers. Use
+# this when you receive I/O errors because of the standard approach where
+# mod_ssl sends the close notify alert.
+# o ssl-accurate-shutdown:
+# This forces an accurate shutdown when the connection is closed, i.e. a
+# SSL close notify alert is send and mod_ssl waits for the close notify
+# alert of the client. This is 100% SSL/TLS standard compliant, but in
+# practice often causes hanging connections with brain-dead browsers. Use
+# this only for browsers where you know that their SSL implementation
+# works correctly.
+# Notice: Most problems of broken clients are also related to the HTTP
+# keep-alive facility, so you usually additionally want to disable
+# keep-alive for those clients, too. Use variable "nokeepalive" for this.
+# Similarly, one has to force some clients to use HTTP/1.0 to workaround
+# their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
+# "force-response-1.0" for this.
+BrowserMatch ".*MSIE.*" \
+ nokeepalive ssl-unclean-shutdown \
+ downgrade-1.0 force-response-1.0
+
+# Per-Server Logging:
+# The home of a custom SSL log file. Use this when you want a
+# compact non-error SSL logfile on a virtual host basis.
+CustomLog "/opt/local/apache2/logs/ssl_request_log" \
+ "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
+
+</VirtualHost>
diff --git a/extra/httpd-userdir.conf b/extra/httpd-userdir.conf
new file mode 100644
index 0000000..24df593
--- /dev/null
+++ b/extra/httpd-userdir.conf
@@ -0,0 +1,28 @@
+# Settings for user home directories
+#
+# Required module: mod_userdir
+
+#
+# UserDir: The name of the directory that is appended onto a user's home
+# directory if a ~user request is received. Note that you must also set
+# the default access control for these directories, as in the example below.
+#
+UserDir Sites
+
+#
+# Control access to UserDir directories. The following is an example
+# for a site where these directories are restricted to read-only.
+#
+<Directory "/Users/*/Sites">
+ AllowOverride FileInfo AuthConfig Limit Indexes
+ Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
+ <Limit GET POST OPTIONS>
+ Order allow,deny
+ Allow from all
+ </Limit>
+ <LimitExcept GET POST OPTIONS>
+ Order deny,allow
+ Deny from all
+ </LimitExcept>
+</Directory>
+
diff --git a/extra/httpd-vhosts.conf b/extra/httpd-vhosts.conf
new file mode 100644
index 0000000..7c2535a
--- /dev/null
+++ b/extra/httpd-vhosts.conf
@@ -0,0 +1,125 @@
+#
+# Virtual Hosts
+#
+# If you want to maintain multiple domains/hostnames on your
+# machine you can setup VirtualHost containers for them. Most configurations
+# use only name-based virtual hosts so the server doesn't need to worry about
+# IP addresses. This is indicated by the asterisks in the directives below.
+#
+# Please see the documentation at
+# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
+# for further details before you try to setup virtual hosts.
+#
+# You may use the command line option '-S' to verify your virtual host
+# configuration.
+
+#
+# Use name-based virtual hosting.
+#
+NameVirtualHost *:80
+
+
+
+############################
+# YanleyFarm (Joomla) local
+<VirtualHost *:80>
+ ServerName yanleyFarm.localhost
+ DocumentRoot "/Users/Shared/Dev/workspace/yanleyFarm"
+ DirectoryIndex index.php
+ <Directory "/Users/Shared/Dev/workspace/yanleyFarm">
+ AllowOverride All
+ Allow from All
+ </Directory>
+ ErrorLog /opt/local/apache2/logs/yanleyFarm_error.log
+ CustomLog /opt/local/apache2/logs/yanleyFarm_access.log combined
+ php_flag log_errors on
+ php_value error_log /opt/local/apache2/logs/yanleyFarm_php_error.log
+ php_flag display_errors on
+
+ # E_ALL & ~E_NOTICE
+ php_value error_reporting 6135
+</VirtualHost>
+
+###########################
+# Ultimate Day (Rails Passenger)
+<VirtualHost *:80>
+ ServerName sexgames.drinkaware.localhost
+ DocumentRoot "/Users/Shared/Dev/workspace/sexgames.drinkaware/public"
+ <Directory "/Users/Shared/Dev/workspace/sexgames.drinkaware/public">
+ AllowOverride All
+ Allow from All
+ </Directory>
+ ErrorLog /opt/local/apache2/logs/sexgames.drinkaware_error.log
+ CustomLog /opt/local/apache2/logs/esexgames.drinkaware_access.log combined
+ RailsBaseURI /
+ RailsEnv development
+</VirtualHost>
+
+############################
+# Drinkware Sandbox local
+#<VirtualHost *:80>
+# ServerName drinkaware.localhost
+# DocumentRoot "/Users/Shared/Dev/workspace/drinkawareSandbox"
+# DirectoryIndex index.php index.html
+# <Directory "/Users/Shared/Dev/workspace/drinkawareSandbox">
+# AllowOverride All
+# Allow from All
+# </Directory>
+# ErrorLog /opt/local/apache2/logs/drinkawareSandbox_error.log
+# CustomLog /opt/local/apache2/logs/drinkawareSandbox_access.log combined
+# php_flag log_errors on
+# php_value error_log /opt/local/apache2/logs/drinkawareSandbox.log
+# php_flag display_errors on
+#
+# # E_ALL & ~E_NOTICE
+# php_value error_reporting 6135
+#</VirtualHost>
+
+
+############################
+# Joomla Sandbox local
+<VirtualHost *:80>
+ ServerName joomlaSandbox.localhost
+ DocumentRoot "/Users/Shared/Dev/workspace/joomlaSandbox"
+ DirectoryIndex index.php
+ <Directory "/Users/Shared/Dev/workspace/joomlaSandbox">
+ AllowOverride All
+ Allow from All
+ </Directory>
+ ErrorLog /opt/local/apache2/logs/joomlaSandbox_error.log
+ CustomLog /opt/local/apache2/logs/joomlaSandbox_access.log combined
+ php_flag log_errors on
+ php_value error_log /opt/local/apache2/logs/joomlaSandbox_php_error.log
+ php_flag display_errors on
+
+ # E_ALL & ~E_NOTICE
+ php_value error_reporting 6135
+</VirtualHost>
+
+
+############################
+# Drinkdiary local
+#<VirtualHost *:80>
+# ServerName drinkdiary.localhost
+# DocumentRoot "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug"
+#
+# DirectoryIndex index.php
+# <Directory "/Users/rick/Documents/Flex Builder 3/DrinkDiary/bin-debug">
+# AllowOverride All
+# Allow from All
+#
+# #AuthType Basic
+# #AuthName "Restricted Files"
+# #AuthUserFile /usr/local/apache/passwd/passwords
+# #Require user rick
+# </Directory>
+# ErrorLog /opt/local/apache2/logs/drinkdiary_error.log
+# CustomLog /opt/local/apache2/logs/drinkdiary_access.log combined
+# php_flag log_errors on
+# php_value error_log /opt/local/apache2/logs/drinkdiary_php_error.log
+# php_flag display_errors on
+#
+# # E_ALL & ~E_NOTICE
+# php_value error_reporting 6135
+#</VirtualHost>
+
diff --git a/extras-conf/mod_php.conf b/extras-conf/mod_php.conf
new file mode 100755
index 0000000..f51b0df
--- /dev/null
+++ b/extras-conf/mod_php.conf
@@ -0,0 +1,6 @@
+<IfModule mod_php5.c>
+
+AddType application/x-httpd-php .php
+AddType application/x-httpd-php-source .phps
+
+</IfModule>
diff --git a/httpd.conf b/httpd.conf
new file mode 100644
index 0000000..d41440e
--- /dev/null
+++ b/httpd.conf
@@ -0,0 +1,502 @@
+#
+# This is the main Apache HTTP server configuration file. It contains the
+# configuration directives that give the server its instructions.
+# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
+# In particular, see
+# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
+# for a discussion of each configuration directive.
+#
+# Do NOT simply read the instructions in here without understanding
+# what they do. They're here only as hints or reminders. If you are unsure
+# consult the online docs. You have been warned.
+#
+# Configuration and logfile names: If the filenames you specify for many
+# of the server's control files begin with "/" (or "drive:/" for Win32), the
+# server will use that explicit path. If the filenames do *not* begin
+# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
+# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
+# server as "/opt/local/apache2/logs/foo_log".
+
+#
+# ServerRoot: The top of the directory tree under which the server's
+# configuration, error, and log files are kept.
+#
+# Do not add a slash at the end of the directory path. If you point
+# ServerRoot at a non-local disk, be sure to point the LockFile directive
+# at a local disk. If you wish to share the same ServerRoot for multiple
+# httpd daemons, you will need to change at least LockFile and PidFile.
+#
+ServerRoot "/opt/local/apache2"
+
+#
+# Listen: Allows you to bind Apache to specific IP addresses and/or
+# ports, instead of the default. See also the <VirtualHost>
+# directive.
+#
+# Change this to Listen on specific IP addresses as shown below to
+# prevent Apache from glomming onto all bound IP addresses.
+#
+#Listen 12.34.56.78:80
+Listen 80
+
+#
+# Dynamic Shared Object (DSO) Support
+#
+# To be able to use the functionality of a module which was built as a DSO you
+# have to place corresponding `LoadModule' lines at this location so the
+# directives contained in it are actually available _before_ they are used.
+# Statically compiled modules (those listed by `httpd -l') do not need
+# to be loaded here.
+#
+# Example:
+# LoadModule foo_module modules/mod_foo.so
+#
+LoadModule authn_file_module modules/mod_authn_file.so
+LoadModule authn_dbm_module modules/mod_authn_dbm.so
+LoadModule authn_anon_module modules/mod_authn_anon.so
+LoadModule authn_dbd_module modules/mod_authn_dbd.so
+LoadModule authn_default_module modules/mod_authn_default.so
+LoadModule authz_host_module modules/mod_authz_host.so
+LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
+LoadModule authz_user_module modules/mod_authz_user.so
+LoadModule authz_dbm_module modules/mod_authz_dbm.so
+LoadModule authz_owner_module modules/mod_authz_owner.so
+LoadModule authz_default_module modules/mod_authz_default.so
+LoadModule auth_basic_module modules/mod_auth_basic.so
+LoadModule auth_digest_module modules/mod_auth_digest.so
+LoadModule file_cache_module modules/mod_file_cache.so
+LoadModule cache_module modules/mod_cache.so
+LoadModule disk_cache_module modules/mod_disk_cache.so
+LoadModule mem_cache_module modules/mod_mem_cache.so
+LoadModule dbd_module modules/mod_dbd.so
+LoadModule dumpio_module modules/mod_dumpio.so
+LoadModule ext_filter_module modules/mod_ext_filter.so
+LoadModule include_module modules/mod_include.so
+LoadModule filter_module modules/mod_filter.so
+LoadModule substitute_module modules/mod_substitute.so
+LoadModule deflate_module modules/mod_deflate.so
+LoadModule log_config_module modules/mod_log_config.so
+LoadModule log_forensic_module modules/mod_log_forensic.so
+LoadModule logio_module modules/mod_logio.so
+LoadModule env_module modules/mod_env.so
+LoadModule mime_magic_module modules/mod_mime_magic.so
+LoadModule cern_meta_module modules/mod_cern_meta.so
+LoadModule expires_module modules/mod_expires.so
+LoadModule headers_module modules/mod_headers.so
+LoadModule ident_module modules/mod_ident.so
+LoadModule usertrack_module modules/mod_usertrack.so
+LoadModule unique_id_module modules/mod_unique_id.so
+LoadModule setenvif_module modules/mod_setenvif.so
+LoadModule version_module modules/mod_version.so
+LoadModule proxy_module modules/mod_proxy.so
+LoadModule proxy_connect_module modules/mod_proxy_connect.so
+LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
+LoadModule proxy_http_module modules/mod_proxy_http.so
+LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
+LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
+LoadModule ssl_module modules/mod_ssl.so
+LoadModule mime_module modules/mod_mime.so
+LoadModule dav_module modules/mod_dav.so
+LoadModule status_module modules/mod_status.so
+LoadModule autoindex_module modules/mod_autoindex.so
+LoadModule asis_module modules/mod_asis.so
+LoadModule info_module modules/mod_info.so
+LoadModule cgi_module modules/mod_cgi.so
+LoadModule dav_fs_module modules/mod_dav_fs.so
+LoadModule vhost_alias_module modules/mod_vhost_alias.so
+LoadModule negotiation_module modules/mod_negotiation.so
+LoadModule dir_module modules/mod_dir.so
+LoadModule imagemap_module modules/mod_imagemap.so
+LoadModule actions_module modules/mod_actions.so
+LoadModule speling_module modules/mod_speling.so
+LoadModule userdir_module modules/mod_userdir.so
+LoadModule alias_module modules/mod_alias.so
+LoadModule rewrite_module modules/mod_rewrite.so
+LoadModule php5_module modules/libphp5.so
+LoadModule passenger_module /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5/ext/apache2/mod_passenger.so
+PassengerRoot /opt/local/lib/ruby/gems/1.8/gems/passenger-2.2.5
+PassengerRuby /opt/local/bin/ruby
+
+<IfModule !mpm_netware_module>
+<IfModule !mpm_winnt_module>
+#
+# If you wish httpd to run as a different user or group, you must run
+# httpd as root initially and it will switch.
+#
+# User/Group: The name (or #number) of the user/group to run httpd as.
+# It is usually good practice to create a dedicated user and group for
+# running httpd, as with most system services.
+#
+User rick
+Group wheel
+
+</IfModule>
+</IfModule>
+
+# 'Main' server configuration
+#
+# The directives in this section set up the values used by the 'main'
+# server, which responds to any requests that aren't handled by a
+# <VirtualHost> definition. These values also provide defaults for
+# any <VirtualHost> containers you may define later in the file.
+#
+# All of these directives may appear inside <VirtualHost> containers,
+# in which case these default settings will be overridden for the
+# virtual host being defined.
+#
+
+#
+# ServerAdmin: Your address, where problems with the server should be
+# e-mailed. This address appears on some server-generated pages, such
+# as error documents. e.g. admin@your-domain.com
+#
+ServerAdmin you@example.com
+
+#
+# ServerName gives the name and port that the server uses to identify itself.
+# This can often be determined automatically, but we recommend you specify
+# it explicitly to prevent problems during startup.
+#
+# If your host doesn't have a registered DNS name, enter its IP address here.
+#
+#ServerName www.example.com:80
+
+#
+# DocumentRoot: The directory out of which you will serve your
+# documents. By default, all requests are taken from this directory, but
+# symbolic links and aliases may be used to point to other locations.
+#
+DocumentRoot "/opt/local/apache2/htdocs"
+
+#
+# Each directory to which Apache has access can be configured with respect
+# to which services and features are allowed and/or disabled in that
+# directory (and its subdirectories).
+#
+# First, we configure the "default" to be a very restrictive set of
+# features.
+#
+<Directory />
+ Options FollowSymLinks
+ AllowOverride None
+ Order deny,allow
+ Deny from all
+</Directory>
+
+#
+# Note that from this point forward you must specifically allow
+# particular features to be enabled - so if something's not working as
+# you might expect, make sure that you have specifically enabled it
+# below.
+#
+
+#
+# This should be changed to whatever you set DocumentRoot to.
+#
+<Directory "/opt/local/apache2/htdocs">
+ #
+ # Possible values for the Options directive are "None", "All",
+ # or any combination of:
+ # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
+ #
+ # Note that "MultiViews" must be named *explicitly* --- "Options All"
+ # doesn't give it to you.
+ #
+ # The Options directive is both complicated and important. Please see
+ # http://httpd.apache.org/docs/2.2/mod/core.html#options
+ # for more information.
+ #
+ Options Indexes FollowSymLinks
+
+ #
+ # AllowOverride controls what directives may be placed in .htaccess files.
+ # It can be "All", "None", or any combination of the keywords:
+ # Options FileInfo AuthConfig Limit
+ #
+ AllowOverride None
+
+ #
+ # Controls who can get stuff from this server.
+ #
+ Order allow,deny
+ Allow from all
+
+</Directory>
+
+#
+# DirectoryIndex: sets the file that Apache will serve if a directory
+# is requested.
+#
+<IfModule dir_module>
+ DirectoryIndex index.html index.php
+</IfModule>
+
+#
+# The following lines prevent .htaccess files from being viewed by
+# Web clients. Since .htaccess files often contain authorization
+# information, access is disallowed for security reasons. Comment
+# these lines out if you want Web visitors to see the contents of
+# .htaccess files.
+#
+# Also, folks tend to use names such as .htpasswd for password
+# files, so this will protect those as well.
+#
+<Files ~ "^<.([Hh][Tt]|[Dd][Ss]_[Ss])">
+ Order allow,deny
+ Deny from all
+ Satisfy All
+</Files>
+
+#
+# Apple specific filesystem protection.
+#
+
+<Files "rsrc">
+ Order allow,deny
+ Deny from all
+ Satisfy All
+</Files>
+
+<Directory ~ ".\.\.namedfork">
+ Order allow,deny
+ Deny from all
+ Satisfy All
+</Directory>
+
+#
+# ErrorLog: The location of the error log file.
+# If you do not specify an ErrorLog directive within a <VirtualHost>
+# container, error messages relating to that virtual host will be
+# logged here. If you *do* define an error logfile for a <VirtualHost>
+# container, that host's errors will be logged there and not here.
+#
+ErrorLog "logs/error_log"
+
+#
+# LogLevel: Control the number of messages logged to the error_log.
+# Possible values include: debug, info, notice, warn, error, crit,
+# alert, emerg.
+#
+LogLevel warn
+
+<IfModule log_config_module>
+ #
+ # The following directives define some format nicknames for use with
+ # a CustomLog directive (see below).
+ #
+ LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
+ LogFormat "%h %l %u %t \"%r\" %>s %b" common
+
+ <IfModule logio_module>
+ # You need to enable mod_logio.c to use %I and %O
+ LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
+ </IfModule>
+
+ #
+ # The location and format of the access logfile (Common Logfile Format).
+ # If you do not define any access logfiles within a <VirtualHost>
+ # container, they will be logged here. Contrariwise, if you *do*
+ # define per-<VirtualHost> access logfiles, transactions will be
+ # logged therein and *not* in this file.
+ #
+ CustomLog "logs/access_log" common
+
+ #
+ # If you prefer a logfile with access, agent, and referer information
+ # (Combined Logfile Format) you can use the following directive.
+ #
+ #CustomLog "logs/access_log" combined
+</IfModule>
+
+<IfModule alias_module>
+ #
+ # Redirect: Allows you to tell clients about documents that used to
+ # exist in your server's namespace, but do not anymore. The client
+ # will make a new request for the document at its new location.
+ # Example:
+ # Redirect permanent /foo http://www.example.com/bar
+
+ #
+ # Alias: Maps web paths into filesystem paths and is used to
+ # access content that does not live under the DocumentRoot.
+ # Example:
+ # Alias /webpath /full/filesystem/path
+ #
+ # If you include a trailing / on /webpath then the server will
+ # require it to be present in the URL. You will also likely
+ # need to provide a <Directory> section to allow access to
+ # the filesystem path.
+
+ #
+ # ScriptAlias: This controls which directories contain server scripts.
+ # ScriptAliases are essentially the same as Aliases, except that
+ # documents in the target directory are treated as applications and
+ # run by the server when requested rather than as documents sent to the
+ # client. The same rules about trailing "/" apply to ScriptAlias
+ # directives as to Alias.
+ #
+ ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
+
+</IfModule>
+
+<IfModule cgid_module>
+ #
+ # ScriptSock: On threaded servers, designate the path to the UNIX
+ # socket used to communicate with the CGI daemon of mod_cgid.
+ #
+ #Scriptsock logs/cgisock
+</IfModule>
+
+#
+# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
+# CGI directory exists, if you have that configured.
+#
+<Directory "/opt/local/apache2/cgi-bin">
+ AllowOverride None
+ Options None
+ Order allow,deny
+ Allow from all
+</Directory>
+
+#
+# DefaultType: the default MIME type the server will use for a document
+# if it cannot otherwise determine one, such as from filename extensions.
+# If your server contains mostly text or HTML documents, "text/plain" is
+# a good value. If most of your content is binary, such as applications
+# or images, you may want to use "application/octet-stream" instead to
+# keep browsers from trying to display binary files as though they are
+# text.
+#
+DefaultType text/plain
+
+<IfModule mime_module>
+ #
+ # TypesConfig points to the file containing the list of mappings from
+ # filename extension to MIME-type.
+ #
+ TypesConfig conf/mime.types
+
+ #
+ # AddType allows you to add to or override the MIME configuration
+ # file specified in TypesConfig for specific file types.
+ #
+ #AddType application/x-gzip .tgz
+ #
+ # AddEncoding allows you to have certain browsers uncompress
+ # information on the fly. Note: Not all browsers support this.
+ #
+ #AddEncoding x-compress .Z
+ #AddEncoding x-gzip .gz .tgz
+ #
+ # If the AddEncoding directives above are commented-out, then you
+ # probably should define those extensions to indicate media types:
+ #
+ AddType application/x-compress .Z
+ AddType application/x-gzip .gz .tgz
+
+ AddType application/x-httpd-php .php
+ AddType application/x-httpd-php-source .phps
+
+ #
+ # AddHandler allows you to map certain file extensions to "handlers":
+ # actions unrelated to filetype. These can be either built into the server
+ # or added with the Action directive (see below)
+ #
+ # To use CGI scripts outside of ScriptAliased directories:
+ # (You will also need to add "ExecCGI" to the "Options" directive.)
+ #
+ #AddHandler cgi-script .cgi
+
+ # For type maps (negotiated resources):
+ #AddHandler type-map var
+
+ #
+ # Filters allow you to process content before it is sent to the client.
+ #
+ # To parse .shtml files for server-side includes (SSI):
+ # (You will also need to add "Includes" to the "Options" directive.)
+ #
+ #AddType text/html .shtml
+ #AddOutputFilter INCLUDES .shtml
+</IfModule>
+
+#
+# The mod_mime_magic module allows the server to use various hints from the
+# contents of the file itself to determine its type. The MIMEMagicFile
+# directive tells the module where the hint definitions are located.
+#
+#MIMEMagicFile conf/magic
+
+#
+# Customizable error responses come in three flavors:
+# 1) plain text 2) local redirects 3) external redirects
+#
+# Some examples:
+#ErrorDocument 500 "The server made a boo boo."
+#ErrorDocument 404 /missing.html
+#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
+#ErrorDocument 402 http://www.example.com/subscription_info.html
+#
+
+#
+# EnableMMAP and EnableSendfile: On systems that support it,
+# memory-mapping or the sendfile syscall is used to deliver
+# files. This usually improves server performance, but must
+# be turned off when serving from networked-mounted
+# filesystems or if support for these functions is otherwise
+# broken on your system.
+#
+#EnableMMAP off
+#EnableSendfile off
+
+# Supplemental configuration
+#
+# The configuration files in the conf/extra/ directory can be
+# included to add extra features or to modify the default configuration of
+# the server, or you may simply copy their contents here and change as
+# necessary.
+
+# Server-pool management (MPM specific)
+#Include conf/extra/httpd-mpm.conf
+
+# Multi-language error messages
+#Include conf/extra/httpd-multilang-errordoc.conf
+
+# Fancy directory listings
+#Include conf/extra/httpd-autoindex.conf
+
+# Language settings
+#Include conf/extra/httpd-languages.conf
+
+# User home directories
+#Include conf/extra/httpd-userdir.conf
+
+# Real-time info on requests and configuration
+Include conf/extra/httpd-info.conf
+
+# Virtual hosts
+Include conf/extra/httpd-vhosts.conf
+
+# Local access to the Apache HTTP Server Manual
+#Include conf/extra/httpd-manual.conf
+
+# Distributed authoring and versioning (WebDAV)
+#Include conf/extra/httpd-dav.conf
+
+# Various default settings
+#Include conf/extra/httpd-default.conf
+
+# Secure (SSL/TLS) connections
+#Include conf/extra/httpd-ssl.conf
+#
+# Note: The following must must be present to support
+# starting without SSL on platforms with no /dev/random equivalent
+# but a statically compiled-in mod_ssl.
+#
+<IfModule ssl_module>
+SSLRandomSeed startup builtin
+SSLRandomSeed connect builtin
+</IfModule>
+
+# Uncomment following lines to enable Compression (GZIP) of shown content-types
+#AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xhtml+xml application/javascript
diff --git a/magic b/magic
new file mode 100644
index 0000000..0de7336
--- /dev/null
+++ b/magic
@@ -0,0 +1,382 @@
+# Magic data for mod_mime_magic Apache module (originally for file(1) command)
+# The module is described in /manual/mod/mod_mime_magic.html
+#
+# The format is 4-5 columns:
+# Column #1: byte number to begin checking from, ">" indicates continuation
+# Column #2: type of data to match
+# Column #3: contents of data to match
+# Column #4: MIME type of result
+# Column #5: MIME encoding of result (optional)
+
+#------------------------------------------------------------------------------
+# Localstuff: file(1) magic for locally observed files
+# Add any locally observed files here.
+
+#------------------------------------------------------------------------------
+# end local stuff
+#------------------------------------------------------------------------------
+
+#------------------------------------------------------------------------------
+# Java
+
+0 short 0xcafe
+>2 short 0xbabe application/java
+
+#------------------------------------------------------------------------------
+# audio: file(1) magic for sound formats
+#
+# from Jan Nicolai Langfeldt <janl@ifi.uio.no>,
+#
+
+# Sun/NeXT audio data
+0 string .snd
+>12 belong 1 audio/basic
+>12 belong 2 audio/basic
+>12 belong 3 audio/basic
+>12 belong 4 audio/basic
+>12 belong 5 audio/basic
+>12 belong 6 audio/basic
+>12 belong 7 audio/basic
+
+>12 belong 23 audio/x-adpcm
+
+# DEC systems (e.g. DECstation 5000) use a variant of the Sun/NeXT format
+# that uses little-endian encoding and has a different magic number
+# (0x0064732E in little-endian encoding).
+0 lelong 0x0064732E
+>12 lelong 1 audio/x-dec-basic
+>12 lelong 2 audio/x-dec-basic
+>12 lelong 3 audio/x-dec-basic
+>12 lelong 4 audio/x-dec-basic
+>12 lelong 5 audio/x-dec-basic
+>12 lelong 6 audio/x-dec-basic
+>12 lelong 7 audio/x-dec-basic
+# compressed (G.721 ADPCM)
+>12 lelong 23 audio/x-dec-adpcm
+
+# Bytes 0-3 of AIFF, AIFF-C, & 8SVX audio files are "FORM"
+# AIFF audio data
+8 string AIFF audio/x-aiff
+# AIFF-C audio data
+8 string AIFC audio/x-aiff
+# IFF/8SVX audio data
+8 string 8SVX audio/x-aiff
+
+# Creative Labs AUDIO stuff
+# Standard MIDI data
+0 string MThd audio/unknown
+#>9 byte >0 (format %d)
+#>11 byte >1 using %d channels
+# Creative Music (CMF) data
+0 string CTMF audio/unknown
+# SoundBlaster instrument data
+0 string SBI audio/unknown
+# Creative Labs voice data
+0 string Creative\ Voice\ File audio/unknown
+## is this next line right? it came this way...
+#>19 byte 0x1A
+#>23 byte >0 - version %d
+#>22 byte >0 \b.%d
+
+# [GRR 950115: is this also Creative Labs? Guessing that first line
+# should be string instead of unknown-endian long...]
+#0 long 0x4e54524b MultiTrack sound data
+#0 string NTRK MultiTrack sound data
+#>4 long x - version %ld
+
+# Microsoft WAVE format (*.wav)
+# [GRR 950115: probably all of the shorts and longs should be leshort/lelong]
+# Microsoft RIFF
+0 string RIFF audio/unknown
+# - WAVE format
+>8 string WAVE audio/x-wav
+# MPEG audio.
+0 beshort&0xfff0 0xfff0 audio/mpeg
+# C64 SID Music files, from Linus Walleij <triad@df.lth.se>
+0 string PSID audio/prs.sid
+
+#------------------------------------------------------------------------------
+# c-lang: file(1) magic for C programs or various scripts
+#
+
+# XPM icons (Greg Roelofs, newt@uchicago.edu)
+# ideally should go into "images", but entries below would tag XPM as C source
+0 string /*\ XPM image/x-xbm 7bit
+
+# this first will upset you if you're a PL/1 shop... (are there any left?)
+# in which case rm it; ascmagic will catch real C programs
+# C or REXX program text
+0 string /* text/plain
+# C++ program text
+0 string // text/plain
+
+#------------------------------------------------------------------------------
+# compress: file(1) magic for pure-compression formats (no archives)
+#
+# compress, gzip, pack, compact, huf, squeeze, crunch, freeze, yabba, whap, etc.
+#
+# Formats for various forms of compressed data
+# Formats for "compress" proper have been moved into "compress.c",
+# because it tries to uncompress it to figure out what's inside.
+
+# standard unix compress
+0 string \037\235 application/octet-stream x-compress
+
+# gzip (GNU zip, not to be confused with [Info-ZIP/PKWARE] zip archiver)
+0 string \037\213 application/octet-stream x-gzip
+
+# According to gzip.h, this is the correct byte order for packed data.
+0 string \037\036 application/octet-stream
+#
+# This magic number is byte-order-independent.
+#
+0 short 017437 application/octet-stream
+
+# XXX - why *two* entries for "compacted data", one of which is
+# byte-order independent, and one of which is byte-order dependent?
+#
+# compacted data
+0 short 0x1fff application/octet-stream
+0 string \377\037 application/octet-stream
+# huf output
+0 short 0145405 application/octet-stream
+
+# Squeeze and Crunch...
+# These numbers were gleaned from the Unix versions of the programs to
+# handle these formats. Note that I can only uncrunch, not crunch, and
+# I didn't have a crunched file handy, so the crunch number is untested.
+# Keith Waclena <keith@cerberus.uchicago.edu>
+#0 leshort 0x76FF squeezed data (CP/M, DOS)
+#0 leshort 0x76FE crunched data (CP/M, DOS)
+
+# Freeze
+#0 string \037\237 Frozen file 2.1
+#0 string \037\236 Frozen file 1.0 (or gzip 0.5)
+
+# lzh?
+#0 string \037\240 LZH compressed data
+
+#------------------------------------------------------------------------------
+# frame: file(1) magic for FrameMaker files
+#
+# This stuff came on a FrameMaker demo tape, most of which is
+# copyright, but this file is "published" as witness the following:
+#
+0 string \<MakerFile application/x-frame
+0 string \<MIFFile application/x-frame
+0 string \<MakerDictionary application/x-frame
+0 string \<MakerScreenFon application/x-frame
+0 string \<MML application/x-frame
+0 string \<Book application/x-frame
+0 string \<Maker application/x-frame
+
+#------------------------------------------------------------------------------
+# html: file(1) magic for HTML (HyperText Markup Language) docs
+#
+# from Daniel Quinlan <quinlan@yggdrasil.com>
+# and Anna Shergold <anna@inext.co.uk>
+#
+0 string \<!DOCTYPE\ HTML text/html
+0 string \<!doctype\ html text/html
+0 string \<HEAD text/html
+0 string \<head text/html
+0 string \<TITLE text/html
+0 string \<title text/html
+0 string \<html text/html
+0 string \<HTML text/html
+0 string \<!-- text/html
+0 string \<h1 text/html
+0 string \<H1 text/html
+
+# XML eXtensible Markup Language, from Linus Walleij <triad@df.lth.se>
+0 string \<?xml text/xml
+
+#------------------------------------------------------------------------------
+# images: file(1) magic for image formats (see also "c-lang" for XPM bitmaps)
+#
+# originally from jef@helios.ee.lbl.gov (Jef Poskanzer),
+# additions by janl@ifi.uio.no as well as others. Jan also suggested
+# merging several one- and two-line files into here.
+#
+# XXX - byte order for GIF and TIFF fields?
+# [GRR: TIFF allows both byte orders; GIF is probably little-endian]
+#
+
+# [GRR: what the hell is this doing in here?]
+#0 string xbtoa btoa'd file
+
+# PBMPLUS
+# PBM file
+0 string P1 image/x-portable-bitmap 7bit
+# PGM file
+0 string P2 image/x-portable-greymap 7bit
+# PPM file
+0 string P3 image/x-portable-pixmap 7bit
+# PBM "rawbits" file
+0 string P4 image/x-portable-bitmap
+# PGM "rawbits" file
+0 string P5 image/x-portable-greymap
+# PPM "rawbits" file
+0 string P6 image/x-portable-pixmap
+
+# NIFF (Navy Interchange File Format, a modification of TIFF)
+# [GRR: this *must* go before TIFF]
+0 string IIN1 image/x-niff
+
+# TIFF and friends
+# TIFF file, big-endian
+0 string MM image/tiff
+# TIFF file, little-endian
+0 string II image/tiff
+
+# possible GIF replacements; none yet released!
+# (Greg Roelofs, newt@uchicago.edu)
+#
+# GRR 950115: this was mine ("Zip GIF"):
+# ZIF image (GIF+deflate alpha)
+0 string GIF94z image/unknown
+#
+# GRR 950115: this is Jeremy Wohl's Free Graphics Format (better):
+# FGF image (GIF+deflate beta)
+0 string FGF95a image/unknown
+#
+# GRR 950115: this is Thomas Boutell's Portable Bitmap Format proposal
+# (best; not yet implemented):
+# PBF image (deflate compression)
+0 string PBF image/unknown
+
+# GIF
+0 string GIF image/gif
+
+# JPEG images
+0 beshort 0xffd8 image/jpeg
+
+# PC bitmaps (OS/2, Windoze BMP files) (Greg Roelofs, newt@uchicago.edu)
+0 string BM image/bmp
+#>14 byte 12 (OS/2 1.x format)
+#>14 byte 64 (OS/2 2.x format)
+#>14 byte 40 (Windows 3.x format)
+#0 string IC icon
+#0 string PI pointer
+#0 string CI color icon
+#0 string CP color pointer
+#0 string BA bitmap array
+
+
+#------------------------------------------------------------------------------
+# lisp: file(1) magic for lisp programs
+#
+# various lisp types, from Daniel Quinlan (quinlan@yggdrasil.com)
+0 string ;; text/plain 8bit
+# Emacs 18 - this is always correct, but not very magical.
+0 string \012( application/x-elc
+# Emacs 19
+0 string ;ELC\023\000\000\000 application/x-elc
+
+#------------------------------------------------------------------------------
+# mail.news: file(1) magic for mail and news
+#
+# There are tests to ascmagic.c to cope with mail and news.
+0 string Relay-Version: message/rfc822 7bit
+0 string #!\ rnews message/rfc822 7bit
+0 string N#!\ rnews message/rfc822 7bit
+0 string Forward\ to message/rfc822 7bit
+0 string Pipe\ to message/rfc822 7bit
+0 string Return-Path: message/rfc822 7bit
+0 string Path: message/news 8bit
+0 string Xref: message/news 8bit
+0 string From: message/rfc822 7bit
+0 string Article message/news 8bit
+#------------------------------------------------------------------------------
+# msword: file(1) magic for MS Word files
+#
+# Contributor claims:
+# Reversed-engineered MS Word magic numbers
+#
+
+0 string \376\067\0\043 application/msword
+0 string \333\245-\0\0\0 application/msword
+
+# disable this one because it applies also to other
+# Office/OLE documents for which msword is not correct. See PR#2608.
+#0 string \320\317\021\340\241\261 application/msword
+
+
+
+#------------------------------------------------------------------------------
+# printer: file(1) magic for printer-formatted files
+#
+
+# PostScript
+0 string %! application/postscript
+0 string \004%! application/postscript
+
+# Acrobat
+# (due to clamen@cs.cmu.edu)
+0 string %PDF- application/pdf
+
+#------------------------------------------------------------------------------
+# sc: file(1) magic for "sc" spreadsheet
+#
+38 string Spreadsheet application/x-sc
+
+#------------------------------------------------------------------------------
+# tex: file(1) magic for TeX files
+#
+# XXX - needs byte-endian stuff (big-endian and little-endian DVI?)
+#
+# From <conklin@talisman.kaleida.com>
+
+# Although we may know the offset of certain text fields in TeX DVI
+# and font files, we can't use them reliably because they are not
+# zero terminated. [but we do anyway, christos]
+0 string \367\002 application/x-dvi
+#0 string \367\203 TeX generic font data
+#0 string \367\131 TeX packed font data
+#0 string \367\312 TeX virtual font data
+#0 string This\ is\ TeX, TeX transcript text
+#0 string This\ is\ METAFONT, METAFONT transcript text
+
+# There is no way to detect TeX Font Metric (*.tfm) files without
+# breaking them apart and reading the data. The following patterns
+# match most *.tfm files generated by METAFONT or afm2tfm.
+#2 string \000\021 TeX font metric data
+#2 string \000\022 TeX font metric data
+#>34 string >\0 (%s)
+
+# Texinfo and GNU Info, from Daniel Quinlan (quinlan@yggdrasil.com)
+#0 string \\input\ texinfo Texinfo source text
+#0 string This\ is\ Info\ file GNU Info text
+
+# correct TeX magic for Linux (and maybe more)
+# from Peter Tobias (tobias@server.et-inf.fho-emden.de)
+#
+0 leshort 0x02f7 application/x-dvi
+
+# RTF - Rich Text Format
+0 string {\\rtf application/rtf
+
+#------------------------------------------------------------------------------
+# animation: file(1) magic for animation/movie formats
+#
+# animation formats, originally from vax@ccwf.cc.utexas.edu (VaX#n8)
+# MPEG file
+0 string \000\000\001\263 video/mpeg
+#
+# The contributor claims:
+# I couldn't find a real magic number for these, however, this
+# -appears- to work. Note that it might catch other files, too,
+# so BE CAREFUL!
+#
+# Note that title and author appear in the two 20-byte chunks
+# at decimal offsets 2 and 22, respectively, but they are XOR'ed with
+# 255 (hex FF)! DL format SUCKS BIG ROCKS.
+#
+# DL file version 1 , medium format (160x100, 4 images/screen)
+0 byte 1 video/unknown
+0 byte 2 video/unknown
+# Quicktime video, from Linus Walleij <triad@df.lth.se>
+# from Apple quicktime file format documentation.
+4 string moov video/quicktime
+4 string mdat video/quicktime
+
diff --git a/mime.types b/mime.types
new file mode 100644
index 0000000..d20ab01
--- /dev/null
+++ b/mime.types
@@ -0,0 +1,1236 @@
+# This file maps Internet media types to unique file extension(s).
+# Although created for httpd, this file is used by many software systems
+# and has been placed in the public domain for unlimited redisribution.
+#
+# The table below contains both registered and (common) unregistered types.
+# A type that has no unique extension can be ignored -- they are listed
+# here to guide configurations toward known types and to make it easier to
+# identify "new" types. File extensions are also commonly used to indicate
+# content languages and encodings, so choose them carefully.
+#
+# Internet media types should be registered as described in RFC 4288.
+# The registry is at <http://www.iana.org/assignments/media-types/>.
+#
+# MIME type Extensions
+application/activemessage
+application/andrew-inset ez
+application/applefile
+application/applixware aw
+application/atom+xml atom
+application/atomcat+xml atomcat
+application/atomicmail
+application/atomsvc+xml atomsvc
+application/auth-policy+xml
+application/batch-smtp
+application/beep+xml
+application/cals-1840
+application/ccxml+xml ccxml
+application/cea-2018+xml
+application/cellml+xml
+application/cnrp+xml
+application/commonground
+application/conference-info+xml
+application/cpl+xml
+application/csta+xml
+application/cstadata+xml
+application/cu-seeme cu
+application/cybercash
+application/davmount+xml davmount
+application/dca-rft
+application/dec-dx
+application/dialog-info+xml
+application/dicom
+application/dns
+application/dvcs
+application/ecmascript ecma
+application/edi-consent
+application/edi-x12
+application/edifact
+application/emma+xml emma
+application/epp+xml
+application/epub+zip epub
+application/eshop
+application/example
+application/fastinfoset
+application/fastsoap
+application/fits
+application/font-tdpfr pfr
+application/h224
+application/http
+application/hyperstudio stk
+application/ibe-key-request+xml
+application/ibe-pkg-reply+xml
+application/ibe-pp-data
+application/iges
+application/im-iscomposing+xml
+application/index
+application/index.cmd
+application/index.obj
+application/index.response
+application/index.vnd
+application/iotp
+application/ipp
+application/isup
+application/java-archive jar
+application/java-serialized-object ser
+application/java-vm class
+application/javascript js
+application/json json
+application/kpml-request+xml
+application/kpml-response+xml
+application/lost+xml lostxml
+application/mac-binhex40 hqx
+application/mac-compactpro cpt
+application/macwriteii
+application/marc mrc
+application/mathematica ma nb mb
+application/mathml+xml mathml
+application/mbms-associated-procedure-description+xml
+application/mbms-deregister+xml
+application/mbms-envelope+xml
+application/mbms-msk+xml
+application/mbms-msk-response+xml
+application/mbms-protection-description+xml
+application/mbms-reception-report+xml
+application/mbms-register+xml
+application/mbms-register-response+xml
+application/mbms-user-service-description+xml
+application/mbox mbox
+application/media_control+xml
+application/mediaservercontrol+xml mscml
+application/mikey
+application/moss-keys
+application/moss-signature
+application/mosskey-data
+application/mosskey-request
+application/mp4 mp4s
+application/mpeg4-generic
+application/mpeg4-iod
+application/mpeg4-iod-xmt
+application/msword doc dot
+application/mxf mxf
+application/nasdata
+application/news-checkgroups
+application/news-groupinfo
+application/news-transmission
+application/nss
+application/ocsp-request
+application/ocsp-response
+application/octet-stream bin dms lha lrf lzh so iso dmg dist distz pkg bpk dump elc deploy
+application/oda oda
+application/oebps-package+xml opf
+application/ogg ogx
+application/onenote onetoc onetoc2 onetmp onepkg
+application/parityfec
+application/patch-ops-error+xml xer
+application/pdf pdf
+application/pgp-encrypted pgp
+application/pgp-keys
+application/pgp-signature asc sig
+application/pics-rules prf
+application/pidf+xml
+application/pidf-diff+xml
+application/pkcs10 p10
+application/pkcs7-mime p7m p7c
+application/pkcs7-signature p7s
+application/pkix-cert cer
+application/pkix-crl crl
+application/pkix-pkipath pkipath
+application/pkixcmp pki
+application/pls+xml pls
+application/poc-settings+xml
+application/postscript ai eps ps
+application/prs.alvestrand.titrax-sheet
+application/prs.cww cww
+application/prs.nprend
+application/prs.plucker
+application/qsig
+application/rdf+xml rdf
+application/reginfo+xml rif
+application/relax-ng-compact-syntax rnc
+application/remote-printing
+application/resource-lists+xml rl
+application/resource-lists-diff+xml rld
+application/riscos
+application/rlmi+xml
+application/rls-services+xml rs
+application/rsd+xml rsd
+application/rss+xml rss
+application/rtf rtf
+application/rtx
+application/samlassertion+xml
+application/samlmetadata+xml
+application/sbml+xml sbml
+application/scvp-cv-request scq
+application/scvp-cv-response scs
+application/scvp-vp-request spq
+application/scvp-vp-response spp
+application/sdp sdp
+application/set-payment
+application/set-payment-initiation setpay
+application/set-registration
+application/set-registration-initiation setreg
+application/sgml
+application/sgml-open-catalog
+application/shf+xml shf
+application/sieve
+application/simple-filter+xml
+application/simple-message-summary
+application/simplesymbolcontainer
+application/slate
+application/smil
+application/smil+xml smi smil
+application/soap+fastinfoset
+application/soap+xml
+application/sparql-query rq
+application/sparql-results+xml srx
+application/spirits-event+xml
+application/srgs gram
+application/srgs+xml grxml
+application/ssml+xml ssml
+application/timestamp-query
+application/timestamp-reply
+application/tve-trigger
+application/ulpfec
+application/vemmi
+application/vividence.scriptfile
+application/vnd.3gpp.bsf+xml
+application/vnd.3gpp.pic-bw-large plb
+application/vnd.3gpp.pic-bw-small psb
+application/vnd.3gpp.pic-bw-var pvb
+application/vnd.3gpp.sms
+application/vnd.3gpp2.bcmcsinfo+xml
+application/vnd.3gpp2.sms
+application/vnd.3gpp2.tcap tcap
+application/vnd.3m.post-it-notes pwn
+application/vnd.accpac.simply.aso aso
+application/vnd.accpac.simply.imp imp
+application/vnd.acucobol acu
+application/vnd.acucorp atc acutc
+application/vnd.adobe.air-application-installer-package+zip air
+application/vnd.adobe.xdp+xml xdp
+application/vnd.adobe.xfdf xfdf
+application/vnd.aether.imp
+application/vnd.airzip.filesecure.azf azf
+application/vnd.airzip.filesecure.azs azs
+application/vnd.amazon.ebook azw
+application/vnd.americandynamics.acc acc
+application/vnd.amiga.ami ami
+application/vnd.android.package-archive apk
+application/vnd.anser-web-certificate-issue-initiation cii
+application/vnd.anser-web-funds-transfer-initiation fti
+application/vnd.antix.game-component atx
+application/vnd.apple.installer+xml mpkg
+application/vnd.arastra.swi swi
+application/vnd.audiograph aep
+application/vnd.autopackage
+application/vnd.avistar+xml
+application/vnd.blueice.multipass mpm
+application/vnd.bluetooth.ep.oob
+application/vnd.bmi bmi
+application/vnd.businessobjects rep
+application/vnd.cab-jscript
+application/vnd.canon-cpdl
+application/vnd.canon-lips
+application/vnd.cendio.thinlinc.clientconf
+application/vnd.chemdraw+xml cdxml
+application/vnd.chipnuts.karaoke-mmd mmd
+application/vnd.cinderella cdy
+application/vnd.cirpack.isdn-ext
+application/vnd.claymore cla
+application/vnd.clonk.c4group c4g c4d c4f c4p c4u
+application/vnd.commerce-battelle
+application/vnd.commonspace csp
+application/vnd.contact.cmsg cdbcmsg
+application/vnd.cosmocaller cmc
+application/vnd.crick.clicker clkx
+application/vnd.crick.clicker.keyboard clkk
+application/vnd.crick.clicker.palette clkp
+application/vnd.crick.clicker.template clkt
+application/vnd.crick.clicker.wordbank clkw
+application/vnd.criticaltools.wbs+xml wbs
+application/vnd.ctc-posml pml
+application/vnd.ctct.ws+xml
+application/vnd.cups-pdf
+application/vnd.cups-postscript
+application/vnd.cups-ppd ppd
+application/vnd.cups-raster
+application/vnd.cups-raw
+application/vnd.curl.car car
+application/vnd.curl.pcurl pcurl
+application/vnd.cybank
+application/vnd.data-vision.rdz rdz
+application/vnd.denovo.fcselayout-link fe_launch
+application/vnd.dir-bi.plate-dl-nosuffix
+application/vnd.dna dna
+application/vnd.dolby.mlp mlp
+application/vnd.dolby.mobile.1
+application/vnd.dolby.mobile.2
+application/vnd.dpgraph dpg
+application/vnd.dreamfactory dfac
+application/vnd.dvb.esgcontainer
+application/vnd.dvb.ipdcdftnotifaccess
+application/vnd.dvb.ipdcesgaccess
+application/vnd.dvb.ipdcroaming
+application/vnd.dvb.iptv.alfec-base
+application/vnd.dvb.iptv.alfec-enhancement
+application/vnd.dvb.notif-aggregate-root+xml
+application/vnd.dvb.notif-container+xml
+application/vnd.dvb.notif-generic+xml
+application/vnd.dvb.notif-ia-msglist+xml
+application/vnd.dvb.notif-ia-registration-request+xml
+application/vnd.dvb.notif-ia-registration-response+xml
+application/vnd.dvb.notif-init+xml
+application/vnd.dxr
+application/vnd.dynageo geo
+application/vnd.ecdis-update
+application/vnd.ecowin.chart mag
+application/vnd.ecowin.filerequest
+application/vnd.ecowin.fileupdate
+application/vnd.ecowin.series
+application/vnd.ecowin.seriesrequest
+application/vnd.ecowin.seriesupdate
+application/vnd.emclient.accessrequest+xml
+application/vnd.enliven nml
+application/vnd.epson.esf esf
+application/vnd.epson.msf msf
+application/vnd.epson.quickanime qam
+application/vnd.epson.salt slt
+application/vnd.epson.ssf ssf
+application/vnd.ericsson.quickcall
+application/vnd.eszigno3+xml es3 et3
+application/vnd.etsi.aoc+xml
+application/vnd.etsi.cug+xml
+application/vnd.etsi.iptvcommand+xml
+application/vnd.etsi.iptvdiscovery+xml
+application/vnd.etsi.iptvprofile+xml
+application/vnd.etsi.iptvsad-bc+xml
+application/vnd.etsi.iptvsad-cod+xml
+application/vnd.etsi.iptvsad-npvr+xml
+application/vnd.etsi.iptvueprofile+xml
+application/vnd.etsi.mcid+xml
+application/vnd.etsi.sci+xml
+application/vnd.etsi.simservs+xml
+application/vnd.eudora.data
+application/vnd.ezpix-album ez2
+application/vnd.ezpix-package ez3
+application/vnd.f-secure.mobile
+application/vnd.fdf fdf
+application/vnd.fdsn.mseed mseed
+application/vnd.fdsn.seed seed dataless
+application/vnd.ffsns
+application/vnd.fints
+application/vnd.flographit gph
+application/vnd.fluxtime.clip ftc
+application/vnd.font-fontforge-sfd
+application/vnd.framemaker fm frame maker book
+application/vnd.frogans.fnc fnc
+application/vnd.frogans.ltf ltf
+application/vnd.fsc.weblaunch fsc
+application/vnd.fujitsu.oasys oas
+application/vnd.fujitsu.oasys2 oa2
+application/vnd.fujitsu.oasys3 oa3
+application/vnd.fujitsu.oasysgp fg5
+application/vnd.fujitsu.oasysprs bh2
+application/vnd.fujixerox.art-ex
+application/vnd.fujixerox.art4
+application/vnd.fujixerox.hbpl
+application/vnd.fujixerox.ddd ddd
+application/vnd.fujixerox.docuworks xdw
+application/vnd.fujixerox.docuworks.binder xbd
+application/vnd.fut-misnet
+application/vnd.fuzzysheet fzs
+application/vnd.genomatix.tuxedo txd
+application/vnd.geogebra.file ggb
+application/vnd.geogebra.tool ggt
+application/vnd.geometry-explorer gex gre
+application/vnd.gmx gmx
+application/vnd.google-earth.kml+xml kml
+application/vnd.google-earth.kmz kmz
+application/vnd.grafeq gqf gqs
+application/vnd.gridmp
+application/vnd.groove-account gac
+application/vnd.groove-help ghf
+application/vnd.groove-identity-message gim
+application/vnd.groove-injector grv
+application/vnd.groove-tool-message gtm
+application/vnd.groove-tool-template tpl
+application/vnd.groove-vcard vcg
+application/vnd.handheld-entertainment+xml zmm
+application/vnd.hbci hbci
+application/vnd.hcl-bireports
+application/vnd.hhe.lesson-player les
+application/vnd.hp-hpgl hpgl
+application/vnd.hp-hpid hpid
+application/vnd.hp-hps hps
+application/vnd.hp-jlyt jlt
+application/vnd.hp-pcl pcl
+application/vnd.hp-pclxl pclxl
+application/vnd.httphone
+application/vnd.hydrostatix.sof-data sfd-hdstx
+application/vnd.hzn-3d-crossword x3d
+application/vnd.ibm.afplinedata
+application/vnd.ibm.electronic-media
+application/vnd.ibm.minipay mpy
+application/vnd.ibm.modcap afp listafp list3820
+application/vnd.ibm.rights-management irm
+application/vnd.ibm.secure-container sc
+application/vnd.iccprofile icc icm
+application/vnd.igloader igl
+application/vnd.immervision-ivp ivp
+application/vnd.immervision-ivu ivu
+application/vnd.informedcontrol.rms+xml
+application/vnd.informix-visionary
+application/vnd.intercon.formnet xpw xpx
+application/vnd.intertrust.digibox
+application/vnd.intertrust.nncp
+application/vnd.intu.qbo qbo
+application/vnd.intu.qfx qfx
+application/vnd.iptc.g2.conceptitem+xml
+application/vnd.iptc.g2.knowledgeitem+xml
+application/vnd.iptc.g2.newsitem+xml
+application/vnd.iptc.g2.packageitem+xml
+application/vnd.ipunplugged.rcprofile rcprofile
+application/vnd.irepository.package+xml irp
+application/vnd.is-xpr xpr
+application/vnd.jam jam
+application/vnd.japannet-directory-service
+application/vnd.japannet-jpnstore-wakeup
+application/vnd.japannet-payment-wakeup
+application/vnd.japannet-registration
+application/vnd.japannet-registration-wakeup
+application/vnd.japannet-setstore-wakeup
+application/vnd.japannet-verification
+application/vnd.japannet-verification-wakeup
+application/vnd.jcp.javame.midlet-rms rms
+application/vnd.jisp jisp
+application/vnd.joost.joda-archive joda
+application/vnd.kahootz ktz ktr
+application/vnd.kde.karbon karbon
+application/vnd.kde.kchart chrt
+application/vnd.kde.kformula kfo
+application/vnd.kde.kivio flw
+application/vnd.kde.kontour kon
+application/vnd.kde.kpresenter kpr kpt
+application/vnd.kde.kspread ksp
+application/vnd.kde.kword kwd kwt
+application/vnd.kenameaapp htke
+application/vnd.kidspiration kia
+application/vnd.kinar kne knp
+application/vnd.koan skp skd skt skm
+application/vnd.kodak-descriptor sse
+application/vnd.liberty-request+xml
+application/vnd.llamagraphics.life-balance.desktop lbd
+application/vnd.llamagraphics.life-balance.exchange+xml lbe
+application/vnd.lotus-1-2-3 123
+application/vnd.lotus-approach apr
+application/vnd.lotus-freelance pre
+application/vnd.lotus-notes nsf
+application/vnd.lotus-organizer org
+application/vnd.lotus-screencam scm
+application/vnd.lotus-wordpro lwp
+application/vnd.macports.portpkg portpkg
+application/vnd.marlin.drm.actiontoken+xml
+application/vnd.marlin.drm.conftoken+xml
+application/vnd.marlin.drm.license+xml
+application/vnd.marlin.drm.mdcf
+application/vnd.mcd mcd
+application/vnd.medcalcdata mc1
+application/vnd.mediastation.cdkey cdkey
+application/vnd.meridian-slingshot
+application/vnd.mfer mwf
+application/vnd.mfmp mfm
+application/vnd.micrografx.flo flo
+application/vnd.micrografx.igx igx
+application/vnd.mif mif
+application/vnd.minisoft-hp3000-save
+application/vnd.mitsubishi.misty-guard.trustweb
+application/vnd.mobius.daf daf
+application/vnd.mobius.dis dis
+application/vnd.mobius.mbk mbk
+application/vnd.mobius.mqy mqy
+application/vnd.mobius.msl msl
+application/vnd.mobius.plc plc
+application/vnd.mobius.txf txf
+application/vnd.mophun.application mpn
+application/vnd.mophun.certificate mpc
+application/vnd.motorola.flexsuite
+application/vnd.motorola.flexsuite.adsi
+application/vnd.motorola.flexsuite.fis
+application/vnd.motorola.flexsuite.gotap
+application/vnd.motorola.flexsuite.kmr
+application/vnd.motorola.flexsuite.ttc
+application/vnd.motorola.flexsuite.wem
+application/vnd.motorola.iprm
+application/vnd.mozilla.xul+xml xul
+application/vnd.ms-artgalry cil
+application/vnd.ms-asf
+application/vnd.ms-cab-compressed cab
+application/vnd.ms-excel xls xlm xla xlc xlt xlw
+application/vnd.ms-excel.addin.macroenabled.12 xlam
+application/vnd.ms-excel.sheet.binary.macroenabled.12 xlsb
+application/vnd.ms-excel.sheet.macroenabled.12 xlsm
+application/vnd.ms-excel.template.macroenabled.12 xltm
+application/vnd.ms-fontobject eot
+application/vnd.ms-htmlhelp chm
+application/vnd.ms-ims ims
+application/vnd.ms-lrm lrm
+application/vnd.ms-pki.seccat cat
+application/vnd.ms-pki.stl stl
+application/vnd.ms-playready.initiator+xml
+application/vnd.ms-powerpoint ppt pps pot
+application/vnd.ms-powerpoint.addin.macroenabled.12 ppam
+application/vnd.ms-powerpoint.presentation.macroenabled.12 pptm
+application/vnd.ms-powerpoint.slide.macroenabled.12 sldm
+application/vnd.ms-powerpoint.slideshow.macroenabled.12 ppsm
+application/vnd.ms-powerpoint.template.macroenabled.12 potm
+application/vnd.ms-project mpp mpt
+application/vnd.ms-tnef
+application/vnd.ms-wmdrm.lic-chlg-req
+application/vnd.ms-wmdrm.lic-resp
+application/vnd.ms-wmdrm.meter-chlg-req
+application/vnd.ms-wmdrm.meter-resp
+application/vnd.ms-word.document.macroenabled.12 docm
+application/vnd.ms-word.template.macroenabled.12 dotm
+application/vnd.ms-works wps wks wcm wdb
+application/vnd.ms-wpl wpl
+application/vnd.ms-xpsdocument xps
+application/vnd.mseq mseq
+application/vnd.msign
+application/vnd.multiad.creator
+application/vnd.multiad.creator.cif
+application/vnd.music-niff
+application/vnd.musician mus
+application/vnd.muvee.style msty
+application/vnd.ncd.control
+application/vnd.ncd.reference
+application/vnd.nervana
+application/vnd.netfpx
+application/vnd.neurolanguage.nlu nlu
+application/vnd.noblenet-directory nnd
+application/vnd.noblenet-sealer nns
+application/vnd.noblenet-web nnw
+application/vnd.nokia.catalogs
+application/vnd.nokia.conml+wbxml
+application/vnd.nokia.conml+xml
+application/vnd.nokia.isds-radio-presets
+application/vnd.nokia.iptv.config+xml
+application/vnd.nokia.landmark+wbxml
+application/vnd.nokia.landmark+xml
+application/vnd.nokia.landmarkcollection+xml
+application/vnd.nokia.n-gage.ac+xml
+application/vnd.nokia.n-gage.data ngdat
+application/vnd.nokia.n-gage.symbian.install n-gage
+application/vnd.nokia.ncd
+application/vnd.nokia.pcd+wbxml
+application/vnd.nokia.pcd+xml
+application/vnd.nokia.radio-preset rpst
+application/vnd.nokia.radio-presets rpss
+application/vnd.novadigm.edm edm
+application/vnd.novadigm.edx edx
+application/vnd.novadigm.ext ext
+application/vnd.oasis.opendocument.chart odc
+application/vnd.oasis.opendocument.chart-template otc
+application/vnd.oasis.opendocument.database odb
+application/vnd.oasis.opendocument.formula odf
+application/vnd.oasis.opendocument.formula-template odft
+application/vnd.oasis.opendocument.graphics odg
+application/vnd.oasis.opendocument.graphics-template otg
+application/vnd.oasis.opendocument.image odi
+application/vnd.oasis.opendocument.image-template oti
+application/vnd.oasis.opendocument.presentation odp
+application/vnd.oasis.opendocument.presentation-template otp
+application/vnd.oasis.opendocument.spreadsheet ods
+application/vnd.oasis.opendocument.spreadsheet-template ots
+application/vnd.oasis.opendocument.text odt
+application/vnd.oasis.opendocument.text-master otm
+application/vnd.oasis.opendocument.text-template ott
+application/vnd.oasis.opendocument.text-web oth
+application/vnd.obn
+application/vnd.olpc-sugar xo
+application/vnd.oma-scws-config
+application/vnd.oma-scws-http-request
+application/vnd.oma-scws-http-response
+application/vnd.oma.bcast.associated-procedure-parameter+xml
+application/vnd.oma.bcast.drm-trigger+xml
+application/vnd.oma.bcast.imd+xml
+application/vnd.oma.bcast.ltkm
+application/vnd.oma.bcast.notification+xml
+application/vnd.oma.bcast.provisioningtrigger
+application/vnd.oma.bcast.sgboot
+application/vnd.oma.bcast.sgdd+xml
+application/vnd.oma.bcast.sgdu
+application/vnd.oma.bcast.simple-symbol-container
+application/vnd.oma.bcast.smartcard-trigger+xml
+application/vnd.oma.bcast.sprov+xml
+application/vnd.oma.bcast.stkm
+application/vnd.oma.dcd
+application/vnd.oma.dcdc
+application/vnd.oma.dd2+xml dd2
+application/vnd.oma.drm.risd+xml
+application/vnd.oma.group-usage-list+xml
+application/vnd.oma.poc.detailed-progress-report+xml
+application/vnd.oma.poc.final-report+xml
+application/vnd.oma.poc.groups+xml
+application/vnd.oma.poc.invocation-descriptor+xml
+application/vnd.oma.poc.optimized-progress-report+xml
+application/vnd.oma.xcap-directory+xml
+application/vnd.omads-email+xml
+application/vnd.omads-file+xml
+application/vnd.omads-folder+xml
+application/vnd.omaloc-supl-init
+application/vnd.openofficeorg.extension oxt
+application/vnd.openxmlformats-officedocument.presentationml.presentation pptx
+application/vnd.openxmlformats-officedocument.presentationml.slide sldx
+application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx
+application/vnd.openxmlformats-officedocument.presentationml.template potx
+application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx
+application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx
+application/vnd.openxmlformats-officedocument.wordprocessingml.document docx
+application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx
+application/vnd.osa.netdeploy
+application/vnd.osgi.bundle
+application/vnd.osgi.dp dp
+application/vnd.otps.ct-kip+xml
+application/vnd.palm pdb pqa oprc
+application/vnd.paos.xml
+application/vnd.pg.format str
+application/vnd.pg.osasli ei6
+application/vnd.piaccess.application-licence
+application/vnd.picsel efif
+application/vnd.poc.group-advertisement+xml
+application/vnd.pocketlearn plf
+application/vnd.powerbuilder6 pbd
+application/vnd.powerbuilder6-s
+application/vnd.powerbuilder7
+application/vnd.powerbuilder7-s
+application/vnd.powerbuilder75
+application/vnd.powerbuilder75-s
+application/vnd.preminet
+application/vnd.previewsystems.box box
+application/vnd.proteus.magazine mgz
+application/vnd.publishare-delta-tree qps
+application/vnd.pvi.ptid1 ptid
+application/vnd.pwg-multiplexed
+application/vnd.pwg-xhtml-print+xml
+application/vnd.qualcomm.brew-app-res
+application/vnd.quark.quarkxpress qxd qxt qwd qwt qxl qxb
+application/vnd.rapid
+application/vnd.recordare.musicxml mxl
+application/vnd.recordare.musicxml+xml musicxml
+application/vnd.renlearn.rlprint
+application/vnd.rim.cod cod
+application/vnd.rn-realmedia rm
+application/vnd.route66.link66+xml link66
+application/vnd.ruckus.download
+application/vnd.s3sms
+application/vnd.sbm.cid
+application/vnd.sbm.mid2
+application/vnd.scribus
+application/vnd.sealed.3df
+application/vnd.sealed.csf
+application/vnd.sealed.doc
+application/vnd.sealed.eml
+application/vnd.sealed.mht
+application/vnd.sealed.net
+application/vnd.sealed.ppt
+application/vnd.sealed.tiff
+application/vnd.sealed.xls
+application/vnd.sealedmedia.softseal.html
+application/vnd.sealedmedia.softseal.pdf
+application/vnd.seemail see
+application/vnd.sema sema
+application/vnd.semd semd
+application/vnd.semf semf
+application/vnd.shana.informed.formdata ifm
+application/vnd.shana.informed.formtemplate itp
+application/vnd.shana.informed.interchange iif
+application/vnd.shana.informed.package ipk
+application/vnd.simtech-mindmapper twd twds
+application/vnd.smaf mmf
+application/vnd.smart.teacher teacher
+application/vnd.software602.filler.form+xml
+application/vnd.software602.filler.form-xml-zip
+application/vnd.solent.sdkm+xml sdkm sdkd
+application/vnd.spotfire.dxp dxp
+application/vnd.spotfire.sfs sfs
+application/vnd.sss-cod
+application/vnd.sss-dtf
+application/vnd.sss-ntf
+application/vnd.stardivision.calc sdc
+application/vnd.stardivision.draw sda
+application/vnd.stardivision.impress sdd
+application/vnd.stardivision.math smf
+application/vnd.stardivision.writer sdw
+application/vnd.stardivision.writer vor
+application/vnd.stardivision.writer-global sgl
+application/vnd.street-stream
+application/vnd.sun.xml.calc sxc
+application/vnd.sun.xml.calc.template stc
+application/vnd.sun.xml.draw sxd
+application/vnd.sun.xml.draw.template std
+application/vnd.sun.xml.impress sxi
+application/vnd.sun.xml.impress.template sti
+application/vnd.sun.xml.math sxm
+application/vnd.sun.xml.writer sxw
+application/vnd.sun.xml.writer.global sxg
+application/vnd.sun.xml.writer.template stw
+application/vnd.sun.wadl+xml
+application/vnd.sus-calendar sus susp
+application/vnd.svd svd
+application/vnd.swiftview-ics
+application/vnd.symbian.install sis sisx
+application/vnd.syncml+xml xsm
+application/vnd.syncml.dm+wbxml bdm
+application/vnd.syncml.dm+xml xdm
+application/vnd.syncml.dm.notification
+application/vnd.syncml.ds.notification
+application/vnd.tao.intent-module-archive tao
+application/vnd.tmobile-livetv tmo
+application/vnd.trid.tpt tpt
+application/vnd.triscape.mxs mxs
+application/vnd.trueapp tra
+application/vnd.truedoc
+application/vnd.ufdl ufd ufdl
+application/vnd.uiq.theme utz
+application/vnd.umajin umj
+application/vnd.unity unityweb
+application/vnd.uoml+xml uoml
+application/vnd.uplanet.alert
+application/vnd.uplanet.alert-wbxml
+application/vnd.uplanet.bearer-choice
+application/vnd.uplanet.bearer-choice-wbxml
+application/vnd.uplanet.cacheop
+application/vnd.uplanet.cacheop-wbxml
+application/vnd.uplanet.channel
+application/vnd.uplanet.channel-wbxml
+application/vnd.uplanet.list
+application/vnd.uplanet.list-wbxml
+application/vnd.uplanet.listcmd
+application/vnd.uplanet.listcmd-wbxml
+application/vnd.uplanet.signal
+application/vnd.vcx vcx
+application/vnd.vd-study
+application/vnd.vectorworks
+application/vnd.vidsoft.vidconference
+application/vnd.visio vsd vst vss vsw
+application/vnd.visionary vis
+application/vnd.vividence.scriptfile
+application/vnd.vsf vsf
+application/vnd.wap.sic
+application/vnd.wap.slc
+application/vnd.wap.wbxml wbxml
+application/vnd.wap.wmlc wmlc
+application/vnd.wap.wmlscriptc wmlsc
+application/vnd.webturbo wtb
+application/vnd.wfa.wsc
+application/vnd.wmc
+application/vnd.wmf.bootstrap
+application/vnd.wordperfect wpd
+application/vnd.wqd wqd
+application/vnd.wrq-hp3000-labelled
+application/vnd.wt.stf stf
+application/vnd.wv.csp+wbxml
+application/vnd.wv.csp+xml
+application/vnd.wv.ssp+xml
+application/vnd.xara xar
+application/vnd.xfdl xfdl
+application/vnd.xfdl.webform
+application/vnd.xmi+xml
+application/vnd.xmpie.cpkg
+application/vnd.xmpie.dpkg
+application/vnd.xmpie.plan
+application/vnd.xmpie.ppkg
+application/vnd.xmpie.xlim
+application/vnd.yamaha.hv-dic hvd
+application/vnd.yamaha.hv-script hvs
+application/vnd.yamaha.hv-voice hvp
+application/vnd.yamaha.openscoreformat osf
+application/vnd.yamaha.openscoreformat.osfpvg+xml osfpvg
+application/vnd.yamaha.smaf-audio saf
+application/vnd.yamaha.smaf-phrase spf
+application/vnd.yellowriver-custom-menu cmp
+application/vnd.zul zir zirz
+application/vnd.zzazz.deck+xml zaz
+application/voicexml+xml vxml
+application/watcherinfo+xml
+application/whoispp-query
+application/whoispp-response
+application/winhlp hlp
+application/wita
+application/wordperfect5.1
+application/wsdl+xml wsdl
+application/wspolicy+xml wspolicy
+application/x-abiword abw
+application/x-ace-compressed ace
+application/x-authorware-bin aab x32 u32 vox
+application/x-authorware-map aam
+application/x-authorware-seg aas
+application/x-bcpio bcpio
+application/x-bittorrent torrent
+application/x-bzip bz
+application/x-bzip2 bz2 boz
+application/x-cdlink vcd
+application/x-chat chat
+application/x-chess-pgn pgn
+application/x-compress
+application/x-cpio cpio
+application/x-csh csh
+application/x-debian-package deb udeb
+application/x-director dir dcr dxr cst cct cxt w3d fgd swa
+application/x-doom wad
+application/x-dtbncx+xml ncx
+application/x-dtbook+xml dtb
+application/x-dtbresource+xml res
+application/x-dvi dvi
+application/x-font-bdf bdf
+application/x-font-dos
+application/x-font-framemaker
+application/x-font-ghostscript gsf
+application/x-font-libgrx
+application/x-font-linux-psf psf
+application/x-font-otf otf
+application/x-font-pcf pcf
+application/x-font-snf snf
+application/x-font-speedo
+application/x-font-sunos-news
+application/x-font-ttf ttf ttc
+application/x-font-type1 pfa pfb pfm afm
+application/x-font-vfont
+application/x-futuresplash spl
+application/x-gnumeric gnumeric
+application/x-gtar gtar
+application/x-gzip
+application/x-hdf hdf
+application/x-java-jnlp-file jnlp
+application/x-latex latex
+application/x-mobipocket-ebook prc mobi
+application/x-ms-application application
+application/x-ms-wmd wmd
+application/x-ms-wmz wmz
+application/x-ms-xbap xbap
+application/x-msaccess mdb
+application/x-msbinder obd
+application/x-mscardfile crd
+application/x-msclip clp
+application/x-msdownload exe dll com bat msi
+application/x-msmediaview mvb m13 m14
+application/x-msmetafile wmf
+application/x-msmoney mny
+application/x-mspublisher pub
+application/x-msschedule scd
+application/x-msterminal trm
+application/x-mswrite wri
+application/x-netcdf nc cdf
+application/x-pkcs12 p12 pfx
+application/x-pkcs7-certificates p7b spc
+application/x-pkcs7-certreqresp p7r
+application/x-rar-compressed rar
+application/x-sh sh
+application/x-shar shar
+application/x-shockwave-flash swf
+application/x-silverlight-app xap
+application/x-stuffit sit
+application/x-stuffitx sitx
+application/x-sv4cpio sv4cpio
+application/x-sv4crc sv4crc
+application/x-tar tar
+application/x-tcl tcl
+application/x-tex tex
+application/x-tex-tfm tfm
+application/x-texinfo texinfo texi
+application/x-ustar ustar
+application/x-wais-source src
+application/x-x509-ca-cert der crt
+application/x-xfig fig
+application/x-xpinstall xpi
+application/x400-bp
+application/xcap-att+xml
+application/xcap-caps+xml
+application/xcap-el+xml
+application/xcap-error+xml
+application/xcap-ns+xml
+application/xcon-conference-info-diff+xml
+application/xcon-conference-info+xml
+application/xenc+xml xenc
+application/xhtml+xml xhtml xht
+application/xhtml-voice+xml
+application/xml xml xsl
+application/xml-dtd dtd
+application/xml-external-parsed-entity
+application/xmpp+xml
+application/xop+xml xop
+application/xslt+xml xslt
+application/xspf+xml xspf
+application/xv+xml mxml xhvml xvml xvm
+application/zip zip
+audio/32kadpcm
+audio/3gpp
+audio/3gpp2
+audio/ac3
+audio/adpcm adp
+audio/amr
+audio/amr-wb
+audio/amr-wb+
+audio/asc
+audio/basic au snd
+audio/bv16
+audio/bv32
+audio/clearmode
+audio/cn
+audio/dat12
+audio/dls
+audio/dsr-es201108
+audio/dsr-es202050
+audio/dsr-es202211
+audio/dsr-es202212
+audio/dvi4
+audio/eac3
+audio/evrc
+audio/evrc-qcp
+audio/evrc0
+audio/evrc1
+audio/evrcb
+audio/evrcb0
+audio/evrcb1
+audio/evrcwb
+audio/evrcwb0
+audio/evrcwb1
+audio/example
+audio/g719
+audio/g722
+audio/g7221
+audio/g723
+audio/g726-16
+audio/g726-24
+audio/g726-32
+audio/g726-40
+audio/g728
+audio/g729
+audio/g7291
+audio/g729d
+audio/g729e
+audio/gsm
+audio/gsm-efr
+audio/ilbc
+audio/l16
+audio/l20
+audio/l24
+audio/l8
+audio/lpc
+audio/midi mid midi kar rmi
+audio/mobile-xmf
+audio/mp4 mp4a
+audio/mp4a-latm
+audio/mpa
+audio/mpa-robust
+audio/mpeg mpga mp2 mp2a mp3 m2a m3a
+audio/mpeg4-generic
+audio/ogg oga ogg spx
+audio/parityfec
+audio/pcma
+audio/pcma-wb
+audio/pcmu-wb
+audio/pcmu
+audio/prs.sid
+audio/qcelp
+audio/red
+audio/rtp-enc-aescm128
+audio/rtp-midi
+audio/rtx
+audio/smv
+audio/smv0
+audio/smv-qcp
+audio/sp-midi
+audio/t140c
+audio/t38
+audio/telephone-event
+audio/tone
+audio/ulpfec
+audio/vdvi
+audio/vmr-wb
+audio/vnd.3gpp.iufp
+audio/vnd.4sb
+audio/vnd.audiokoz
+audio/vnd.celp
+audio/vnd.cisco.nse
+audio/vnd.cmles.radio-events
+audio/vnd.cns.anp1
+audio/vnd.cns.inf1
+audio/vnd.digital-winds eol
+audio/vnd.dlna.adts
+audio/vnd.dolby.heaac.1
+audio/vnd.dolby.heaac.2
+audio/vnd.dolby.mlp
+audio/vnd.dolby.mps
+audio/vnd.dolby.pl2
+audio/vnd.dolby.pl2x
+audio/vnd.dolby.pl2z
+audio/vnd.dts dts
+audio/vnd.dts.hd dtshd
+audio/vnd.everad.plj
+audio/vnd.hns.audio
+audio/vnd.lucent.voice lvp
+audio/vnd.ms-playready.media.pya pya
+audio/vnd.nokia.mobile-xmf
+audio/vnd.nortel.vbk
+audio/vnd.nuera.ecelp4800 ecelp4800
+audio/vnd.nuera.ecelp7470 ecelp7470
+audio/vnd.nuera.ecelp9600 ecelp9600
+audio/vnd.octel.sbc
+audio/vnd.qcelp
+audio/vnd.rhetorex.32kadpcm
+audio/vnd.sealedmedia.softseal.mpeg
+audio/vnd.vmx.cvsd
+audio/vorbis
+audio/vorbis-config
+audio/x-aac aac
+audio/x-aiff aif aiff aifc
+audio/x-mpegurl m3u
+audio/x-ms-wax wax
+audio/x-ms-wma wma
+audio/x-pn-realaudio ram ra
+audio/x-pn-realaudio-plugin rmp
+audio/x-wav wav
+chemical/x-cdx cdx
+chemical/x-cif cif
+chemical/x-cmdf cmdf
+chemical/x-cml cml
+chemical/x-csml csml
+chemical/x-pdb
+chemical/x-xyz xyz
+image/bmp bmp
+image/cgm cgm
+image/example
+image/fits
+image/g3fax g3
+image/gif gif
+image/ief ief
+image/jp2
+image/jpeg jpeg jpg jpe
+image/jpm
+image/jpx
+image/naplps
+image/png png
+image/prs.btif btif
+image/prs.pti
+image/svg+xml svg svgz
+image/t38
+image/tiff tiff tif
+image/tiff-fx
+image/vnd.adobe.photoshop psd
+image/vnd.cns.inf2
+image/vnd.djvu djvu djv
+image/vnd.dwg dwg
+image/vnd.dxf dxf
+image/vnd.fastbidsheet fbs
+image/vnd.fpx fpx
+image/vnd.fst fst
+image/vnd.fujixerox.edmics-mmr mmr
+image/vnd.fujixerox.edmics-rlc rlc
+image/vnd.globalgraphics.pgb
+image/vnd.microsoft.icon
+image/vnd.mix
+image/vnd.ms-modi mdi
+image/vnd.net-fpx npx
+image/vnd.radiance
+image/vnd.sealed.png
+image/vnd.sealedmedia.softseal.gif
+image/vnd.sealedmedia.softseal.jpg
+image/vnd.svf
+image/vnd.wap.wbmp wbmp
+image/vnd.xiff xif
+image/x-cmu-raster ras
+image/x-cmx cmx
+image/x-freehand fh fhc fh4 fh5 fh7
+image/x-icon ico
+image/x-pcx pcx
+image/x-pict pic pct
+image/x-portable-anymap pnm
+image/x-portable-bitmap pbm
+image/x-portable-graymap pgm
+image/x-portable-pixmap ppm
+image/x-rgb rgb
+image/x-xbitmap xbm
+image/x-xpixmap xpm
+image/x-xwindowdump xwd
+message/cpim
+message/delivery-status
+message/disposition-notification
+message/example
+message/external-body
+message/global
+message/global-delivery-status
+message/global-disposition-notification
+message/global-headers
+message/http
+message/imdn+xml
+message/news
+message/partial
+message/rfc822 eml mime
+message/s-http
+message/sip
+message/sipfrag
+message/tracking-status
+message/vnd.si.simp
+model/example
+model/iges igs iges
+model/mesh msh mesh silo
+model/vnd.dwf dwf
+model/vnd.flatland.3dml
+model/vnd.gdl gdl
+model/vnd.gs-gdl
+model/vnd.gs.gdl
+model/vnd.gtw gtw
+model/vnd.moml+xml
+model/vnd.mts mts
+model/vnd.parasolid.transmit.binary
+model/vnd.parasolid.transmit.text
+model/vnd.vtu vtu
+model/vrml wrl vrml
+multipart/alternative
+multipart/appledouble
+multipart/byteranges
+multipart/digest
+multipart/encrypted
+multipart/example
+multipart/form-data
+multipart/header-set
+multipart/mixed
+multipart/parallel
+multipart/related
+multipart/report
+multipart/signed
+multipart/voice-message
+text/calendar ics ifb
+text/css css
+text/csv csv
+text/directory
+text/dns
+text/ecmascript
+text/enriched
+text/example
+text/html html htm
+text/javascript
+text/parityfec
+text/plain txt text conf def list log in
+text/prs.fallenstein.rst
+text/prs.lines.tag dsc
+text/red
+text/rfc822-headers
+text/richtext rtx
+text/rtf
+text/rtp-enc-aescm128
+text/rtx
+text/sgml sgml sgm
+text/t140
+text/tab-separated-values tsv
+text/troff t tr roff man me ms
+text/ulpfec
+text/uri-list uri uris urls
+text/vnd.abc
+text/vnd.curl curl
+text/vnd.curl.dcurl dcurl
+text/vnd.curl.scurl scurl
+text/vnd.curl.mcurl mcurl
+text/vnd.dmclientscript
+text/vnd.esmertec.theme-descriptor
+text/vnd.fly fly
+text/vnd.fmi.flexstor flx
+text/vnd.graphviz gv
+text/vnd.in3d.3dml 3dml
+text/vnd.in3d.spot spot
+text/vnd.iptc.newsml
+text/vnd.iptc.nitf
+text/vnd.latex-z
+text/vnd.motorola.reflex
+text/vnd.ms-mediapackage
+text/vnd.net2phone.commcenter.command
+text/vnd.si.uricatalogue
+text/vnd.sun.j2me.app-descriptor jad
+text/vnd.trolltech.linguist
+text/vnd.wap.si
+text/vnd.wap.sl
+text/vnd.wap.wml wml
+text/vnd.wap.wmlscript wmls
+text/x-asm s asm
+text/x-c c cc cxx cpp h hh dic
+text/x-fortran f for f77 f90
+text/x-pascal p pas
+text/x-java-source java
+text/x-setext etx
+text/x-uuencode uu
+text/x-vcalendar vcs
+text/x-vcard vcf
+text/xml
+text/xml-external-parsed-entity
+video/3gpp 3gp
+video/3gpp-tt
+video/3gpp2 3g2
+video/bmpeg
+video/bt656
+video/celb
+video/dv
+video/example
+video/h261 h261
+video/h263 h263
+video/h263-1998
+video/h263-2000
+video/h264 h264
+video/jpeg jpgv
+video/jpeg2000
+video/jpm jpm jpgm
+video/mj2 mj2 mjp2
+video/mp1s
+video/mp2p
+video/mp2t
+video/mp4 mp4 mp4v mpg4
+video/mp4v-es
+video/mpeg mpeg mpg mpe m1v m2v
+video/mpeg4-generic
+video/mpv
+video/nv
+video/ogg ogv
+video/parityfec
+video/pointer
+video/quicktime qt mov
+video/raw
+video/rtp-enc-aescm128
+video/rtx
+video/smpte292m
+video/ulpfec
+video/vc1
+video/vnd.cctv
+video/vnd.dlna.mpeg-tts
+video/vnd.fvt fvt
+video/vnd.hns.video
+video/vnd.iptvforum.1dparityfec-1010
+video/vnd.iptvforum.1dparityfec-2005
+video/vnd.iptvforum.2dparityfec-1010
+video/vnd.iptvforum.2dparityfec-2005
+video/vnd.iptvforum.ttsavc
+video/vnd.iptvforum.ttsmpeg2
+video/vnd.motorola.video
+video/vnd.motorola.videop
+video/vnd.mpegurl mxu m4u
+video/vnd.ms-playready.media.pyv pyv
+video/vnd.nokia.interleaved-multimedia
+video/vnd.nokia.videovoip
+video/vnd.objectvideo
+video/vnd.sealed.mpeg1
+video/vnd.sealed.mpeg4
+video/vnd.sealed.swf
+video/vnd.sealedmedia.softseal.mov
+video/vnd.vivo viv
+video/x-f4v f4v
+video/x-fli fli
+video/x-flv flv
+video/x-m4v m4v
+video/x-ms-asf asf asx
+video/x-ms-wm wm
+video/x-ms-wmv wmv
+video/x-ms-wmx wmx
+video/x-ms-wvx wvx
+video/x-msvideo avi
+video/x-sgi-movie movie
+x-conference/x-cooltalk ice
diff --git a/original/extra/httpd-autoindex.conf b/original/extra/httpd-autoindex.conf
new file mode 100644
index 0000000..c576178
--- /dev/null
+++ b/original/extra/httpd-autoindex.conf
@@ -0,0 +1,93 @@
+#
+# Directives controlling the display of server-generated directory listings.
+#
+# Required modules: mod_autoindex, mod_alias
+#
+# To see the listing of a directory, the Options directive for the
+# directory must include "Indexes", and the directory must not contain
+# a file matching those listed in the DirectoryIndex directive.
+#
+
+#
+# IndexOptions: Controls the appearance of server-generated directory
+# listings.
+#
+IndexOptions FancyIndexing HTMLTable VersionSort
+
+# We include the /icons/ alias for FancyIndexed directory listings. If
+# you do not use FancyIndexing, you may comment this out.
+#
+Alias /icons/ "/opt/local/apache2/icons/"
+
+<Directory "/opt/local/apache2/icons">
+ Options Indexes MultiViews
+ AllowOverride None
+ Order allow,deny
+ Allow from all
+</Directory>
+
+#
+# AddIcon* directives tell the server which icon to show for different
+# files or filename extensions. These are only displayed for
+# FancyIndexed directories.
+#
+AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip
+
+AddIconByType (TXT,/icons/text.gif) text/*
+AddIconByType (IMG,/icons/image2.gif) image/*
+AddIconByType (SND,/icons/sound2.gif) audio/*
+AddIconByType (VID,/icons/movie.gif) video/*
+
+AddIcon /icons/binary.gif .bin .exe
+AddIcon /icons/binhex.gif .hqx
+AddIcon /icons/tar.gif .tar
+AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv
+AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip
+AddIcon /icons/a.gif .ps .ai .eps
+AddIcon /icons/layout.gif .html .shtml .htm .pdf
+AddIcon /icons/text.gif .txt
+AddIcon /icons/c.gif .c
+AddIcon /icons/p.gif .pl .py
+AddIcon /icons/f.gif .for
+AddIcon /icons/dvi.gif .dvi
+AddIcon /icons/uuencoded.gif .uu
+AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl
+AddIcon /icons/tex.gif .tex
+AddIcon /icons/bomb.gif core
+
+AddIcon /icons/back.gif ..
+AddIcon /icons/hand.right.gif README
+AddIcon /icons/folder.gif ^^DIRECTORY^^
+AddIcon /icons/blank.gif ^^BLANKICON^^
+
+#
+# DefaultIcon is which icon to show for files which do not have an icon
+# explicitly set.
+#
+DefaultIcon /icons/unknown.gif
+
+#
+# AddDescription allows you to place a short description after a file in
+# server-generated indexes. These are only displayed for FancyIndexed
+# directories.
+# Format: AddDescription "description" filename
+#
+#AddDescription "GZIP compressed document" .gz
+#AddDescription "tar archive" .tar
+#AddDescription "GZIP compressed tar archive" .tgz
+
+#
+# ReadmeName is the name of the README file the server will look for by
+# default, and append to directory listings.
+#
+# HeaderName is the name of a file which should be prepended to
+# directory indexes.
+ReadmeName README.html
+HeaderName HEADER.html
+
+#
+# IndexIgnore is a set of filenames which directory indexing should ignore
+# and not include in the listing. Shell-style wildcarding is permitted.
+#
+IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t
+
diff --git a/original/extra/httpd-dav.conf b/original/extra/httpd-dav.conf
new file mode 100644
index 0000000..ab7a136
--- /dev/null
+++ b/original/extra/httpd-dav.conf
@@ -0,0 +1,52 @@
+#
+# Distributed authoring and versioning (WebDAV)
+#
+# Required modules: mod_dav, mod_dav_fs, mod_setenvif, mod_alias
+# mod_auth_digest, mod_authn_file
+#
+
+# The following example gives DAV write access to a directory called
+# "uploads" under the ServerRoot directory.
+#
+# The User/Group specified in httpd.conf needs to have write permissions
+# on the directory where the DavLockDB is placed and on any directory where
+# "Dav On" is specified.
+
+DavLockDB "/opt/local/apache2/var/DavLock"
+
+Alias /uploads "/opt/local/apache2/uploads"
+
+<Directory "/opt/local/apache2/uploads">
+ Dav On
+
+ Order Allow,Deny
+ Allow from all
+
+ AuthType Digest
+ AuthName DAV-upload
+
+ # You can use the htdigest program to create the password database:
+ # htdigest -c "/opt/local/apache2/user.passwd" DAV-upload admin
+ AuthUserFile "/opt/local/apache2/user.passwd"
+ AuthDigestProvider file
+
+ # Allow universal read-access, but writes are restricted
+ # to the admin user.
+ <LimitExcept GET OPTIONS>
+ require user admin
+ </LimitExcept>
+</Directory>
+
+#
+# The following directives disable redirects on non-GET requests for
+# a directory that does not include the trailing slash. This fixes a
+# problem with several clients that do not appropriately handle
+# redirects for folders with DAV methods.
+#
+BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully
+BrowserMatch "MS FrontPage" redirect-carefully
+BrowserMatch "^WebDrive" redirect-carefully
+BrowserMatch "^WebDAVFS/1.[0123]" redirect-carefully
+BrowserMatch "^gnome-vfs/1.0" redirect-carefully
+BrowserMatch "^XML Spy" redirect-carefully
+BrowserMatch "^Dreamweaver-WebDAV-SCM1" redirect-carefully
diff --git a/original/extra/httpd-default.conf b/original/extra/httpd-default.conf
new file mode 100644
index 0000000..efeca05
--- /dev/null
+++ b/original/extra/httpd-default.conf
@@ -0,0 +1,75 @@
+#
+# This configuration file reflects default settings for Apache HTTP Server.
+#
+# You may change these, but chances are that you may not need to.
+#
+
+#
+# Timeout: The number of seconds before receives and sends time out.
+#
+Timeout 300
+
+#
+# KeepAlive: Whether or not to allow persistent connections (more than
+# one request per connection). Set to "Off" to deactivate.
+#
+KeepAlive On
+
+#
+# MaxKeepAliveRequests: The maximum number of requests to allow
+# during a persistent connection. Set to 0 to allow an unlimited amount.
+# We recommend you leave this number high, for maximum performance.
+#
+MaxKeepAliveRequests 100
+
+#
+# KeepAliveTimeout: Number of seconds to wait for the next request from the
+# same client on the same connection.
+#
+KeepAliveTimeout 5
+
+#
+# UseCanonicalName: Determines how Apache constructs self-referencing
+# URLs and the SERVER_NAME and SERVER_PORT variables.
+# When set "Off", Apache will use the Hostname and Port supplied
+# by the client. When set "On", Apache will use the value of the
+# ServerName directive.
+#
+UseCanonicalName Off
+
+#
+# AccessFileName: The name of the file to look for in each directory
+# for additional configuration directives. See also the AllowOverride
+# directive.
+#
+AccessFileName .htaccess
+
+#
+# ServerTokens
+# This directive configures what you return as the Server HTTP response
+# Header. The default is 'Full' which sends information about the OS-Type
+# and compiled in modules.
+# Set to one of: Full | OS | Minor | Minimal | Major | Prod
+# where Full conveys the most information, and Prod the least.
+#
+ServerTokens Full
+
+#
+# Optionally add a line containing the server version and virtual host
+# name to server-generated pages (internal error documents, FTP directory
+# listings, mod_status and mod_info output etc., but not CGI generated
+# documents or custom error documents).
+# Set to "EMail" to also include a mailto: link to the ServerAdmin.
+# Set to one of: On | Off | EMail
+#
+ServerSignature On
+
+#
+# HostnameLookups: Log the names of clients or just their IP addresses
+# e.g., www.apache.org (on) or 204.62.129.132 (off).
+# The default is off because it'd be overall better for the net if people
+# had to knowingly turn this feature on, since enabling it means that
+# each client request will result in AT LEAST one lookup request to the
+# nameserver.
+#
+HostnameLookups Off
diff --git a/original/extra/httpd-info.conf b/original/extra/httpd-info.conf
new file mode 100644
index 0000000..db316c0
--- /dev/null
+++ b/original/extra/httpd-info.conf
@@ -0,0 +1,37 @@
+#
+# Get information about the requests being processed by the server
+# and the configuration of the server.
+#
+# Required modules: mod_status (for the server-status handler),
+# mod_info (for the server-info handler)
+
+#
+# Allow server status reports generated by mod_status,
+# with the URL of http://servername/server-status
+# Change the ".example.com" to match your domain to enable.
+
+<Location /server-status>
+ SetHandler server-status
+ Order deny,allow
+ Deny from all
+ Allow from .example.com
+</Location>
+
+#
+# ExtendedStatus controls whether Apache will generate "full" status
+# information (ExtendedStatus On) or just basic information (ExtendedStatus
+# Off) when the "server-status" handler is called. The default is Off.
+#
+#ExtendedStatus On
+
+#
+# Allow remote server configuration reports, with the URL of
+# http://servername/server-info (requires that mod_info.c be loaded).
+# Change the ".example.com" to match your domain to enable.
+#
+<Location /server-info>
+ SetHandler server-info
+ Order deny,allow
+ Deny from all
+ Allow from .example.com
+</Location>
diff --git a/original/extra/httpd-languages.conf b/original/extra/httpd-languages.conf
new file mode 100644
index 0000000..7f66461
--- /dev/null
+++ b/original/extra/httpd-languages.conf
@@ -0,0 +1,141 @@
+#
+# Settings for hosting different languages.
+#
+# Required modules: mod_mime, mod_negotiation
+
+# DefaultLanguage and AddLanguage allows you to specify the language of
+# a document. You can then use content negotiation to give a browser a
+# file in a language the user can understand.
+#
+# Specify a default language. This means that all data
+# going out without a specific language tag (see below) will
+# be marked with this one. You probably do NOT want to set
+# this unless you are sure it is correct for all cases.
+#
+# * It is generally better to not mark a page as
+# * being a certain language than marking it with the wrong
+# * language!
+#
+# DefaultLanguage nl
+#
+# Note 1: The suffix does not have to be the same as the language
+# keyword --- those with documents in Polish (whose net-standard
+# language code is pl) may wish to use "AddLanguage pl .po" to
+# avoid the ambiguity with the common suffix for perl scripts.
+#
+# Note 2: The example entries below illustrate that in some cases
+# the two character 'Language' abbreviation is not identical to
+# the two character 'Country' code for its country,
+# E.g. 'Danmark/dk' versus 'Danish/da'.
+#
+# Note 3: In the case of 'ltz' we violate the RFC by using a three char
+# specifier. There is 'work in progress' to fix this and get
+# the reference data for rfc1766 cleaned up.
+#
+# Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl)
+# English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de)
+# Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja)
+# Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn)
+# Norwegian (no) - Polish (pl) - Portugese (pt)
+# Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv)
+# Turkish (tr) - Simplified Chinese (zh-CN) - Spanish (es)
+# Traditional Chinese (zh-TW)
+#
+AddLanguage ca .ca
+AddLanguage cs .cz .cs
+AddLanguage da .dk
+AddLanguage de .de
+AddLanguage el .el
+AddLanguage en .en
+AddLanguage eo .eo
+AddLanguage es .es
+AddLanguage et .et
+AddLanguage fr .fr
+AddLanguage he .he
+AddLanguage hr .hr
+AddLanguage it .it
+AddLanguage ja .ja
+AddLanguage ko .ko
+AddLanguage ltz .ltz
+AddLanguage nl .nl
+AddLanguage nn .nn
+AddLanguage no .no
+AddLanguage pl .po
+AddLanguage pt .pt
+AddLanguage pt-BR .pt-br
+AddLanguage ru .ru
+AddLanguage sv .sv
+AddLanguage tr .tr
+AddLanguage zh-CN .zh-cn
+AddLanguage zh-TW .zh-tw
+
+# LanguagePriority allows you to give precedence to some languages
+# in case of a tie during content negotiation.
+#
+# Just list the languages in decreasing order of preference. We have
+# more or less alphabetized them here. You probably want to change this.
+#
+LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv tr zh-CN zh-TW
+
+#
+# ForceLanguagePriority allows you to serve a result page rather than
+# MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback)
+# [in case no accepted languages matched the available variants]
+#
+ForceLanguagePriority Prefer Fallback
+
+#
+# Commonly used filename extensions to character sets. You probably
+# want to avoid clashes with the language extensions, unless you
+# are good at carefully testing your setup after each change.
+# See http://www.iana.org/assignments/character-sets for the
+# official list of charset names and their respective RFCs.
+#
+AddCharset us-ascii.ascii .us-ascii
+AddCharset ISO-8859-1 .iso8859-1 .latin1
+AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen
+AddCharset ISO-8859-3 .iso8859-3 .latin3
+AddCharset ISO-8859-4 .iso8859-4 .latin4
+AddCharset ISO-8859-5 .iso8859-5 .cyr .iso-ru
+AddCharset ISO-8859-6 .iso8859-6 .arb .arabic
+AddCharset ISO-8859-7 .iso8859-7 .grk .greek
+AddCharset ISO-8859-8 .iso8859-8 .heb .hebrew
+AddCharset ISO-8859-9 .iso8859-9 .latin5 .trk
+AddCharset ISO-8859-10 .iso8859-10 .latin6
+AddCharset ISO-8859-13 .iso8859-13
+AddCharset ISO-8859-14 .iso8859-14 .latin8
+AddCharset ISO-8859-15 .iso8859-15 .latin9
+AddCharset ISO-8859-16 .iso8859-16 .latin10
+AddCharset ISO-2022-JP .iso2022-jp .jis
+AddCharset ISO-2022-KR .iso2022-kr .kis
+AddCharset ISO-2022-CN .iso2022-cn .cis
+AddCharset Big5.Big5 .big5 .b5
+AddCharset cn-Big5 .cn-big5
+# For russian, more than one charset is used (depends on client, mostly):
+AddCharset WINDOWS-1251 .cp-1251 .win-1251
+AddCharset CP866 .cp866
+AddCharset KOI8 .koi8
+AddCharset KOI8-E .koi8-e
+AddCharset KOI8-r .koi8-r .koi8-ru
+AddCharset KOI8-U .koi8-u
+AddCharset KOI8-ru .koi8-uk .ua
+AddCharset ISO-10646-UCS-2 .ucs2
+AddCharset ISO-10646-UCS-4 .ucs4
+AddCharset UTF-7 .utf7
+AddCharset UTF-8 .utf8
+AddCharset UTF-16 .utf16
+AddCharset UTF-16BE .utf16be
+AddCharset UTF-16LE .utf16le
+AddCharset UTF-32 .utf32
+AddCharset UTF-32BE .utf32be
+AddCharset UTF-32LE .utf32le
+AddCharset euc-cn .euc-cn
+AddCharset euc-gb .euc-gb
+AddCharset euc-jp .euc-jp
+AddCharset euc-kr .euc-kr
+#Not sure how euc-tw got in - IANA doesn't list it???
+AddCharset EUC-TW .euc-tw
+AddCharset gb2312 .gb2312 .gb
+AddCharset iso-10646-ucs-2 .ucs-2 .iso-10646-ucs-2
+AddCharset iso-10646-ucs-4 .ucs-4 .iso-10646-ucs-4
+AddCharset shift_jis .shift_jis .sjis
diff --git a/original/extra/httpd-manual.conf b/original/extra/httpd-manual.conf
new file mode 100644
index 0000000..71e4fc8
--- /dev/null
+++ b/original/extra/httpd-manual.conf
@@ -0,0 +1,31 @@
+#
+# Provide access to the documentation on your server as
+# http://yourserver.example.com/manual/
+# The documentation is always available at
+# http://httpd.apache.org/docs/2.2/
+#
+# Required modules: mod_alias, mod_setenvif, mod_negotiation
+#
+
+AliasMatch ^/manual(?:/(?:de|en|es|fr|ja|ko|pt-br|ru|tr))?(/.*)?$ "/opt/local/apache2/manual$1"
+
+<Directory "/opt/local/apache2/manual">
+ Options Indexes
+ AllowOverride None
+ Order allow,deny
+ Allow from all
+
+ <Files *.html>
+ SetHandler type-map
+ </Files>
+ # .tr is text/troff in mime.types!
+ <Files *.html.tr.utf8>
+ ForceType text/html
+ </Files>
+
+ SetEnvIf Request_URI ^/manual/(de|en|es|fr|ja|ko|pt-br|ru|tr)/ prefer-language=$1
+ RedirectMatch 301 ^/manual(?:/(de|en|es|fr|ja|ko|pt-br|ru|tr)){2,}(/.*)?$ /manual/$1$2
+
+ LanguagePriority en de es fr ja ko pt-br ru tr
+ ForceLanguagePriority Prefer Fallback
+</Directory>
diff --git a/original/extra/httpd-mpm.conf b/original/extra/httpd-mpm.conf
new file mode 100644
index 0000000..8c44c60
--- /dev/null
+++ b/original/extra/httpd-mpm.conf
@@ -0,0 +1,110 @@
+#
+# Server-Pool Management (MPM specific)
+#
+
+#
+# PidFile: The file in which the server should record its process
+# identification number when it starts.
+#
+# Note that this is the default PidFile for most MPMs.
+#
+<IfModule !mpm_netware_module>
+ PidFile "logs/httpd.pid"
+</IfModule>
+
+#
+# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
+#
+<IfModule !mpm_winnt_module>
+<IfModule !mpm_netware_module>
+LockFile "logs/accept.lock"
+</IfModule>
+</IfModule>
+
+#
+# Only one of the below sections will be relevant on your
+# installed httpd. Use "apachectl -l" to find out the
+# active mpm.
+#
+
+# prefork MPM
+# StartServers: number of server processes to start
+# MinSpareServers: minimum number of server processes which are kept spare
+# MaxSpareServers: maximum number of server processes which are kept spare
+# MaxClients: maximum number of server processes allowed to start
+# MaxRequestsPerChild: maximum number of requests a server process serves
+<IfModule mpm_prefork_module>
+ StartServers 5
+ MinSpareServers 5
+ MaxSpareServers 10
+ MaxClients 150
+ MaxRequestsPerChild 0
+</IfModule>
+
+# worker MPM
+# StartServers: initial number of server processes to start
+# MaxClients: maximum number of simultaneous client connections
+# MinSpareThreads: minimum number of worker threads which are kept spare
+# MaxSpareThreads: maximum number of worker threads which are kept spare
+# ThreadsPerChild: constant number of worker threads in each server process
+# MaxRequestsPerChild: maximum number of requests a server process serves
+<IfModule mpm_worker_module>
+ StartServers 2
+ MaxClients 150
+ MinSpareThreads 25
+ MaxSpareThreads 75
+ ThreadsPerChild 25
+ MaxRequestsPerChild 0
+</IfModule>
+
+# BeOS MPM
+# StartThreads: how many threads do we initially spawn?
+# MaxClients: max number of threads we can have (1 thread == 1 client)
+# MaxRequestsPerThread: maximum number of requests each thread will process
+<IfModule mpm_beos_module>
+ StartThreads 10
+ MaxClients 50
+ MaxRequestsPerThread 10000
+</IfModule>
+
+# NetWare MPM
+# ThreadStackSize: Stack size allocated for each worker thread
+# StartThreads: Number of worker threads launched at server startup
+# MinSpareThreads: Minimum number of idle threads, to handle request spikes
+# MaxSpareThreads: Maximum number of idle threads
+# MaxThreads: Maximum number of worker threads alive at the same time
+# MaxRequestsPerChild: Maximum number of requests a thread serves. It is
+# recommended that the default value of 0 be set for this
+# directive on NetWare. This will allow the thread to
+# continue to service requests indefinitely.
+<IfModule mpm_netware_module>
+ ThreadStackSize 65536
+ StartThreads 250
+ MinSpareThreads 25
+ MaxSpareThreads 250
+ MaxThreads 1000
+ MaxRequestsPerChild 0
+ MaxMemFree 100
+</IfModule>
+
+# OS/2 MPM
+# StartServers: Number of server processes to maintain
+# MinSpareThreads: Minimum number of idle threads per process,
+# to handle request spikes
+# MaxSpareThreads: Maximum number of idle threads per process
+# MaxRequestsPerChild: Maximum number of connections per server process
+<IfModule mpm_mpmt_os2_module>
+ StartServers 2
+ MinSpareThreads 5
+ MaxSpareThreads 10
+ MaxRequestsPerChild 0
+</IfModule>
+
+# WinNT MPM
+# ThreadsPerChild: constant number of worker threads in the server process
+# MaxRequestsPerChild: maximum number of requests a server process serves
+<IfModule mpm_winnt_module>
+ ThreadsPerChild 150
+ MaxRequestsPerChild 0
+</IfModule>
+
diff --git a/original/extra/httpd-multilang-errordoc.conf b/original/extra/httpd-multilang-errordoc.conf
new file mode 100644
index 0000000..b45fbe8
--- /dev/null
+++ b/original/extra/httpd-multilang-errordoc.conf
@@ -0,0 +1,52 @@
+#
+# The configuration below implements multi-language error documents through
+# content-negotiation.
+#
+# Required modules: mod_alias, mod_include, mod_negotiation
+#
+# We use Alias to redirect any /error/HTTP_<error>.html.var response to
+# our collection of by-error message multi-language collections. We use
+# includes to substitute the appropriate text.
+#
+# You can modify the messages' appearance without changing any of the
+# default HTTP_<error>.html.var files by adding the line:
+#
+# Alias /error/include/ "/your/include/path/"
+#
+# which allows you to create your own set of files by starting with the
+# /opt/local/apache2/error/include/ files and copying them to /your/include/path/,
+# even on a per-VirtualHost basis. The default include files will display
+# your Apache version number and your ServerAdmin email address regardless
+# of the setting of ServerSignature.
+
+Alias /error/ "/opt/local/apache2/error/"
+
+<Directory "/opt/local/apache2/error">
+ AllowOverride None
+ Options IncludesNoExec
+ AddOutputFilter Includes html
+ AddHandler type-map var
+ Order allow,deny
+ Allow from all
+ LanguagePriority en cs de es fr it ja ko nl pl pt-br ro sv tr
+ ForceLanguagePriority Prefer Fallback
+</Directory>
+
+ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var
+ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var
+ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var
+ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var
+ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var
+ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var
+ErrorDocument 410 /error/HTTP_GONE.html.var
+ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var
+ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var
+ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var
+ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var
+ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var
+ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var
+ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var
+ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var
+ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var
+ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var
+
diff --git a/original/extra/httpd-ssl.conf b/original/extra/httpd-ssl.conf
new file mode 100644
index 0000000..814aa0c
--- /dev/null
+++ b/original/extra/httpd-ssl.conf
@@ -0,0 +1,231 @@
+#
+# This is the Apache server configuration file providing SSL support.
+# It contains the configuration directives to instruct the server how to
+# serve pages over an https connection. For detailing information about these
+# directives see <URL:http://httpd.apache.org/docs/2.2/mod/mod_ssl.html>
+#
+# Do NOT simply read the instructions in here without understanding
+# what they do. They're here only as hints or reminders. If you are unsure
+# consult the online docs. You have been warned.
+#
+
+#
+# Pseudo Random Number Generator (PRNG):
+# Configure one or more sources to seed the PRNG of the SSL library.
+# The seed data should be of good random quality.
+# WARNING! On some platforms /dev/random blocks if not enough entropy
+# is available. This means you then cannot use the /dev/random device
+# because it would lead to very long connection times (as long as
+# it requires to make more entropy available). But usually those
+# platforms additionally provide a /dev/urandom device which doesn't
+# block. So, if available, use this one instead. Read the mod_ssl User
+# Manual for more details.
+#
+#SSLRandomSeed startup file:/dev/random 512
+#SSLRandomSeed startup file:/dev/urandom 512
+#SSLRandomSeed connect file:/dev/random 512
+#SSLRandomSeed connect file:/dev/urandom 512
+
+
+#
+# When we also provide SSL we have to listen to the
+# standard HTTP port (see above) and to the HTTPS port
+#
+# Note: Configurations that use IPv6 but not IPv4-mapped addresses need two
+# Listen directives: "Listen [::]:443" and "Listen 0.0.0.0:443"
+#
+Listen 443
+
+##
+## SSL Global Context
+##
+## All SSL configuration in this context applies both to
+## the main server and all SSL-enabled virtual hosts.
+##
+
+#
+# Some MIME-types for downloading Certificates and CRLs
+#
+AddType application/x-x509-ca-cert .crt
+AddType application/x-pkcs7-crl .crl
+
+# Pass Phrase Dialog:
+# Configure the pass phrase gathering process.
+# The filtering dialog program (`builtin' is a internal
+# terminal dialog) has to provide the pass phrase on stdout.
+SSLPassPhraseDialog builtin
+
+# Inter-Process Session Cache:
+# Configure the SSL Session Cache: First the mechanism
+# to use and second the expiring timeout (in seconds).
+#SSLSessionCache "dbm:/opt/local/apache2/logs/ssl_scache"
+SSLSessionCache "shmcb:/opt/local/apache2/logs/ssl_scache(512000)"
+SSLSessionCacheTimeout 300
+
+# Semaphore:
+# Configure the path to the mutual exclusion semaphore the
+# SSL engine uses internally for inter-process synchronization.
+SSLMutex "file:/opt/local/apache2/logs/ssl_mutex"
+
+##
+## SSL Virtual Host Context
+##
+
+<VirtualHost _default_:443>
+
+# General setup for the virtual host
+DocumentRoot "/opt/local/apache2/htdocs"
+ServerName www.example.com:443
+ServerAdmin you@example.com
+ErrorLog "/opt/local/apache2/logs/error_log"
+TransferLog "/opt/local/apache2/logs/access_log"
+
+# SSL Engine Switch:
+# Enable/Disable SSL for this virtual host.
+SSLEngine on
+
+# SSL Cipher Suite:
+# List the ciphers that the client is permitted to negotiate.
+# See the mod_ssl documentation for a complete list.
+SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
+
+# Server Certificate:
+# Point SSLCertificateFile at a PEM encoded certificate. If
+# the certificate is encrypted, then you will be prompted for a
+# pass phrase. Note that a kill -HUP will prompt again. Keep
+# in mind that if you have both an RSA and a DSA certificate you
+# can configure both in parallel (to also allow the use of DSA
+# ciphers, etc.)
+SSLCertificateFile "/opt/local/apache2/conf/server.crt"
+#SSLCertificateFile "/opt/local/apache2/conf/server-dsa.crt"
+
+# Server Private Key:
+# If the key is not combined with the certificate, use this
+# directive to point at the key file. Keep in mind that if
+# you've both a RSA and a DSA private key you can configure
+# both in parallel (to also allow the use of DSA ciphers, etc.)
+SSLCertificateKeyFile "/opt/local/apache2/conf/server.key"
+#SSLCertificateKeyFile "/opt/local/apache2/conf/server-dsa.key"
+
+# Server Certificate Chain:
+# Point SSLCertificateChainFile at a file containing the
+# concatenation of PEM encoded CA certificates which form the
+# certificate chain for the server certificate. Alternatively
+# the referenced file can be the same as SSLCertificateFile
+# when the CA certificates are directly appended to the server
+# certificate for convinience.
+#SSLCertificateChainFile "/opt/local/apache2/conf/server-ca.crt"
+
+# Certificate Authority (CA):
+# Set the CA certificate verification path where to find CA
+# certificates for client authentication or alternatively one
+# huge file containing all of them (file must be PEM encoded)
+# Note: Inside SSLCACertificatePath you need hash symlinks
+# to point to the certificate files. Use the provided
+# Makefile to update the hash symlinks after changes.
+#SSLCACertificatePath "/opt/local/apache2/conf/ssl.crt"
+#SSLCACertificateFile "/opt/local/apache2/conf/ssl.crt/ca-bundle.crt"
+
+# Certificate Revocation Lists (CRL):
+# Set the CA revocation path where to find CA CRLs for client
+# authentication or alternatively one huge file containing all
+# of them (file must be PEM encoded)
+# Note: Inside SSLCARevocationPath you need hash symlinks
+# to point to the certificate files. Use the provided
+# Makefile to update the hash symlinks after changes.
+#SSLCARevocationPath "/opt/local/apache2/conf/ssl.crl"
+#SSLCARevocationFile "/opt/local/apache2/conf/ssl.crl/ca-bundle.crl"
+
+# Client Authentication (Type):
+# Client certificate verification type and depth. Types are
+# none, optional, require and optional_no_ca. Depth is a
+# number which specifies how deeply to verify the certificate
+# issuer chain before deciding the certificate is not valid.
+#SSLVerifyClient require
+#SSLVerifyDepth 10
+
+# Access Control:
+# With SSLRequire you can do per-directory access control based
+# on arbitrary complex boolean expressions containing server
+# variable checks and other lookup directives. The syntax is a
+# mixture between C and Perl. See the mod_ssl documentation
+# for more details.
+#<Location />
+#SSLRequire ( %{SSL_CIPHER} !~ m/^(EXP|NULL)/ \
+# and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." \
+# and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} \
+# and %{TIME_WDAY} >= 1 and %{TIME_WDAY} <= 5 \
+# and %{TIME_HOUR} >= 8 and %{TIME_HOUR} <= 20 ) \
+# or %{REMOTE_ADDR} =~ m/^192\.76\.162\.[0-9]+$/
+#</Location>
+
+# SSL Engine Options:
+# Set various options for the SSL engine.
+# o FakeBasicAuth:
+# Translate the client X.509 into a Basic Authorisation. This means that
+# the standard Auth/DBMAuth methods can be used for access control. The
+# user name is the `one line' version of the client's X.509 certificate.
+# Note that no password is obtained from the user. Every entry in the user
+# file needs this password: `xxj31ZMTZzkVA'.
+# o ExportCertData:
+# This exports two additional environment variables: SSL_CLIENT_CERT and
+# SSL_SERVER_CERT. These contain the PEM-encoded certificates of the
+# server (always existing) and the client (only existing when client
+# authentication is used). This can be used to import the certificates
+# into CGI scripts.
+# o StdEnvVars:
+# This exports the standard SSL/TLS related `SSL_*' environment variables.
+# Per default this exportation is switched off for performance reasons,
+# because the extraction step is an expensive operation and is usually
+# useless for serving static content. So one usually enables the
+# exportation for CGI and SSI requests only.
+# o StrictRequire:
+# This denies access when "SSLRequireSSL" or "SSLRequire" applied even
+# under a "Satisfy any" situation, i.e. when it applies access is denied
+# and no other module can change it.
+# o OptRenegotiate:
+# This enables optimized SSL connection renegotiation handling when SSL
+# directives are used in per-directory context.
+#SSLOptions +FakeBasicAuth +ExportCertData +StrictRequire
+<FilesMatch "\.(cgi|shtml|phtml|php)$">
+ SSLOptions +StdEnvVars
+</FilesMatch>
+<Directory "/opt/local/apache2/cgi-bin">
+ SSLOptions +StdEnvVars
+</Directory>
+
+# SSL Protocol Adjustments:
+# The safe and default but still SSL/TLS standard compliant shutdown
+# approach is that mod_ssl sends the close notify alert but doesn't wait for
+# the close notify alert from client. When you need a different shutdown
+# approach you can use one of the following variables:
+# o ssl-unclean-shutdown:
+# This forces an unclean shutdown when the connection is closed, i.e. no
+# SSL close notify alert is send or allowed to received. This violates
+# the SSL/TLS standard but is needed for some brain-dead browsers. Use
+# this when you receive I/O errors because of the standard approach where
+# mod_ssl sends the close notify alert.
+# o ssl-accurate-shutdown:
+# This forces an accurate shutdown when the connection is closed, i.e. a
+# SSL close notify alert is send and mod_ssl waits for the close notify
+# alert of the client. This is 100% SSL/TLS standard compliant, but in
+# practice often causes hanging connections with brain-dead browsers. Use
+# this only for browsers where you know that their SSL implementation
+# works correctly.
+# Notice: Most problems of broken clients are also related to the HTTP
+# keep-alive facility, so you usually additionally want to disable
+# keep-alive for those clients, too. Use variable "nokeepalive" for this.
+# Similarly, one has to force some clients to use HTTP/1.0 to workaround
+# their broken HTTP/1.1 implementation. Use variables "downgrade-1.0" and
+# "force-response-1.0" for this.
+BrowserMatch ".*MSIE.*" \
+ nokeepalive ssl-unclean-shutdown \
+ downgrade-1.0 force-response-1.0
+
+# Per-Server Logging:
+# The home of a custom SSL log file. Use this when you want a
+# compact non-error SSL logfile on a virtual host basis.
+CustomLog "/opt/local/apache2/logs/ssl_request_log" \
+ "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
+
+</VirtualHost>
diff --git a/original/extra/httpd-userdir.conf b/original/extra/httpd-userdir.conf
new file mode 100644
index 0000000..24df593
--- /dev/null
+++ b/original/extra/httpd-userdir.conf
@@ -0,0 +1,28 @@
+# Settings for user home directories
+#
+# Required module: mod_userdir
+
+#
+# UserDir: The name of the directory that is appended onto a user's home
+# directory if a ~user request is received. Note that you must also set
+# the default access control for these directories, as in the example below.
+#
+UserDir Sites
+
+#
+# Control access to UserDir directories. The following is an example
+# for a site where these directories are restricted to read-only.
+#
+<Directory "/Users/*/Sites">
+ AllowOverride FileInfo AuthConfig Limit Indexes
+ Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
+ <Limit GET POST OPTIONS>
+ Order allow,deny
+ Allow from all
+ </Limit>
+ <LimitExcept GET POST OPTIONS>
+ Order deny,allow
+ Deny from all
+ </LimitExcept>
+</Directory>
+
diff --git a/original/extra/httpd-vhosts.conf b/original/extra/httpd-vhosts.conf
new file mode 100644
index 0000000..fca78a0
--- /dev/null
+++ b/original/extra/httpd-vhosts.conf
@@ -0,0 +1,45 @@
+#
+# Virtual Hosts
+#
+# If you want to maintain multiple domains/hostnames on your
+# machine you can setup VirtualHost containers for them. Most configurations
+# use only name-based virtual hosts so the server doesn't need to worry about
+# IP addresses. This is indicated by the asterisks in the directives below.
+#
+# Please see the documentation at
+# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
+# for further details before you try to setup virtual hosts.
+#
+# You may use the command line option '-S' to verify your virtual host
+# configuration.
+
+#
+# Use name-based virtual hosting.
+#
+NameVirtualHost *:80
+
+#
+# VirtualHost example:
+# Almost any Apache directive may go into a VirtualHost container.
+# The first VirtualHost section is used for all requests that do not
+# match a ServerName or ServerAlias in any <VirtualHost> block.
+#
+<VirtualHost *:80>
+ ServerAdmin webmaster@dummy-host.example.com
+ DocumentRoot "/opt/local/apache2/docs/dummy-host.example.com"
+ ServerName dummy-host.example.com
+ ServerAlias www.dummy-host.example.com
+ ErrorLog "logs/dummy-host.example.com-error_log"
+ CustomLog "logs/dummy-host.example.com-access_log" common
+</VirtualHost>
+
+<VirtualHost *:80>
+ ServerAdmin webmaster@dummy-host2.example.com
+ DocumentRoot "/opt/local/apache2/docs/dummy-host2.example.com"
+ ServerName dummy-host2.example.com
+ ErrorLog "logs/dummy-host2.example.com-error_log"
+ CustomLog "logs/dummy-host2.example.com-access_log" common
+</VirtualHost>
+
+
+
diff --git a/original/httpd.conf b/original/httpd.conf
new file mode 100644
index 0000000..68ba8ad
--- /dev/null
+++ b/original/httpd.conf
@@ -0,0 +1,480 @@
+#
+# This is the main Apache HTTP server configuration file. It contains the
+# configuration directives that give the server its instructions.
+# See <URL:http://httpd.apache.org/docs/2.2> for detailed information.
+# In particular, see
+# <URL:http://httpd.apache.org/docs/2.2/mod/directives.html>
+# for a discussion of each configuration directive.
+#
+# Do NOT simply read the instructions in here without understanding
+# what they do. They're here only as hints or reminders. If you are unsure
+# consult the online docs. You have been warned.
+#
+# Configuration and logfile names: If the filenames you specify for many
+# of the server's control files begin with "/" (or "drive:/" for Win32), the
+# server will use that explicit path. If the filenames do *not* begin
+# with "/", the value of ServerRoot is prepended -- so "logs/foo_log"
+# with ServerRoot set to "/opt/local/apache2" will be interpreted by the
+# server as "/opt/local/apache2/logs/foo_log".
+
+#
+# ServerRoot: The top of the directory tree under which the server's
+# configuration, error, and log files are kept.
+#
+# Do not add a slash at the end of the directory path. If you point
+# ServerRoot at a non-local disk, be sure to point the LockFile directive
+# at a local disk. If you wish to share the same ServerRoot for multiple
+# httpd daemons, you will need to change at least LockFile and PidFile.
+#
+ServerRoot "/opt/local/apache2"
+
+#
+# Listen: Allows you to bind Apache to specific IP addresses and/or
+# ports, instead of the default. See also the <VirtualHost>
+# directive.
+#
+# Change this to Listen on specific IP addresses as shown below to
+# prevent Apache from glomming onto all bound IP addresses.
+#
+#Listen 12.34.56.78:80
+Listen 80
+
+#
+# Dynamic Shared Object (DSO) Support
+#
+# To be able to use the functionality of a module which was built as a DSO you
+# have to place corresponding `LoadModule' lines at this location so the
+# directives contained in it are actually available _before_ they are used.
+# Statically compiled modules (those listed by `httpd -l') do not need
+# to be loaded here.
+#
+# Example:
+# LoadModule foo_module modules/mod_foo.so
+#
+LoadModule authn_file_module modules/mod_authn_file.so
+LoadModule authn_dbm_module modules/mod_authn_dbm.so
+LoadModule authn_anon_module modules/mod_authn_anon.so
+LoadModule authn_dbd_module modules/mod_authn_dbd.so
+LoadModule authn_default_module modules/mod_authn_default.so
+LoadModule authz_host_module modules/mod_authz_host.so
+LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
+LoadModule authz_user_module modules/mod_authz_user.so
+LoadModule authz_dbm_module modules/mod_authz_dbm.so
+LoadModule authz_owner_module modules/mod_authz_owner.so
+LoadModule authz_default_module modules/mod_authz_default.so
+LoadModule auth_basic_module modules/mod_auth_basic.so
+LoadModule auth_digest_module modules/mod_auth_digest.so
+LoadModule file_cache_module modules/mod_file_cache.so
+LoadModule cache_module modules/mod_cache.so
+LoadModule disk_cache_module modules/mod_disk_cache.so
+LoadModule mem_cache_module modules/mod_mem_cache.so
+LoadModule dbd_module modules/mod_dbd.so
+LoadModule dumpio_module modules/mod_dumpio.so
+LoadModule ext_filter_module modules/mod_ext_filter.so
+LoadModule include_module modules/mod_include.so
+LoadModule filter_module modules/mod_filter.so
+LoadModule substitute_module modules/mod_substitute.so
+LoadModule deflate_module modules/mod_deflate.so
+LoadModule log_config_module modules/mod_log_config.so
+LoadModule log_forensic_module modules/mod_log_forensic.so
+LoadModule logio_module modules/mod_logio.so
+LoadModule env_module modules/mod_env.so
+LoadModule mime_magic_module modules/mod_mime_magic.so
+LoadModule cern_meta_module modules/mod_cern_meta.so
+LoadModule expires_module modules/mod_expires.so
+LoadModule headers_module modules/mod_headers.so
+LoadModule ident_module modules/mod_ident.so
+LoadModule usertrack_module modules/mod_usertrack.so
+LoadModule unique_id_module modules/mod_unique_id.so
+LoadModule setenvif_module modules/mod_setenvif.so
+LoadModule version_module modules/mod_version.so
+LoadModule proxy_module modules/mod_proxy.so
+LoadModule proxy_connect_module modules/mod_proxy_connect.so
+LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
+LoadModule proxy_http_module modules/mod_proxy_http.so
+LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
+LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
+LoadModule ssl_module modules/mod_ssl.so
+LoadModule mime_module modules/mod_mime.so
+LoadModule dav_module modules/mod_dav.so
+LoadModule status_module modules/mod_status.so
+LoadModule autoindex_module modules/mod_autoindex.so
+LoadModule asis_module modules/mod_asis.so
+LoadModule info_module modules/mod_info.so
+LoadModule cgi_module modules/mod_cgi.so
+LoadModule dav_fs_module modules/mod_dav_fs.so
+LoadModule vhost_alias_module modules/mod_vhost_alias.so
+LoadModule negotiation_module modules/mod_negotiation.so
+LoadModule dir_module modules/mod_dir.so
+LoadModule imagemap_module modules/mod_imagemap.so
+LoadModule actions_module modules/mod_actions.so
+LoadModule speling_module modules/mod_speling.so
+LoadModule userdir_module modules/mod_userdir.so
+LoadModule alias_module modules/mod_alias.so
+LoadModule rewrite_module modules/mod_rewrite.so
+
+<IfModule !mpm_netware_module>
+<IfModule !mpm_winnt_module>
+#
+# If you wish httpd to run as a different user or group, you must run
+# httpd as root initially and it will switch.
+#
+# User/Group: The name (or #number) of the user/group to run httpd as.
+# It is usually good practice to create a dedicated user and group for
+# running httpd, as with most system services.
+#
+User www
+Group www
+
+</IfModule>
+</IfModule>
+
+# 'Main' server configuration
+#
+# The directives in this section set up the values used by the 'main'
+# server, which responds to any requests that aren't handled by a
+# <VirtualHost> definition. These values also provide defaults for
+# any <VirtualHost> containers you may define later in the file.
+#
+# All of these directives may appear inside <VirtualHost> containers,
+# in which case these default settings will be overridden for the
+# virtual host being defined.
+#
+
+#
+# ServerAdmin: Your address, where problems with the server should be
+# e-mailed. This address appears on some server-generated pages, such
+# as error documents. e.g. admin@your-domain.com
+#
+ServerAdmin you@example.com
+
+#
+# ServerName gives the name and port that the server uses to identify itself.
+# This can often be determined automatically, but we recommend you specify
+# it explicitly to prevent problems during startup.
+#
+# If your host doesn't have a registered DNS name, enter its IP address here.
+#
+#ServerName www.example.com:80
+
+#
+# DocumentRoot: The directory out of which you will serve your
+# documents. By default, all requests are taken from this directory, but
+# symbolic links and aliases may be used to point to other locations.
+#
+DocumentRoot "/opt/local/apache2/htdocs"
+
+#
+# Each directory to which Apache has access can be configured with respect
+# to which services and features are allowed and/or disabled in that
+# directory (and its subdirectories).
+#
+# First, we configure the "default" to be a very restrictive set of
+# features.
+#
+<Directory />
+ Options FollowSymLinks
+ AllowOverride None
+ Order deny,allow
+ Deny from all
+</Directory>
+
+#
+# Note that from this point forward you must specifically allow
+# particular features to be enabled - so if something's not working as
+# you might expect, make sure that you have specifically enabled it
+# below.
+#
+
+#
+# This should be changed to whatever you set DocumentRoot to.
+#
+<Directory "/opt/local/apache2/htdocs">
+ #
+ # Possible values for the Options directive are "None", "All",
+ # or any combination of:
+ # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
+ #
+ # Note that "MultiViews" must be named *explicitly* --- "Options All"
+ # doesn't give it to you.
+ #
+ # The Options directive is both complicated and important. Please see
+ # http://httpd.apache.org/docs/2.2/mod/core.html#options
+ # for more information.
+ #
+ Options Indexes FollowSymLinks
+
+ #
+ # AllowOverride controls what directives may be placed in .htaccess files.
+ # It can be "All", "None", or any combination of the keywords:
+ # Options FileInfo AuthConfig Limit
+ #
+ AllowOverride None
+
+ #
+ # Controls who can get stuff from this server.
+ #
+ Order allow,deny
+ Allow from all
+
+</Directory>
+
+#
+# DirectoryIndex: sets the file that Apache will serve if a directory
+# is requested.
+#
+<IfModule dir_module>
+ DirectoryIndex index.html
+</IfModule>
+
+#
+# The following lines prevent .htaccess, .htpasswd and .DS_Store files and
+# Mac resource forks and named forks from being viewed by Web clients.
+#
+<Files ~ "^\.([Hh][Tt]|[Dd][Ss]_[Ss])">
+ Order allow,deny
+ Deny from all
+ Satisfy All
+</Files>
+<Files "rsrc">
+ Order allow,deny
+ Deny from all
+ Satisfy All
+</Files>
+<DirectoryMatch ".*\.\.namedfork">
+ Order allow,deny
+ Deny from all
+ Satisfy All
+</DirectoryMatch>
+
+#
+# ErrorLog: The location of the error log file.
+# If you do not specify an ErrorLog directive within a <VirtualHost>
+# container, error messages relating to that virtual host will be
+# logged here. If you *do* define an error logfile for a <VirtualHost>
+# container, that host's errors will be logged there and not here.
+#
+ErrorLog "logs/error_log"
+
+#
+# LogLevel: Control the number of messages logged to the error_log.
+# Possible values include: debug, info, notice, warn, error, crit,
+# alert, emerg.
+#
+LogLevel warn
+
+<IfModule log_config_module>
+ #
+ # The following directives define some format nicknames for use with
+ # a CustomLog directive (see below).
+ #
+ LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
+ LogFormat "%h %l %u %t \"%r\" %>s %b" common
+
+ <IfModule logio_module>
+ # You need to enable mod_logio.c to use %I and %O
+ LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
+ </IfModule>
+
+ #
+ # The location and format of the access logfile (Common Logfile Format).
+ # If you do not define any access logfiles within a <VirtualHost>
+ # container, they will be logged here. Contrariwise, if you *do*
+ # define per-<VirtualHost> access logfiles, transactions will be
+ # logged therein and *not* in this file.
+ #
+ CustomLog "logs/access_log" common
+
+ #
+ # If you prefer a logfile with access, agent, and referer information
+ # (Combined Logfile Format) you can use the following directive.
+ #
+ #CustomLog "logs/access_log" combined
+</IfModule>
+
+<IfModule alias_module>
+ #
+ # Redirect: Allows you to tell clients about documents that used to
+ # exist in your server's namespace, but do not anymore. The client
+ # will make a new request for the document at its new location.
+ # Example:
+ # Redirect permanent /foo http://www.example.com/bar
+
+ #
+ # Alias: Maps web paths into filesystem paths and is used to
+ # access content that does not live under the DocumentRoot.
+ # Example:
+ # Alias /webpath /full/filesystem/path
+ #
+ # If you include a trailing / on /webpath then the server will
+ # require it to be present in the URL. You will also likely
+ # need to provide a <Directory> section to allow access to
+ # the filesystem path.
+
+ #
+ # ScriptAlias: This controls which directories contain server scripts.
+ # ScriptAliases are essentially the same as Aliases, except that
+ # documents in the target directory are treated as applications and
+ # run by the server when requested rather than as documents sent to the
+ # client. The same rules about trailing "/" apply to ScriptAlias
+ # directives as to Alias.
+ #
+ ScriptAlias /cgi-bin/ "/opt/local/apache2/cgi-bin/"
+
+</IfModule>
+
+<IfModule cgid_module>
+ #
+ # ScriptSock: On threaded servers, designate the path to the UNIX
+ # socket used to communicate with the CGI daemon of mod_cgid.
+ #
+ #Scriptsock logs/cgisock
+</IfModule>
+
+#
+# "/opt/local/apache2/cgi-bin" should be changed to whatever your ScriptAliased
+# CGI directory exists, if you have that configured.
+#
+<Directory "/opt/local/apache2/cgi-bin">
+ AllowOverride None
+ Options None
+ Order allow,deny
+ Allow from all
+</Directory>
+
+#
+# DefaultType: the default MIME type the server will use for a document
+# if it cannot otherwise determine one, such as from filename extensions.
+# If your server contains mostly text or HTML documents, "text/plain" is
+# a good value. If most of your content is binary, such as applications
+# or images, you may want to use "application/octet-stream" instead to
+# keep browsers from trying to display binary files as though they are
+# text.
+#
+DefaultType text/plain
+
+<IfModule mime_module>
+ #
+ # TypesConfig points to the file containing the list of mappings from
+ # filename extension to MIME-type.
+ #
+ TypesConfig conf/mime.types
+
+ #
+ # AddType allows you to add to or override the MIME configuration
+ # file specified in TypesConfig for specific file types.
+ #
+ #AddType application/x-gzip .tgz
+ #
+ # AddEncoding allows you to have certain browsers uncompress
+ # information on the fly. Note: Not all browsers support this.
+ #
+ #AddEncoding x-compress .Z
+ #AddEncoding x-gzip .gz .tgz
+ #
+ # If the AddEncoding directives above are commented-out, then you
+ # probably should define those extensions to indicate media types:
+ #
+ AddType application/x-compress .Z
+ AddType application/x-gzip .gz .tgz
+
+ #
+ # AddHandler allows you to map certain file extensions to "handlers":
+ # actions unrelated to filetype. These can be either built into the server
+ # or added with the Action directive (see below)
+ #
+ # To use CGI scripts outside of ScriptAliased directories:
+ # (You will also need to add "ExecCGI" to the "Options" directive.)
+ #
+ #AddHandler cgi-script .cgi
+
+ # For type maps (negotiated resources):
+ #AddHandler type-map var
+
+ #
+ # Filters allow you to process content before it is sent to the client.
+ #
+ # To parse .shtml files for server-side includes (SSI):
+ # (You will also need to add "Includes" to the "Options" directive.)
+ #
+ #AddType text/html .shtml
+ #AddOutputFilter INCLUDES .shtml
+</IfModule>
+
+#
+# The mod_mime_magic module allows the server to use various hints from the
+# contents of the file itself to determine its type. The MIMEMagicFile
+# directive tells the module where the hint definitions are located.
+#
+#MIMEMagicFile conf/magic
+
+#
+# Customizable error responses come in three flavors:
+# 1) plain text 2) local redirects 3) external redirects
+#
+# Some examples:
+#ErrorDocument 500 "The server made a boo boo."
+#ErrorDocument 404 /missing.html
+#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
+#ErrorDocument 402 http://www.example.com/subscription_info.html
+#
+
+#
+# EnableMMAP and EnableSendfile: On systems that support it,
+# memory-mapping or the sendfile syscall is used to deliver
+# files. This usually improves server performance, but must
+# be turned off when serving from networked-mounted
+# filesystems or if support for these functions is otherwise
+# broken on your system.
+#
+#EnableMMAP off
+#EnableSendfile off
+
+# Supplemental configuration
+#
+# The configuration files in the conf/extra/ directory can be
+# included to add extra features or to modify the default configuration of
+# the server, or you may simply copy their contents here and change as
+# necessary.
+
+# Server-pool management (MPM specific)
+#Include conf/extra/httpd-mpm.conf
+
+# Multi-language error messages
+#Include conf/extra/httpd-multilang-errordoc.conf
+
+# Fancy directory listings
+#Include conf/extra/httpd-autoindex.conf
+
+# Language settings
+#Include conf/extra/httpd-languages.conf
+
+# User home directories
+#Include conf/extra/httpd-userdir.conf
+
+# Real-time info on requests and configuration
+#Include conf/extra/httpd-info.conf
+
+# Virtual hosts
+#Include conf/extra/httpd-vhosts.conf
+
+# Local access to the Apache HTTP Server Manual
+#Include conf/extra/httpd-manual.conf
+
+# Distributed authoring and versioning (WebDAV)
+#Include conf/extra/httpd-dav.conf
+
+# Various default settings
+#Include conf/extra/httpd-default.conf
+
+# Secure (SSL/TLS) connections
+#Include conf/extra/httpd-ssl.conf
+#
+# Note: The following must must be present to support
+# starting without SSL on platforms with no /dev/random equivalent
+# but a statically compiled-in mod_ssl.
+#
+<IfModule ssl_module>
+SSLRandomSeed startup builtin
+SSLRandomSeed connect builtin
+</IfModule>
|
radar/fans
|
04fce02b3f63892a93de0b235955e8633b22b0ae
|
Destroy memberships if a user or a group is destroyed.
|
diff --git a/app/models/group.rb b/app/models/group.rb
index 077fd2e..d49eda3 100644
--- a/app/models/group.rb
+++ b/app/models/group.rb
@@ -1,4 +1,4 @@
class Group < ActiveRecord::Base
- has_many :memberships
+ has_many :memberships, :depedent => :destroy
has_many :members, :through => :memberships, :source => "user"
end
\ No newline at end of file
diff --git a/app/models/user.rb b/app/models/user.rb
index c05aee6..8175416 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,10 +1,10 @@
class User < ActiveRecord::Base
# Fans and Favourites
has_and_belongs_to_many :favs, :class_name => "User", :join_table => "fans", :association_foreign_key => "fav_id", :foreign_key => "fan_id"
has_and_belongs_to_many :fans, :class_name => "User", :join_table => "fans", :association_foreign_key => "fan_id", :foreign_key => "fav_id"
# Groups & Memberships
- has_many :memberships
+ has_many :memberships, :dependent => :destroy
has_many :groups, :through => :memberships
end
|
radar/fans
|
c7c6e3883f90f04e7a387fbf574da4bce70f613c
|
Added .gitignore, removed development.log
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..6115c10
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+log/*
diff --git a/log/development.log b/log/development.log
deleted file mode 100644
index 99cf249..0000000
--- a/log/development.log
+++ /dev/null
@@ -1,178 +0,0 @@
- [4;36;1mSQL (0.000329)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000194)[0m [0mselect sqlite_version(*)[0m
- [4;36;1mSQL (0.002629)[0m [0;1mCREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL) [0m
- [4;35;1mSQL (0.002899)[0m [0mCREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version")[0m
- [4;36;1mSQL (0.000598)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000422)[0m [0mSELECT version FROM schema_migrations[0m
-Migrating to CreateUsers (20081017005157)
- [4;36;1mSQL (0.002445)[0m [0;1mCREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255)) [0m
- [4;35;1mSQL (0.001825)[0m [0mINSERT INTO schema_migrations (version) VALUES ('20081017005157')[0m
-Migrating to CreateFans (20081017005159)
- [4;36;1mSQL (0.002948)[0m [0;1mCREATE TABLE "fans_users" ("fan_id" integer, "fav_id" integer) [0m
- [4;35;1mSQL (0.002335)[0m [0mINSERT INTO schema_migrations (version) VALUES ('20081017005159')[0m
- [4;36;1mSQL (0.000382)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000234)[0m [0mSELECT version FROM schema_migrations[0m
- [4;36;1mSQL (0.000300)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000052)[0m [0mPRAGMA index_list("fans_users")[0m
- [4;36;1mSQL (0.000050)[0m [0;1mPRAGMA index_list("users")[0m
- [4;36;1mUser Create (0.000624)[0m [0;1mINSERT INTO "users" ("name") VALUES('Ryan')[0m
- [4;35;1mUser Create (0.000497)[0m [0mINSERT INTO "users" ("name") VALUES('Charlie')[0m
- [4;36;1mUser Load (0.000398)[0m [0;1mSELECT * FROM "users" LIMIT 1[0m
- [4;35;1mUser Load (0.000348)[0m [0mSELECT * FROM "users" LIMIT 1[0m
- [4;36;1mUser Load (0.000392)[0m [0;1mSELECT * FROM "users" LIMIT 1[0m
- [4;35;1mUser Load (0.000228)[0m [0mSELECT * FROM "users" WHERE ("users"."id" = 2) [0m
- [4;36;1mSQL (0.000511)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000222)[0m [0mSELECT version FROM schema_migrations[0m
- [4;36;1mSQL (0.000199)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000187)[0m [0mSELECT version FROM schema_migrations[0m
-Migrating to CreateFans (20081017005159)
- [4;36;1mSQL (0.000000)[0m [0;1mSQLite3::SQLException: no such table: fans: DROP TABLE "fans"[0m
- [4;36;1mSQL (0.000576)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000201)[0m [0mSELECT version FROM schema_migrations[0m
- [4;36;1mSQL (0.000197)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000226)[0m [0mSELECT version FROM schema_migrations[0m
-Migrating to CreateFans (20081017005159)
- [4;36;1mSQL (0.000000)[0m [0;1mSQLite3::SQLException: no such table: fans_user: DROP TABLE "fans_user"[0m
- [4;36;1mSQL (0.000467)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000191)[0m [0mSELECT version FROM schema_migrations[0m
- [4;36;1mSQL (0.000205)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000179)[0m [0mSELECT version FROM schema_migrations[0m
-Migrating to CreateFans (20081017005159)
- [4;36;1mSQL (0.002739)[0m [0;1mDROP TABLE "fans_users"[0m
- [4;35;1mSQL (0.002655)[0m [0mDELETE FROM schema_migrations WHERE version = '20081017005159'[0m
- [4;36;1mSQL (0.000218)[0m [0;1mselect sqlite_version(*)[0m
- [4;35;1mSQL (0.000399)[0m [0m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;36;1mSQL (0.000235)[0m [0;1mSELECT version FROM schema_migrations[0m
- [4;35;1mSQL (0.000281)[0m [0m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;36;1mSQL (0.000066)[0m [0;1mPRAGMA index_list("users")[0m
- [4;36;1mSQL (0.000457)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000160)[0m [0mSELECT version FROM schema_migrations[0m
- [4;36;1mSQL (0.000166)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000230)[0m [0mSELECT version FROM schema_migrations[0m
-Migrating to CreateUsers (20081017005157)
- [4;36;1mSQL (0.003029)[0m [0;1mDROP TABLE "users"[0m
- [4;35;1mSQL (0.002516)[0m [0mDELETE FROM schema_migrations WHERE version = '20081017005157'[0m
- [4;36;1mSQL (0.000209)[0m [0;1mselect sqlite_version(*)[0m
- [4;35;1mSQL (0.000281)[0m [0m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;36;1mSQL (0.000135)[0m [0;1mSELECT version FROM schema_migrations[0m
- [4;35;1mSQL (0.000238)[0m [0m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;36;1mSQL (0.000387)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000113)[0m [0mSELECT version FROM schema_migrations[0m
-Migrating to CreateUsers (20081017005157)
- [4;36;1mSQL (0.000109)[0m [0;1mselect sqlite_version(*)[0m
- [4;35;1mSQL (0.003435)[0m [0mCREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255)) [0m
- [4;36;1mSQL (0.002261)[0m [0;1mINSERT INTO schema_migrations (version) VALUES ('20081017005157')[0m
-Migrating to CreateFans (20081017005159)
- [4;35;1mSQL (0.001940)[0m [0mCREATE TABLE "fans" ("fan_id" integer, "fav_id" integer) [0m
- [4;36;1mSQL (0.003148)[0m [0;1mINSERT INTO schema_migrations (version) VALUES ('20081017005159')[0m
- [4;35;1mSQL (0.000433)[0m [0m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;36;1mSQL (0.000272)[0m [0;1mSELECT version FROM schema_migrations[0m
- [4;35;1mSQL (0.000288)[0m [0m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;36;1mSQL (0.000063)[0m [0;1mPRAGMA index_list("fans")[0m
- [4;35;1mSQL (0.000038)[0m [0mPRAGMA index_list("users")[0m
- [4;36;1mUser Create (0.000387)[0m [0;1mINSERT INTO "users" ("name") VALUES('Ryan')[0m
- [4;35;1mUser Create (0.000468)[0m [0mINSERT INTO "users" ("name") VALUES('Charlie')[0m
- [4;36;1mUser Create (0.000437)[0m [0;1mINSERT INTO "users" ("name") VALUES('Ryan')[0m
- [4;35;1mUser Create (0.000449)[0m [0mINSERT INTO "users" ("name") VALUES('Ryan')[0m
- [4;36;1mUser Load (0.000392)[0m [0;1mSELECT * FROM "users" WHERE ("users"."id" = 2) [0m
- [4;35;1mSQL (0.000353)[0m [0mINSERT INTO "fans" ("fan_id", "fav_id") VALUES (2, 4)[0m
- [4;36;1mUser Load (0.000360)[0m [0;1mSELECT * FROM "users" INNER JOIN "fans" ON "users".id = "fans".fan_id WHERE ("fans".fav_id = 4 ) [0m
- [4;35;1mUser Load (0.000361)[0m [0mSELECT * FROM "users" WHERE ("users"."id" = 4) [0m
- [4;36;1mUser Load (0.000354)[0m [0;1mSELECT * FROM "users" WHERE ("users"."id" = 4) [0m
- [4;35;1mUser Load (0.000321)[0m [0mSELECT * FROM "users" INNER JOIN "fans" ON "users".id = "fans".fan_id WHERE ("fans".fav_id = 4 ) [0m
- [4;36;1mUser Load (0.000471)[0m [0;1mSELECT * FROM "users" WHERE ("users"."id" = 2) [0m
- [4;35;1mUser Load (0.000361)[0m [0mSELECT * FROM "users" WHERE ("users"."id" = 2) [0m
- [4;36;1mUser Load (0.000349)[0m [0;1mSELECT * FROM "users" INNER JOIN "fans" ON "users".id = "fans".fav_id WHERE ("fans".fan_id = 2 ) [0m
- [4;36;1mGroup Load (0.000000)[0m [0;1mSQLite3::SQLException: no such table: groups: SELECT * FROM "groups" LIMIT 1[0m
- [4;36;1mSQL (0.000484)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000371)[0m [0mSELECT version FROM schema_migrations[0m
-Migrating to CreateUsers (20081017005157)
-Migrating to CreateFans (20081017005159)
-Migrating to AddGroups (20081020110639)
- [4;36;1mSQL (0.000154)[0m [0;1mselect sqlite_version(*)[0m
- [4;35;1mSQL (0.003213)[0m [0mCREATE TABLE "groups" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255)) [0m
- [4;36;1mSQL (0.002427)[0m [0;1mCREATE TABLE "memberships" ("user_id" integer, "group_id" integer) [0m
- [4;35;1mSQL (0.002882)[0m [0mINSERT INTO schema_migrations (version) VALUES ('20081020110639')[0m
- [4;36;1mSQL (0.000354)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000184)[0m [0mSELECT version FROM schema_migrations[0m
- [4;36;1mSQL (0.000273)[0m [0;1m SELECT name
- FROM sqlite_master
- WHERE type = 'table' AND NOT name = 'sqlite_sequence'
-[0m
- [4;35;1mSQL (0.000047)[0m [0mPRAGMA index_list("fans")[0m
- [4;36;1mSQL (0.000050)[0m [0;1mPRAGMA index_list("groups")[0m
- [4;35;1mSQL (0.000039)[0m [0mPRAGMA index_list("memberships")[0m
- [4;36;1mSQL (0.000039)[0m [0;1mPRAGMA index_list("users")[0m
- [4;36;1mGroup Create (0.000583)[0m [0;1mINSERT INTO "groups" ("name") VALUES('Group')[0m
- [4;35;1mGroup Load (0.000432)[0m [0mSELECT * FROM "groups" LIMIT 1[0m
- [4;36;1mGroup Load (0.000434)[0m [0;1mSELECT * FROM "groups" LIMIT 1[0m
- [4;35;1mGroup Load (0.000295)[0m [0mSELECT * FROM "groups" LIMIT 1[0m
- [4;36;1mUser Load (0.000330)[0m [0;1mSELECT * FROM "users" LIMIT 1[0m
- [4;35;1mMembership Create (0.000569)[0m [0mINSERT INTO "memberships" ("group_id", "user_id") VALUES(1, 1)[0m
- [4;36;1mUser Load (0.000469)[0m [0;1mSELECT "users".* FROM "users" INNER JOIN memberships ON users.id = memberships.user_id WHERE (("memberships".group_id = 1)) [0m
- [4;35;1mUser Load (0.000379)[0m [0mSELECT * FROM "users" LIMIT 1[0m
- [4;36;1mUser Load (0.000355)[0m [0;1mSELECT * FROM "users" LIMIT 1[0m
- [4;35;1mGroup Load (0.000295)[0m [0mSELECT "groups".* FROM "groups" INNER JOIN memberships ON groups.id = memberships.group_id WHERE (("memberships".user_id = 1)) [0m
|
radar/fans
|
b56511323ef442fd721173493539a9fa486370c4
|
Added groups and memberships to the foray.
|
diff --git a/app/models/group.rb b/app/models/group.rb
new file mode 100644
index 0000000..077fd2e
--- /dev/null
+++ b/app/models/group.rb
@@ -0,0 +1,4 @@
+class Group < ActiveRecord::Base
+ has_many :memberships
+ has_many :members, :through => :memberships, :source => "user"
+end
\ No newline at end of file
diff --git a/app/models/membership.rb b/app/models/membership.rb
new file mode 100644
index 0000000..d87df89
--- /dev/null
+++ b/app/models/membership.rb
@@ -0,0 +1,4 @@
+class Membership < ActiveRecord::Base
+ belongs_to :user
+ belongs_to :group
+end
\ No newline at end of file
diff --git a/app/models/user.rb b/app/models/user.rb
index 839d52a..c05aee6 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,4 +1,10 @@
class User < ActiveRecord::Base
+
+ # Fans and Favourites
has_and_belongs_to_many :favs, :class_name => "User", :join_table => "fans", :association_foreign_key => "fav_id", :foreign_key => "fan_id"
has_and_belongs_to_many :fans, :class_name => "User", :join_table => "fans", :association_foreign_key => "fan_id", :foreign_key => "fav_id"
+
+ # Groups & Memberships
+ has_many :memberships
+ has_many :groups, :through => :memberships
end
diff --git a/db/development.sqlite3 b/db/development.sqlite3
index 37c7578..e92c657 100644
Binary files a/db/development.sqlite3 and b/db/development.sqlite3 differ
diff --git a/db/migrate/20081020110639_add_groups.rb b/db/migrate/20081020110639_add_groups.rb
new file mode 100644
index 0000000..54435fd
--- /dev/null
+++ b/db/migrate/20081020110639_add_groups.rb
@@ -0,0 +1,16 @@
+class AddGroups < ActiveRecord::Migration
+ def self.up
+ create_table :groups do |t|
+ t.string :name
+ end
+
+ create_table :memberships, :id => false do |t|
+ t.references :user, :group
+ end
+ end
+
+ def self.down
+ drop_table :groups
+ drop_table :memberships
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index c962a62..d9ecdfa 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,23 +1,32 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20081017005159) do
+ActiveRecord::Schema.define(:version => 20081020110639) do
create_table "fans", :id => false, :force => true do |t|
t.integer "fan_id"
t.integer "fav_id"
end
+ create_table "groups", :force => true do |t|
+ t.string "name"
+ end
+
+ create_table "memberships", :id => false, :force => true do |t|
+ t.integer "user_id"
+ t.integer "group_id"
+ end
+
create_table "users", :force => true do |t|
t.string "name"
end
end
diff --git a/log/development.log b/log/development.log
index 48ef1f8..99cf249 100644
--- a/log/development.log
+++ b/log/development.log
@@ -1,142 +1,178 @@
[4;36;1mSQL (0.000329)[0m [0;1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;35;1mSQL (0.000194)[0m [0mselect sqlite_version(*)[0m
[4;36;1mSQL (0.002629)[0m [0;1mCREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL) [0m
[4;35;1mSQL (0.002899)[0m [0mCREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version")[0m
[4;36;1mSQL (0.000598)[0m [0;1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;35;1mSQL (0.000422)[0m [0mSELECT version FROM schema_migrations[0m
Migrating to CreateUsers (20081017005157)
[4;36;1mSQL (0.002445)[0m [0;1mCREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255)) [0m
[4;35;1mSQL (0.001825)[0m [0mINSERT INTO schema_migrations (version) VALUES ('20081017005157')[0m
Migrating to CreateFans (20081017005159)
[4;36;1mSQL (0.002948)[0m [0;1mCREATE TABLE "fans_users" ("fan_id" integer, "fav_id" integer) [0m
[4;35;1mSQL (0.002335)[0m [0mINSERT INTO schema_migrations (version) VALUES ('20081017005159')[0m
[4;36;1mSQL (0.000382)[0m [0;1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;35;1mSQL (0.000234)[0m [0mSELECT version FROM schema_migrations[0m
[4;36;1mSQL (0.000300)[0m [0;1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;35;1mSQL (0.000052)[0m [0mPRAGMA index_list("fans_users")[0m
[4;36;1mSQL (0.000050)[0m [0;1mPRAGMA index_list("users")[0m
[4;36;1mUser Create (0.000624)[0m [0;1mINSERT INTO "users" ("name") VALUES('Ryan')[0m
[4;35;1mUser Create (0.000497)[0m [0mINSERT INTO "users" ("name") VALUES('Charlie')[0m
[4;36;1mUser Load (0.000398)[0m [0;1mSELECT * FROM "users" LIMIT 1[0m
[4;35;1mUser Load (0.000348)[0m [0mSELECT * FROM "users" LIMIT 1[0m
[4;36;1mUser Load (0.000392)[0m [0;1mSELECT * FROM "users" LIMIT 1[0m
[4;35;1mUser Load (0.000228)[0m [0mSELECT * FROM "users" WHERE ("users"."id" = 2) [0m
[4;36;1mSQL (0.000511)[0m [0;1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;35;1mSQL (0.000222)[0m [0mSELECT version FROM schema_migrations[0m
[4;36;1mSQL (0.000199)[0m [0;1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;35;1mSQL (0.000187)[0m [0mSELECT version FROM schema_migrations[0m
Migrating to CreateFans (20081017005159)
[4;36;1mSQL (0.000000)[0m [0;1mSQLite3::SQLException: no such table: fans: DROP TABLE "fans"[0m
[4;36;1mSQL (0.000576)[0m [0;1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;35;1mSQL (0.000201)[0m [0mSELECT version FROM schema_migrations[0m
[4;36;1mSQL (0.000197)[0m [0;1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;35;1mSQL (0.000226)[0m [0mSELECT version FROM schema_migrations[0m
Migrating to CreateFans (20081017005159)
[4;36;1mSQL (0.000000)[0m [0;1mSQLite3::SQLException: no such table: fans_user: DROP TABLE "fans_user"[0m
[4;36;1mSQL (0.000467)[0m [0;1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;35;1mSQL (0.000191)[0m [0mSELECT version FROM schema_migrations[0m
[4;36;1mSQL (0.000205)[0m [0;1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;35;1mSQL (0.000179)[0m [0mSELECT version FROM schema_migrations[0m
Migrating to CreateFans (20081017005159)
[4;36;1mSQL (0.002739)[0m [0;1mDROP TABLE "fans_users"[0m
[4;35;1mSQL (0.002655)[0m [0mDELETE FROM schema_migrations WHERE version = '20081017005159'[0m
[4;36;1mSQL (0.000218)[0m [0;1mselect sqlite_version(*)[0m
[4;35;1mSQL (0.000399)[0m [0m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;36;1mSQL (0.000235)[0m [0;1mSELECT version FROM schema_migrations[0m
[4;35;1mSQL (0.000281)[0m [0m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;36;1mSQL (0.000066)[0m [0;1mPRAGMA index_list("users")[0m
[4;36;1mSQL (0.000457)[0m [0;1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;35;1mSQL (0.000160)[0m [0mSELECT version FROM schema_migrations[0m
[4;36;1mSQL (0.000166)[0m [0;1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;35;1mSQL (0.000230)[0m [0mSELECT version FROM schema_migrations[0m
Migrating to CreateUsers (20081017005157)
[4;36;1mSQL (0.003029)[0m [0;1mDROP TABLE "users"[0m
[4;35;1mSQL (0.002516)[0m [0mDELETE FROM schema_migrations WHERE version = '20081017005157'[0m
[4;36;1mSQL (0.000209)[0m [0;1mselect sqlite_version(*)[0m
[4;35;1mSQL (0.000281)[0m [0m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;36;1mSQL (0.000135)[0m [0;1mSELECT version FROM schema_migrations[0m
[4;35;1mSQL (0.000238)[0m [0m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;36;1mSQL (0.000387)[0m [0;1m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;35;1mSQL (0.000113)[0m [0mSELECT version FROM schema_migrations[0m
Migrating to CreateUsers (20081017005157)
[4;36;1mSQL (0.000109)[0m [0;1mselect sqlite_version(*)[0m
[4;35;1mSQL (0.003435)[0m [0mCREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255)) [0m
[4;36;1mSQL (0.002261)[0m [0;1mINSERT INTO schema_migrations (version) VALUES ('20081017005157')[0m
Migrating to CreateFans (20081017005159)
[4;35;1mSQL (0.001940)[0m [0mCREATE TABLE "fans" ("fan_id" integer, "fav_id" integer) [0m
[4;36;1mSQL (0.003148)[0m [0;1mINSERT INTO schema_migrations (version) VALUES ('20081017005159')[0m
[4;35;1mSQL (0.000433)[0m [0m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;36;1mSQL (0.000272)[0m [0;1mSELECT version FROM schema_migrations[0m
[4;35;1mSQL (0.000288)[0m [0m SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
[0m
[4;36;1mSQL (0.000063)[0m [0;1mPRAGMA index_list("fans")[0m
[4;35;1mSQL (0.000038)[0m [0mPRAGMA index_list("users")[0m
[4;36;1mUser Create (0.000387)[0m [0;1mINSERT INTO "users" ("name") VALUES('Ryan')[0m
[4;35;1mUser Create (0.000468)[0m [0mINSERT INTO "users" ("name") VALUES('Charlie')[0m
[4;36;1mUser Create (0.000437)[0m [0;1mINSERT INTO "users" ("name") VALUES('Ryan')[0m
[4;35;1mUser Create (0.000449)[0m [0mINSERT INTO "users" ("name") VALUES('Ryan')[0m
[4;36;1mUser Load (0.000392)[0m [0;1mSELECT * FROM "users" WHERE ("users"."id" = 2) [0m
[4;35;1mSQL (0.000353)[0m [0mINSERT INTO "fans" ("fan_id", "fav_id") VALUES (2, 4)[0m
[4;36;1mUser Load (0.000360)[0m [0;1mSELECT * FROM "users" INNER JOIN "fans" ON "users".id = "fans".fan_id WHERE ("fans".fav_id = 4 ) [0m
[4;35;1mUser Load (0.000361)[0m [0mSELECT * FROM "users" WHERE ("users"."id" = 4) [0m
[4;36;1mUser Load (0.000354)[0m [0;1mSELECT * FROM "users" WHERE ("users"."id" = 4) [0m
[4;35;1mUser Load (0.000321)[0m [0mSELECT * FROM "users" INNER JOIN "fans" ON "users".id = "fans".fan_id WHERE ("fans".fav_id = 4 ) [0m
[4;36;1mUser Load (0.000471)[0m [0;1mSELECT * FROM "users" WHERE ("users"."id" = 2) [0m
[4;35;1mUser Load (0.000361)[0m [0mSELECT * FROM "users" WHERE ("users"."id" = 2) [0m
[4;36;1mUser Load (0.000349)[0m [0;1mSELECT * FROM "users" INNER JOIN "fans" ON "users".id = "fans".fav_id WHERE ("fans".fan_id = 2 ) [0m
+ [4;36;1mGroup Load (0.000000)[0m [0;1mSQLite3::SQLException: no such table: groups: SELECT * FROM "groups" LIMIT 1[0m
+ [4;36;1mSQL (0.000484)[0m [0;1m SELECT name
+ FROM sqlite_master
+ WHERE type = 'table' AND NOT name = 'sqlite_sequence'
+[0m
+ [4;35;1mSQL (0.000371)[0m [0mSELECT version FROM schema_migrations[0m
+Migrating to CreateUsers (20081017005157)
+Migrating to CreateFans (20081017005159)
+Migrating to AddGroups (20081020110639)
+ [4;36;1mSQL (0.000154)[0m [0;1mselect sqlite_version(*)[0m
+ [4;35;1mSQL (0.003213)[0m [0mCREATE TABLE "groups" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255)) [0m
+ [4;36;1mSQL (0.002427)[0m [0;1mCREATE TABLE "memberships" ("user_id" integer, "group_id" integer) [0m
+ [4;35;1mSQL (0.002882)[0m [0mINSERT INTO schema_migrations (version) VALUES ('20081020110639')[0m
+ [4;36;1mSQL (0.000354)[0m [0;1m SELECT name
+ FROM sqlite_master
+ WHERE type = 'table' AND NOT name = 'sqlite_sequence'
+[0m
+ [4;35;1mSQL (0.000184)[0m [0mSELECT version FROM schema_migrations[0m
+ [4;36;1mSQL (0.000273)[0m [0;1m SELECT name
+ FROM sqlite_master
+ WHERE type = 'table' AND NOT name = 'sqlite_sequence'
+[0m
+ [4;35;1mSQL (0.000047)[0m [0mPRAGMA index_list("fans")[0m
+ [4;36;1mSQL (0.000050)[0m [0;1mPRAGMA index_list("groups")[0m
+ [4;35;1mSQL (0.000039)[0m [0mPRAGMA index_list("memberships")[0m
+ [4;36;1mSQL (0.000039)[0m [0;1mPRAGMA index_list("users")[0m
+ [4;36;1mGroup Create (0.000583)[0m [0;1mINSERT INTO "groups" ("name") VALUES('Group')[0m
+ [4;35;1mGroup Load (0.000432)[0m [0mSELECT * FROM "groups" LIMIT 1[0m
+ [4;36;1mGroup Load (0.000434)[0m [0;1mSELECT * FROM "groups" LIMIT 1[0m
+ [4;35;1mGroup Load (0.000295)[0m [0mSELECT * FROM "groups" LIMIT 1[0m
+ [4;36;1mUser Load (0.000330)[0m [0;1mSELECT * FROM "users" LIMIT 1[0m
+ [4;35;1mMembership Create (0.000569)[0m [0mINSERT INTO "memberships" ("group_id", "user_id") VALUES(1, 1)[0m
+ [4;36;1mUser Load (0.000469)[0m [0;1mSELECT "users".* FROM "users" INNER JOIN memberships ON users.id = memberships.user_id WHERE (("memberships".group_id = 1)) [0m
+ [4;35;1mUser Load (0.000379)[0m [0mSELECT * FROM "users" LIMIT 1[0m
+ [4;36;1mUser Load (0.000355)[0m [0;1mSELECT * FROM "users" LIMIT 1[0m
+ [4;35;1mGroup Load (0.000295)[0m [0mSELECT "groups".* FROM "groups" INNER JOIN memberships ON groups.id = memberships.group_id WHERE (("memberships".user_id = 1)) [0m
|
sergeche/rocon
|
b61466e8eb88c032db1a0913897db107ba2cf7bf
|
Better drawing of thick borders
|
diff --git a/js_src/vml.js b/js_src/vml.js
index a265f2d..4f0f518 100644
--- a/js_src/vml.js
+++ b/js_src/vml.js
@@ -1,202 +1,202 @@
/**
* VML adapter for drawing rounded corners
* @author Sergey Chikuyonok (serge.che@gmail.com)
* @link http://chikuyonok.ru
*
* @include "common.js"
*/
var vml = (function(){
// init VML (took from RaphaÑl lib)
var ns = 'rc_vml',
doc = document,
vml_ns = '',
common_style = 'position:absolute;display:inline-block;',
is_inited = false;
/** Stroke drawing raw string */
var stroke_path = '<' + ns + ':shape ' + vml_ns + ' class="' + ns + ' ' + ns + '_stroke" fillcolor="%top_color%" style="' + common_style + 'width:%width%px;height:%height%px;%offset%;%rotation%" stroked="false" coordsize="%c_width% %c_height%" coordorigin="5 5" ' +
'path="m0,%c_height% l0,%radius% qy%radius%,0 l%c_width%,0 r0,%top% l%radius%,%top% qx%left%,%radius% l%left%,%c_height% l0,%c_height% e x">' +
'<' + ns + ':fill ' + vml_ns + ' class="' + ns + '" color="%left_color%" color2="%top_color%" type="gradient" colors="%grd_start%% %grd_color_start%, %grd_end%% %grd_color_end%"/>' +
'</' + ns + ':shape>',
/** Fill drawing raw string */
fill_path = '<' + ns + ':shape ' + vml_ns + ' class="' + ns + '" fillcolor="%color%" stroked="false" style="' + common_style + 'width:%width%px;height:%height%px;%rotation%;%offset%" coordsize="%c_width% %c_height%" coordorigin="5 5" ' +
'path="m%offset_x%,%c_height% l%offset_x%,%radius% qy%radius%,%offset_y% l%c_width%,%offset_y% l%c_width%,0 %shape% l0,%c_height% e x"></' + ns + ':shape>',
/** All numeric properies of <code>params</code> object */
num_properties = ['top', 'left', 'radius', 'c_width', 'c_height'],
/** VML coordinate space multiplier for crispy edges of shapes */
multiplier = 10;
/**
* Replaces entities (like %entity%) in string with values passed in
* <code>params</code>: {entity1: value, entity2: value, ...}
* @param {String} str Raw string
* @param {Object} params Entity values
* @return {String} New string with replaced entities
*/
function replaceEntities(str, params) {
// merge objects
var _params = {};
for (var i = 1; i < arguments.length; i++) {
var obj = arguments[i];
if (obj)
for (var a in obj) if (obj.hasOwnProperty(a))
_params[a] = obj[a];
}
// replace entities
return str.replace(/\%(\w+)\%/g, function(s, p1){
return _params[p1];
});
}
/**
* Create border shape (stroke).
*
* @param {Number} params.radius Corner radius
* @param {Number} params.left Left border width, pixels
* @param {String} params.left_color Left border color
* @param {Number} params.top Top border width, pixels
* @param {String} params.top_color Top border color
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
*
* @return {String} String containing SVG tags
*/
function drawStroke(params) {
var extra_params = {
grd_start: (1 - params.top / params.radius) * 100,
grd_color_start: params.top_color,
grd_end: (1 - params.radius / params.height) * 100,
grd_color_end: params.left_color
};
if ((params.type || '').charAt(0) == 'b') {
// swap colors
var tmp_color = params.top_color;
params.top_color = params.left_color;
params.left_color = tmp_color;
extra_params.grd_start = 100 - extra_params.grd_start;
extra_params.grd_end = 100 - extra_params.grd_end;
}
return (params.top + params.left) ?
// replaceEntities(stroke_gradient, params, extra_params) +
replaceEntities(stroke_path, params, extra_params)
: '';
}
/**
* Draw background for corner image
*
* @param {Number} params.radius Corner radius
* @param {Number} params.left Left border width, pixels
* @param {Number} params.top Top border width, pixels
* @param {String} params.color Color of background
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
*/
function drawBackground(params) {
var t = {
shape: params.use_shape ? 'r0,' + params.c_height : 'l0,0'
};
return replaceEntities(fill_path, params, t);
}
/**
* Returns transformation params for different types of corners
* @param {String} Corner type: tl, tr, bl, br
* @param {Number} radius Corner radius
*/
function rotate(type, radius) {
switch (type) {
case 'tr': // top right corner
return 'flip:x;margin-left:-1px;';
case 'bl': // bottom left corner
return 'flip:y;margin-top:-1px';
case 'br': // bottom right corner
return 'rotation:180;margin-left:-1px;margin-top:-1px;';
default:
return '';
}
}
return {
init: function() {
if (!is_inited) {
doc.createStyleSheet().addRule("." + ns, "behavior:url(#default#VML)");
try {
!doc.namespaces[ns] && doc.namespaces.add(ns, "urn:schemas-microsoft-com:vml");
} catch (e) {
vml_ns = 'xmlns="urn:schemas-microsoft.com:vml"';
}
}
is_inited = true;
},
/**
* Draw rounded corner
*
* @param {Number} params.radius Corner radius
* @param {Number} params.left Left border width, pixels
* @param {String} params.left_color Left border color
* @param {Number} params.top Top border width, pixels
* @param {String} params.top_color Top border color
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
* @param {String} params.color Color of background
* @param {String} params.type Corner type: tl, tr, bl, br
*
* @return {String} Image in data:URL format
*/
draw: function(params) {
params = copyObj(params);
params.width = params.c_width = params.width || params.radius;
params.height = params.c_height = params.height || params.radius;
params.offset = '';
if (params.type.charAt(0) == 'b')
params.offset += 'top: 0px;';
if (params.type.charAt(1) == 'r')
params.offset += 'left: 0px;';
else if (params.use_shape) {
- params.offset += 'left: ' + (params.radius - params.left - params.opposite.left) + 'px;';
+ params.offset += 'left: ' + Math.max(0, params.radius - params.left - params.opposite.left) + 'px;';
}
params.offset_x = (!params.use_shape && params.left) ? 0.5 * multiplier : 0;
params.offset_y = (!params.use_shape && params.top) ? 0.5 * multiplier : 0;
params.rotation = rotate(params.type);
// multiply all numeric values
walkArray(num_properties, function(i, n){
params[n] *= multiplier;
});
var data = /* '<v:group class="vml" ' + replaceEntities(group_data, params) + '>' + */
drawBackground(params) +
drawStroke(params) +
/* '</v:group>' */
'';
// if (params.type == 'tl')
// alert(data);
// var elem = createElement('div', 'rocon-cn');
// elem.innerHTML = data;
return data;
},
returnType: function() {
return 2;
}
};
})();
\ No newline at end of file
diff --git a/js_src/worker.js b/js_src/worker.js
index 2e0d994..445ec7d 100644
--- a/js_src/worker.js
+++ b/js_src/worker.js
@@ -1,533 +1,535 @@
/**
* Main worker and caching mechanism used for storing and applying of drawn
* corners to the elements
*
* @author Sergey Chikuyonok (serge.che@gmail.com)
* @link http://chikuyonok.ru
* @include "common.js"
* @include "canvas.js"
*/
var worker = (function(){
/** @type {canvas} Drawing adapter (canvas, SVG, VML) */
var adapter = null,
/** Cached corners */
cache = {},
/** Number of keys in cache */
key_count = 0,
/** Native browser properties used to draw browser corners */
native_props = [],
queue = [],
/** Corner type index in array */
type_pos = {tl: 0, tr: 1, br: 2, bl: 3},
/** CSS properties for corner types */
corner_type_map = {
tl: {
left: 'border-left-width',
left_color: 'border-left-color',
top: 'border-top-width',
top_color: 'border-top-color'
},
tr: {
left: 'border-right-width',
left_color: 'border-right-color',
top: 'border-top-width',
top_color: 'border-top-color'
},
br: {
left: 'border-right-width',
left_color: 'border-right-color',
top: 'border-bottom-width',
top_color: 'border-bottom-color'
},
bl: {
left: 'border-left-width',
left_color: 'border-left-color',
top: 'border-bottom-width',
top_color: 'border-bottom-color'
}
},
opposite_corners = {
tl: 'tr',
tr: 'tl',
bl: 'br',
br: 'bl'
},
css_props = [];
//fill-up CSS properties
walkArray(['left', 'top', 'right', 'bottom'], function(i, n){
var prefix = 'border-' + n;
css_props.push(prefix + '-color', prefix + '-width');
});
/**
* Check if we need to add extra width for image (for shape-type corners)
* @param {Object} params
* @param {String} params
* @return {Boolean}
*/
function needExtraWidth(params, type) {
return params.shape && (type || 'tl').charAt(1) == 'l';
}
/**
* Returns the smallest numbers
* @return {Number}
*/
function min() {
var args = mapArray(arguments, function(n, i){
return parseInt(n) || 0;
});
if (args.length == 2) {
return args[0] < args[1] ? args[0] : args[1];
} else {
var result = args[0];
for (var i = 1; i < args.length; i++) {
if (args[i] < result)
result = args[i];
}
return result;
}
}
/**
* Returns the highest numbers
* @return {Number}
*/
function max() {
var args = mapArray(arguments, function(n, i){
return parseInt(n) || 0;
});
if (args.length == 2)
return args[0] > args[1] ? args[0] : args[1];
else {
var result = args[0];
for (var i = 1; i < args.length; i++) {
if (args[i] > result)
result = args[i];
}
return result;
}
}
/**
* Returns key used to store image data
* @param {Array|Object} params Corner parameters
* @return {String}
*/
function cacheKey(params) {
var result = [];
if (params instanceof Array)
for (var i = 0; i < params.length; i++)
result.push(params[i]);
else
for (var a in params) if (params.hasOwnProperty(a))
result.push(a + ':' + params[a]);
return result.join(';');
}
/**
* Add value to cache
* @param {String} key Cache key
* @param {String} [value] Cache value. If not set, internal class name will be used
* @return {String} Internal class name
*/
function addToCache(key, value) {
if (getCachedValue(key))
return getCachedValue(key);
key_count++;
cache[key] = value || rule_prefix + key_count;
return rule_prefix + key_count;
}
/**
* Returns cached value
* @param {String} key cache key
* @return {String|null}
*/
function getCachedValue(key) {
return cache[key];
}
/**
* Add native CSS corners to the element
* @param {Array} radius Set of border radius values
* @param {HTMLElement} elem Element to add corners
*/
function addNativeCorners(radius, elem) {
var key = cacheKey(radius),
css_class = getCachedValue(key),
css_rules = '';
if (!css_class) {
css_class = addToCache(key);
walkArray(native_props, function(i, n){
css_rules += n + ':' + radius[i] + 'px;';
});
addRule('.' + css_class, css_rules);
}
addClass(css_class, elem);
}
/**
* Creates, if necessary, new corner elements and returns them
* @param {HTMLElement} elem Container element
* @return {Object}
*/
function createCornerElements(elem) {
var result = {},
found = 0,
re = new RegExp('\\b' + base_class + '-([tblr]{2})\\b', 'i'),
m;
walkArray(elem.childNodes, function(i, /* HTMLElement */ n){
if (m = re.exec(n.className)) {
found++;
result[m[1]] = n;
}
});
if (!found) {
walkArray(['tl', 'tr', 'bl', 'br'], function(i, n) {
var e = createElement('span', base_class + ' ' + base_class +'-' + n);
elem.appendChild(e);
result[n] = e;
});
}
return result;
}
/**
* Add element to drawing queue
* @param {Object} params Parent element params
* @param {HTMLElement} parent Parent element
* @param {Object} corners Corner elements
*/
function addToQueue(params, parent, corners) {
queue.push([params, parent, corners]);
}
/**
* Removes old internal classes from element
* @param {HTMLElement} elem
* @param {String} new_class New class name to add (optional)
* @return {HTMLElement}
*/
function cleanUp(elem, new_class) {
elem.className = elem.className.replace(/\s*rocon__\d+/, '');
if (new_class)
elem.className += ' ' + new_class;
return elem;
}
/**
* Returns width that must be set for specified corner type
* @param {Object} params Corner's container element params
* @param {String} type Corner type (tl, tr, bl, br)
* @return {Number}
*/
function getCornerWidth(params, type) {
return needExtraWidth(params, type) ? 2000 : params.radius[type_pos[type]];
}
/**
* Returns height that must be set for specified corner type
* @param {Object} params Corner's container element params
* @param {String} type Corner type (tl, tr, bl, br)
* @return {Number}
*/
function getCornerHeight(params, type) {
var cur_pos = type_pos[type],
op_pos = type_pos[ opposite_corners[type] ];
return Math.max(params.radius[cur_pos], params.radius[op_pos]);
}
/**
* Draw corners using adapter
* @param {Object} params Parent element params
* @param {HTMLElement} parent Parent element
* @param {HTMLElement[]} corners Corner elements
* @param {Object} style Cached CSS properties
*/
function drawCorners(params, parent, corners, style) {
// gather all params for all corners
var all_params = {}, css_map, elem, style;
for (var corner_type in corners) if (corners.hasOwnProperty(corner_type)) {
css_map = corner_type_map[corner_type];
/** @type {HTMLElement} */
elem = corners[corner_type];
style = style || getStyle(parent, css_props);
// debugger;
// gather params for current corner
var r = parseInt(params.radius[ type_pos[corner_type] ]);
all_params[corner_type] = {
radius: r,
top: min(style[css_map.top], r),
real_top: parseInt(style[css_map.top]) || 0,
top_color: convertColorToHex(style[css_map.top_color]),
left: min(style[css_map.left], r),
real_left: parseInt(style[css_map.left]) || 0,
left_color: convertColorToHex(style[css_map.left_color]),
color: getBg(params.shape ? parent : parent.parentNode),
use_shape: params.shape,
type: corner_type,
width: max(getCornerWidth(params, corner_type), parseInt(style[css_map.left]) || 0),
height: getCornerHeight(params, corner_type)
};
}
// create corners
for (var corner_type in corners) {
/** @type {HTMLElement} */
elem = corners[corner_type];
var cparams = all_params[corner_type];
// calculate X and Y offsets
cparams.offset_x = -cparams.real_left;
cparams.offset_y = -(params.shape ? max(cparams.height, cparams.radius, cparams.real_top) : cparams.real_top);
var op_corner = opposite_corners[corner_type],
key = cacheKey(cparams);
cparams.opposite = all_params[op_corner];
if (needExtraWidth(params, corner_type)) {
//add extra properties for cache key
key += '--' + (cparams.left + all_params[op_corner].left) +
':' + params.radius[ type_pos[op_corner] ];
}
var css_class = getCachedValue(key);
if (!css_class) {
// image is not yet created
css_class = addToCache(key);
var css_rules = 'height:' + cparams.height + 'px;';
if (adapter.returnType() != 2) // adapter draws image in data:url format
css_rules += 'background-image:url(' + adapter.draw(cparams) + ');';
var offset_top = -(params.shape ? Math.max(cparams.height, cparams.radius) : cparams.top);
css_rules += ( corner_type.charAt(0) == 't' ? 'top:' : 'bottom:' ) + cparams.offset_y + 'px;';
css_rules += ( corner_type.charAt(1) == 'l' ? 'left:' : 'right:' ) + cparams.offset_x + 'px;';
if (needExtraWidth(params, corner_type)) {
+ var size_delta = max(cparams.left + cparams.opposite.left - cparams.radius, 0);
css_rules += 'width:100%;' +
- 'background-position:' + (cparams.radius - cparams.left - cparams.opposite.left) + 'px 0px;' +
- 'left:' + (-cparams.radius + cparams.opposite.left) + 'px;';
+ 'background-position:' + Math.max(0, cparams.radius - cparams.left - cparams.opposite.left) + 'px 0px;' +
+ 'left:' + min(-cparams.radius + cparams.opposite.left - size_delta, cparams.offset_x) + 'px;' +
+ 'padding-right:' + (size_delta + max(cparams.real_left - cparams.radius, 0)) + 'px';
// css_rules += 'width:100%;' +
// 'padding-left:' + (cparams.real_left + all_params[op_corner].left) + 'px;' +
// 'clip:rect(auto,auto,auto,' + params.radius[ type_pos[op_corner] ] + 'px);' +
// 'background-position:top right;';
} else {
css_rules += 'width:' + cparams.width + 'px;';
}
addRule('.' + css_class, css_rules);
}
cleanUp(elem, css_class);
if (adapter.returnType() == 2) {
var corner = adapter.draw(cparams);
if (typeof(corner) == 'string') {
elem.innerHTML = corner;
} else {
elem.innerHTML = '';
elem.appendChild(corner);
}
}
}
cleanUp(parent);
if (!hasClass(parent, 'rocon-init'))
addClass('rocon-init', parent);
if (params.shape)
adjustBox(params, parent);
}
/**
* Add corners drawn by <code>adapter</code> to the element
* @param {Array} params.radius Array of radius values
* @param {Boolean} params.shape Use shape instead of counter-shape
* @param {HTMLElement} elem Element to apply corners
* @param {Boolean} [is_immediate] Draw corners immediately instead adding element to the queue (may cause performance issues in Opera)
*/
function addAdapterCorners(params, elem, is_immediate) {
/*
* Due to stupid Opera bug (http://chikuyonok.ru/playground/opera-bug/)
* we need to split this single process into two loops:
* 1. Add corner elements to the container
* 2. Draw images and apply them to the corners
*/
var corners = createCornerElements(elem);
if (is_immediate)
drawCorners(params, elem, corners);
else
addToQueue(params, elem, corners);
}
/**
* Main processing function
* @param {Array} params.radius Array of radius values
* @param {Boolean} params.shape Use shape instead of counter-shape
* @param {Boolean} params.force {Boolean} Force usage of drawing adapter instead of native properties
* @param {HTMLElement} elem Element to apply corners
* @param {Boolean} [is_immediate] Draw corners immediately instead adding element to the queue (may cause performance issues in Opera)
*/
function process(params, elem, is_immediate) {
if (native_props.length && !params.force) {
addNativeCorners(params.radius, elem);
} else {
addAdapterCorners(params, elem, is_immediate);
}
}
/**
* ÐоÑÑекÑиÑÑÐµÑ CSS-ÑвойÑÑва ÑлеменÑа Ð´Ð»Ñ Ð¿ÑавилÑного ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ Ñголков в виде
* ÑоÑмÑ
* @param {Object} params Corner params
* @param {HTMLElement} elem ÐлеменÑ, коÑоÑÑй нÑжно подкоÑÑекÑиÑоваÑÑ
*/
function adjustBox(params, elem) {
var pt = 'padding-top',
pb = 'padding-bottom',
mt = 'margin-top',
mb = 'margin-bottom',
btw = 'border-top-width',
bbw = 'border-bottom-width',
getProp = function(prop) {
return parseInt(elem_styles[prop], 10) || 0;
},
addCSSRule = function(property, value) {
return property + ':' + value + 'px !important;';
},
elem_styles = getStyle(elem, [pt, pb, mt, mb, btw, bbw]),
offset_top = Math.max(params.radius[ type_pos['tl'] ], params.radius[ type_pos['tr'] ]),
offset_bottom = Math.max(params.radius[ type_pos['bl'] ], params.radius[ type_pos['br'] ]),
offset_border_top = Math.min(offset_top, getProp(btw)),
offset_border_bottom = Math.min(offset_bottom, getProp(bbw));
/*
* ÐÑполÑзÑем ÑоÑмÑ, поÑÑÐ¾Ð¼Ñ Ñ Ð±Ð»Ð¾ÐºÐ° Ñнижаем веÑÑ
ние и нижние
* боÑдÑÑÑ, а Ñакже на велиÑÐ¸Ð½Ñ ÑадиÑÑа Ñнижаем веÑÑ
ний
* и нижний паддинг
*/
var padding_top = Math.max(getProp(pt) - offset_top + offset_border_top, 0),
padding_bottom = Math.max(getProp(pb) - offset_bottom + offset_border_bottom, 0),
margin_top = getProp(mt) + offset_top,
margin_bottom = getProp(mb) + offset_bottom,
border_top_width = getProp(btw) - offset_border_top,
border_bottom_width = getProp(bbw) - offset_border_bottom,
key = cacheKey([padding_top, padding_bottom, margin_top, margin_bottom, border_top_width, border_bottom_width]),
class_name = getCachedValue(key);
if (!class_name) {
class_name = addToCache(key);
addRule('.' + class_name,
addCSSRule(btw, border_top_width) +
addCSSRule(bbw, border_bottom_width) +
addCSSRule(pt, padding_top) +
addCSSRule(pb, padding_bottom) +
addCSSRule(mt, margin_top) +
addCSSRule(mb, margin_bottom));
}
elem.className += ' ' + class_name;
}
return {
/**
* Set drawing adapter
*/
setAdapter: function(obj) {
adapter = obj;
if ('init' in adapter)
adapter.init();
},
/**
* Set native CSS properties for drawing rounded borders
* @param {String} tl Top-left corner
* @param {String} tr Top-right corner
* @param {String} br Bottom-right corner
* @param {String} bl Bottom-left corner
*/
nativeProperties: function(tl, tr, br, bl) {
native_props = [tl, tr, br, bl];
},
/**
* Enqueue element for corners addition
* @param {Array} params.radius Array of radius values
* @param {Boolean} params.shape Use shape instead of counter-shape
* @param {Boolean} params.force {Boolean} Force usage of drawing adapter instead of native properties
* @param {HTMLElement} elem Element to apply corners
*/
add: function(params, elem) {
process(params, elem);
},
/**
* Add corners to enqueued elements
*/
run: function() {
var start = (new Date).getTime();
walkArray(queue, function(i, n){
drawCorners(n[0], n[1], n[2]);
});
var stop1 = (new Date).getTime();
applyCSS();
var stop2 = (new Date).getTime();
// alert('Draw: ' + (stop1 - start) + ' ms, CSS: ' + (stop2 - stop1) + ' ms');
},
/**
* Add corners to the element
*/
apply: function(params, elem) {
process(params, elem, true);
}
}
})();
\ No newline at end of file
diff --git a/test/draw-test.html b/test/draw-test.html
index 95561ee..2916587 100644
--- a/test/draw-test.html
+++ b/test/draw-test.html
@@ -1 +1 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" debug="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<style type="text/css">
.rounded {
padding:10px;
background:red;
white-space:nowrap;
zoom:1;
}
* html div.rounded {
height:20px;
}
span.rounded {
padding:3px 10px;
margin:-3px 0;
}
p{
line-height:1.5;
}
.some-class {
color: red;
}
h2 {
clear:both;
}
.wrap {
float:left;
padding:20px;
overflow:hidden;
margin:10px;
width:15%;
}
.bg-wrap {
background:url(../bg.jpg);
padding:10px;
overflow:hidden;
}
* html .bg-wrap {
float:left;
}
.with-border {
border:3px solid #000;
}
.b1{border:1px solid blue;}
.b2{border:2px solid blue;}
.b3{border:3px solid blue;}
.b4{border:4px solid blue;}
.b5{border:5px solid blue;}
.b6{border:6px solid blue;}
.b7{border:7px solid blue;}
.b8{border:8px solid blue;}
.b9{border:9px solid blue;}
.b10{border:10px solid blue;}
.b11{border:11px solid blue;}
.b12{border:12px solid blue;}
.b13{border:13px solid blue;}
.b14{border:14px solid blue;}
.b15{border:15px solid blue;}
.b16{border:16px solid blue;}
.b17{border:17px solid blue;}
.b18{border:18px solid blue;}
.b19{border:19px solid blue;}
.b20{border:20px solid blue;}
#borders .rounded {
background-image: url(../gradient.png);
background-repeat: repeat-x;
}
.rocon-init {
position:relative;
}
.rocon {
display:block;
position:absolute;
overflow:hidden;
background-repeat:no-repeat;
}
.rocon-tr {
background-position:top right;
}
.rocon-br {
background-position:bottom right;
}
.rocon .rocon-cn {
position:absolute;
}
.rocon-br .rocon-cn,
.rocon-tr .rocon-cn {
right:0;
}
</style>
<!-- <script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script> -->
<script type="text/javascript" src="../js_src/common.js"></script>
<!-- <script type="text/javascript" src="../js_src/ie.js"></script> -->
<script type="text/javascript" src="../js_src/canvas.js"></script>
<script type="text/javascript" src="../js_src/svg.js"></script>
<script type="text/javascript" src="../js_src/vml.js"></script>
<script type="text/javascript" src="../js_src/worker.js"></script>
<script type="text/javascript" src="../js_src/init.js"></script>
<script type="text/javascript">
var rocon = result;
</script>
</head>
<body>
<h2>ÐÑовеÑка ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ ÑоÑмÑ</h2>
<div class="bg-wrap">
<div class="wrap">
<div class="rounded rc10 b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" debug="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<style type="text/css">
.rounded {
padding:10px;
background:red;
white-space:nowrap;
zoom:1;
}
* html div.rounded {
height:20px;
}
span.rounded {
padding:3px 10px;
margin:-3px 0;
}
p{
line-height:1.5;
}
.some-class {
color: red;
}
h2 {
clear:both;
}
.wrap {
float:left;
padding:20px;
overflow:hidden;
margin:10px;
width:15%;
}
.bg-wrap {
background:url(../bg.jpg);
padding:10px;
overflow:hidden;
}
* html .bg-wrap {
float:left;
}
.with-border {
border:3px solid #000;
}
.b1{border:1px solid blue;}
.b2{border:2px solid blue;}
.b3{border:3px solid blue;}
.b4{border:4px solid blue;}
.b5{border:5px solid blue;}
.b6{border:6px solid blue;}
.b7{border:7px solid blue;}
.b8{border:8px solid blue;}
.b9{border:9px solid blue;}
.b10{border:10px solid blue;}
.b11{border:11px solid blue;}
.b12{border:12px solid blue;}
.b13{border:13px solid blue;}
.b14{border:14px solid blue;}
.b15{border:15px solid blue;}
.b16{border:16px solid blue;}
.b17{border:17px solid blue;}
.b18{border:18px solid blue;}
.b19{border:19px solid blue;}
.b20{border:20px solid blue;}
#borders .rounded {
background-image: url(../gradient.png);
background-repeat: repeat-x;
}
.rocon-init {
position:relative;
}
.rocon {
display:block;
position:absolute;
overflow:hidden;
background-repeat:no-repeat;
}
.rocon-tr {
background-position:top right;
}
.rocon-br {
background-position:bottom right;
}
.rocon .rocon-cn {
position:absolute;
}
.rocon-br .rocon-cn,
.rocon-tr .rocon-cn {
right:0;
}
</style>
<!-- <script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script> -->
<script type="text/javascript" src="../js_src/common.js"></script>
<!-- <script type="text/javascript" src="../js_src/ie.js"></script> -->
<script type="text/javascript" src="../js_src/canvas.js"></script>
<script type="text/javascript" src="../js_src/svg.js"></script>
<script type="text/javascript" src="../js_src/vml.js"></script>
<script type="text/javascript" src="../js_src/worker.js"></script>
<script type="text/javascript" src="../js_src/init.js"></script>
<script type="text/javascript">
var rocon = result;
</script>
</head>
<body>
<h2>ÐÑовеÑка ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ ÑоÑмÑ</h2>
<div class="bg-wrap">
<div class="wrap">
<div class="rounded rc10 b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10 b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
|
sergeche/rocon
|
379221176de8d3c900924fbdce4af798cade4cd8
|
No background-repead
|
diff --git a/test/speed-test.html b/test/speed-test.html
index a110f5e..1ccbeca 100644
--- a/test/speed-test.html
+++ b/test/speed-test.html
@@ -1 +1 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" debug="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<style type="text/css">
.rounded {
padding:10px;
background:red;
white-space:nowrap;
zoom:1;
}
* html div.rounded {
height:20px;
}
span.rounded {
padding:3px 10px;
margin:-3px 0;
}
p{
line-height:1.5;
}
.some-class {
color: red;
}
h2 {
clear:both;
}
.wrap {
float:left;
padding:20px;
overflow:hidden;
margin:10px;
width:15%;
}
.bg-wrap {
background:url(../bg.jpg);
padding:10px;
overflow:hidden;
}
* html .bg-wrap {
float:left;
}
.with-border {
border:3px solid #000;
}
.b1{border:1px solid blue;}
.b2{border:2px solid blue;}
.b3{border:3px solid blue;}
.b4{border:4px solid blue;}
.b5{border:5px solid blue;}
.b6{border:6px solid blue;}
.b7{border:7px solid blue;}
.b8{border:8px solid blue;}
.b9{border:9px solid blue;}
.b10{border:10px solid blue;}
.b11{border:11px solid blue;}
.b12{border:12px solid blue;}
.b13{border:13px solid blue;}
.b14{border:14px solid blue;}
.b15{border:15px solid blue;}
.b16{border:16px solid blue;}
.b17{border:17px solid blue;}
.b18{border:18px solid blue;}
.b19{border:19px solid blue;}
.b20{border:20px solid blue;}
#borders .rounded {
background-image: url(../gradient.png);
background-repeat: repeat-x;
}
.rocon-init {
position:relative;
}
.rocon {
display:block;
position:absolute;
overflow:hidden;
}
.rocon-tr {
background-position:top right;
}
.rocon-br {
background-position:bottom right;
}
.rocon .rocon-cn {
position:absolute;
}
.rocon-br .rocon-cn,
.rocon-tr .rocon-cn {
right:0;
}
</style>
<!-- <script type="text/javascript" src="../js_src/firebug.js"></script> -->
<script type="text/javascript" src="../js_src/common.js"></script>
<!-- <script type="text/javascript" src="../js_src/ie.js"></script> -->
<script type="text/javascript" src="../js_src/canvas.js"></script>
<script type="text/javascript" src="../js_src/svg.js"></script>
<script type="text/javascript" src="../js_src/vml.js"></script>
<script type="text/javascript" src="../js_src/worker.js"></script>
<script type="text/javascript" src="../js_src/init.js"></script>
<script type="text/javascript">
var rocon = result;
</script>
</head>
<body>
<h2>ÐÑовеÑка ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ ÑоÑмÑ</h2>
<div class="bg-wrap">
<div class="wrap">
<div class="rounded rc10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10 b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" debug="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<style type="text/css">
.rounded {
padding:10px;
background:red;
white-space:nowrap;
zoom:1;
}
* html div.rounded {
height:20px;
}
span.rounded {
padding:3px 10px;
margin:-3px 0;
}
p{
line-height:1.5;
}
.some-class {
color: red;
}
h2 {
clear:both;
}
.wrap {
float:left;
padding:20px;
overflow:hidden;
margin:10px;
width:15%;
}
.bg-wrap {
background:url(../bg.jpg);
padding:10px;
overflow:hidden;
}
* html .bg-wrap {
float:left;
}
.with-border {
border:3px solid #000;
}
.b1{border:1px solid blue;}
.b2{border:2px solid blue;}
.b3{border:3px solid blue;}
.b4{border:4px solid blue;}
.b5{border:5px solid blue;}
.b6{border:6px solid blue;}
.b7{border:7px solid blue;}
.b8{border:8px solid blue;}
.b9{border:9px solid blue;}
.b10{border:10px solid blue;}
.b11{border:11px solid blue;}
.b12{border:12px solid blue;}
.b13{border:13px solid blue;}
.b14{border:14px solid blue;}
.b15{border:15px solid blue;}
.b16{border:16px solid blue;}
.b17{border:17px solid blue;}
.b18{border:18px solid blue;}
.b19{border:19px solid blue;}
.b20{border:20px solid blue;}
#borders .rounded {
background-image: url(../gradient.png);
background-repeat: repeat-x;
}
.rocon-init {
position:relative;
}
.rocon {
display:block;
position:absolute;
overflow:hidden;
background-repeat:no-repeat;
}
.rocon-tr {
background-position:top right;
}
.rocon-br {
background-position:bottom right;
}
.rocon .rocon-cn {
position:absolute;
}
.rocon-br .rocon-cn,
.rocon-tr .rocon-cn {
right:0;
}
</style>
<!-- <script type="text/javascript" src="../js_src/firebug.js"></script> -->
<script type="text/javascript" src="../js_src/common.js"></script>
<!-- <script type="text/javascript" src="../js_src/ie.js"></script> -->
<script type="text/javascript" src="../js_src/canvas.js"></script>
<script type="text/javascript" src="../js_src/svg.js"></script>
<script type="text/javascript" src="../js_src/vml.js"></script>
<script type="text/javascript" src="../js_src/worker.js"></script>
<script type="text/javascript" src="../js_src/init.js"></script>
<script type="text/javascript">
var rocon = result;
</script>
</head>
<body>
<h2>ÐÑовеÑка ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ ÑоÑмÑ</h2>
<div class="bg-wrap">
<div class="wrap">
<div class="rounded rc10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10 b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
|
sergeche/rocon
|
92151f31dc19035b7fb591a395ae739cfb5948a0
|
Fixed bug with incorrect background seek in Safari
|
diff --git a/js_src/canvas.js b/js_src/canvas.js
index 2df142e..11698a1 100644
--- a/js_src/canvas.js
+++ b/js_src/canvas.js
@@ -1,243 +1,244 @@
/**
* Canvas adapter for drawing rounded corners
* @author Sergey Chikuyonok (serge.che@gmail.com)
* @link http://chikuyonok.ru
*
* @include "common.js"
* @include "/js-libs/canvas-doc.js"
*/
var canvas = (function(){
var composite_op = 'destination-out',
/** @type {Element} Canvas where all images are drawn */
cv,
/** @type {Element} Canvas for stroke */
stroke_cv,
/** @type {CanvasRenderingContext2D} Drawing context */
ctx,
/** @type {CanvasRenderingContext2D} Stroke drawing context */
stroke_ctx,
/** Type of returnerd object of <code>draw()</code> method (1 â image string, 2 â canvas element) */
return_type = 1;
// debug only
// document.body.appendChild(cv);
/**
* Prepare canvas for drawing: removes old paintings, restores original
* transform matrix, scales canvas
*
* @param {Number} params.radius Corner radius
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
* @param {String} params.type Corner type: tl, tr, bl, br
*/
function prepare(params) {
ctx.restore();
cv.width = params.width;
cv.height = params.height;
ctx.clearRect(0, 0, cv.width, cv.height);
ctx.save();
}
/**
* Draw border shape (stroke) on <code>ctx</code>. Canvas must be already
* scaled to the size of corner.
*
* @param {Number} params.radius Corner radius
* @param {Number} params.left Left border width, pixels
* @param {String} params.left_color Left border color
* @param {Number} params.top Top border width, pixels
* @param {String} params.top_color Top border color
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
*/
function drawStroke(params) {
// create short-hand vars for better YUICompressor mungin
var radius = params.radius,
border_left = params.left,
border_top = params.top;
if (!(border_left + border_top))
// nothing to draw
return;
stroke_cv.width = params.width;
stroke_cv.height = params.height;
stroke_ctx.clearRect(0, 0, params.width, params.height);
if (border_top) {
stroke_ctx.fillStyle = params.top_color;
stroke_ctx.fillRect(radius, 0, cv.width, border_top);
}
if (border_left) {
stroke_ctx.fillStyle = params.left_color;
stroke_ctx.fillRect(0, radius, border_left, cv.height);
}
stroke_ctx.save();
if (params.top_color != params.left_color) {
var grd = ctx.createLinearGradient(0, border_top, 0, radius);
grd.addColorStop(0, border_top ? params.top_color : params.left_color);
grd.addColorStop(1, border_left ? params.left_color : params.top_color);
stroke_ctx.fillStyle = grd;
} else {
stroke_ctx.fillStyle = params.top_color;
}
// start drawing two circles to create border arc
ctx.save();
stroke_ctx.beginPath();
stroke_ctx.arc(radius, radius, radius, 0, Math.PI * 2, true);
stroke_ctx.fill();
ctx.restore();
// change composite operation so the next circle will be extracted from the previous one
stroke_ctx.globalCompositeOperation = composite_op;
stroke_ctx.translate(border_left, border_top);
if (radius) {
stroke_ctx.scale(Math.max(1 - border_left / radius, 0) || 0.01, Math.max(1 - border_top / radius, 0) || 0.01);
}
stroke_ctx.beginPath();
stroke_ctx.arc(radius, radius, radius, 0, Math.PI * 2, true);
stroke_ctx.fill();
stroke_ctx.restore();
// leave only one quarter of circle
stroke_ctx.clearRect(radius, border_top, radius, cv.height);
stroke_ctx.clearRect(border_left, radius, cv.width, cv.height);
ctx.drawImage(stroke_cv, 0, 0);
}
/**
* Rotate canvas for specified corner type
*
* @param {String} Corner type: tl, tr, bl, br
* @param {Number} radius Corner radius
*/
function rotate(params) {
switch (params.type) {
case 'tr': // top right corner
ctx.scale(-1, 1);
ctx.translate(-params.width, 0);
break;
case 'bl': // bottom left corner
ctx.scale(1, -1);
ctx.translate(0, -params.height);
break;
case 'br': // bottom right corner
ctx.scale(-1, -1);
ctx.translate(-params.width, -params.height);
break;
}
}
/**
* Draw background for corner image
*
* @param {Number} params.radius Corner radius
* @param {Number} params.left Left border width, pixels
* @param {Number} params.top Top border width, pixels
* @param {String} params.color Color of background
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
*/
function drawBackground(params) {
var radius = params.radius,
offset_x = 0,
offset_y = 0;
ctx.save();
ctx.fillStyle = params.color;
if (!params.use_shape) {
ctx.fillRect(0, 0, radius, radius);
if (params.left)
offset_x = .5;
if (params.top)
offset_y = .5;
ctx.globalCompositeOperation = composite_op;
} else {
if (params.left)
offset_x = 1;
if (params.top)
offset_y = 1;
}
ctx.translate(offset_x, offset_y);
ctx.beginPath();
ctx.fillStyle = params.color;
ctx.arc(radius, radius, radius, 0, Math.PI * 2, true);
+ ctx.closePath();
ctx.fill();
ctx.restore();
if (params.use_shape) {
ctx.fillStyle = params.color;
ctx.fillRect(radius, 0, cv.width, cv.height);
ctx.fillRect(0, radius, cv.width, cv.height);
}
}
return {
init: function() {
cv = createElement('canvas');
ctx = cv.getContext('2d');
cv.width = 10;
cv.height = 10;
stroke_cv = createElement('canvas');
stroke_ctx = stroke_cv.getContext('2d');
},
/**
* Draw rounded corner
*
* @param {Number} params.radius Corner radius
* @param {Number} params.left Left border width, pixels
* @param {String} params.left_color Left border color
* @param {Number} params.top Top border width, pixels
* @param {String} params.top_color Top border color
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
* @param {String} params.color Color of background
* @param {String} params.type Corner type: tl, tr, bl, br
*
* @return {String} Image in data:URL format
*/
draw: function(params) {
// TODO delete this
params.width = params.width || params.radius;
params.height = params.height || params.radius;
if (return_type == 2) {
cv = createElement('canvas', 'rocon-cn');
ctx = cv.getContext('2d');
}
prepare(params);
rotate(params);
drawBackground(params);
drawStroke(params);
return (return_type == 2) ? cv : cv.toDataURL();
},
returnType: function(type) {
if (typeof(type) != 'undefined')
return_type = type;
return return_type;
}
};
})();
\ No newline at end of file
diff --git a/js_src/common.js b/js_src/common.js
index 03c4d93..51f2ab3 100644
--- a/js_src/common.js
+++ b/js_src/common.js
@@ -1,531 +1,531 @@
/*!
* Rocon: library that creates rounded corners
* @author Sergey Chikuyonok (serge.che@gmail.com)
* @link http://code.google.com/p/rocon/
*/
/**
* ÐбÑие меÑÐ¾Ð´Ñ Ð¸ ÑвойÑÑва Ð´Ð»Ñ rocon
* @author Sergey Chikuyonok (sc@design.ru)
* @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
* @include "worker.js"
*/
var re_rule = /\.rc(\d+)\b/,
re_class = /\brc(\d+(?:\-\d+){0,3})(\-.+?)?\b/,
re_shape_flag = /\brc-shape\b/,
/** ÐазовÑй клаÑÑ Ð´Ð»Ñ ÑоздаваемÑÑ
ÑлеменÑов */
base_class = 'rocon',
/** ÐÑеÑиÑк Ð´Ð»Ñ ÑоздаваемÑÑ
CSS-пÑавил */
rule_prefix = base_class + '__',
/** РезÑлÑÑаÑ, возвÑаÑаемÑй в обÑÐµÐºÑ <code>rocon</code> */
result = {
/**
* Ðобавление/обновление Ñголков Ð´Ð»Ñ Ð´Ð¸Ð½Ð°Ð¼Ð¸ÑеÑки ÑозданнÑÑ
ÑлеменÑов.
* ÐÐ¾Ð¶ÐµÑ Ð¿ÑинимаÑÑ Ð½ÐµÐ¾Ð³ÑаниÑенное колиÑеÑÑво ÑлеменÑов либо маÑÑивов
* ÑлеменÑов, Ñ ÐºÐ¾ÑоÑÑÑ
нÑжно обновиÑÑ Ñголки
*/
update: function(){},
process: function(context) {
processRoundedElements(context);
}
},
/** @type {CSSStyleSheet} ТаблиÑа ÑÑилей Ð´Ð»Ñ Ñголков */
corners_ss = null,
css_text = '',
/** СпиÑок ÑÑнкÑий, коÑоÑÑе нÑжно вÑполниÑÑ Ð¿Ñи загÑÑзке DOM-деÑева */
dom_ready_list = [],
/** ÐагÑÑзилÑÑ Ð»Ð¸ DOM? */
is_ready = false,
/** ÐÑивÑзано ли ÑобÑÑие, ожидаÑÑее загÑÑÐ·ÐºÑ DOM? */
readyBound = false,
userAgent = navigator.userAgent.toLowerCase(),
/** Тип и веÑÑÐ¸Ñ Ð±ÑаÑзеÑа полÑзоваÑелÑ. ÐзÑÑо Ñ jQuery */
browser = {
version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
safari: /webkit/.test( userAgent ),
opera: /opera/.test( userAgent ),
msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};
/**
* ÐÑполнÑÐµÑ Ð²Ñе ÑÑнкÑии, добавленнÑе на ÑобÑÑие onDomContentLoaded.
* ÐзÑÑо Ñ jQuery
*/
function fireReady() {
//Make sure that the DOM is not already loaded
if (!is_ready) {
// Remember that the DOM is ready
is_ready = true;
// If there are functions bound, to execute
if ( dom_ready_list.length ) {
walkArray(dom_ready_list, function(){
this.call(document);
}, true);
// Reset the list of functions
dom_ready_list = null;
}
}
}
/**
* ÐобавлÑÐµÑ ÑлÑÑаÑÐµÐ»Ñ Ð½Ð° ÑобÑÑие onDomContentLoaded
* @type {Function} fn СлÑÑаÑелÑ
*/
function addDomReady(fn) {
dom_ready_list.push(fn);
}
/**
* ÐÑовеÑка на наÑÑÑпление ÑобÑÑÐ¸Ñ onDomContentLoaded.
* ÐзÑÑо Ñ jQuery
*/
function bindReady(){
if ( readyBound ) return;
readyBound = true;
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
fireReady();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
fireReady();
}
});
// If IE and not an iframe
// continually check to see if the document is ready
if ( document.documentElement.doScroll && !window.frameElement ) (function(){
if ( is_ready ) return;
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch( error ) {
setTimeout( arguments.callee, 0 );
return;
}
// and execute any waiting functions
fireReady();
})();
}
}
/**
* ÐÑпомогаÑелÑÐ½Ð°Ñ ÑÑнкÑиÑ, коÑоÑÐ°Ñ Ð¿ÑобегаеÑÑÑ Ð¿Ð¾ вÑем ÑлеменÑам маÑÑива
* <code>ar</code> и вÑполнÑÐµÑ Ð½Ð° каждом ÑлеменÑе его ÑлеменÑе ÑÑнкÑиÑ
* <code>fn</code>. <code>this</code> внÑÑÑи ÑÑой ÑÑнкÑии ÑказÑÐ²Ð°ÐµÑ Ð½Ð°
* ÑÐ»ÐµÐ¼ÐµÐ½Ñ Ð¼Ð°ÑÑива
* @param {Array} ar ÐаÑÑив, по коÑоÑÐ¾Ð¼Ñ Ð½Ñжно пÑобежаÑÑÑÑ
* @param {Function} fn ФÑнкÑиÑ, коÑоÑÑÑ Ð½Ñжно вÑполниÑÑ Ð½Ð° каждом ÑлеменÑе маÑÑива
* @param {Boolean} forward ÐеÑебиÑаÑÑ Ð·Ð½Ð°ÑÐµÐ½Ð¸Ñ Ð¾Ñ Ð½Ð°Ñала маÑÑива (п ÑмолÑаниÑ: Ñ ÐºÐ¾Ð½Ñа)
*/
function walkArray(ar, fn, forward) {
if (forward) {
for (var i = 0, len = ar.length; i < len; i++)
if (fn.call(ar[i], i, ar[i]) === false)
break;
} else {
for (var i = ar.length - 1; i >= 0; i--)
if (fn.call(ar[i], i, ar[i]) === false)
break;
}
}
/**
* ÐÑеобÑазÑÐµÑ Ð¾Ð´Ð¸Ð½ маÑÑив ÑлеменÑов в дÑÑгой Ñ Ð¿Ð¾Ð¼Ð¾ÑÑÑ ÑÑнкÑии callback.
* ÐзÑÑо в jQuery
* @param {Array} elems
* @param {Function} callback
* @return {Array}
*/
function mapArray(elems, callback) {
var ret = [];
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0, length = elems.length; i < length; i++ ) {
var value = callback( elems[ i ], i );
if ( value != null )
ret[ ret.length ] = value;
}
return ret.concat.apply( [], ret );
}
// TODO ÐобавиÑÑ Ð¸ÑклÑÑение пÑи пÑавилÑной ÑабоÑе border-radius
/**
* ÐÑеобÑазÑÐµÑ ÑÐ²ÐµÑ Ð¸Ð· RGB-пÑедÑÑÐ²Ð»ÐµÐ½Ð¸Ñ Ð² hex
* @param {String} color
* @return {String}
*/
function convertColorToHex(color) {
var result;
function s(num) {
var n = parseInt(num, 10).toString(16);
return (n.length == 1) ? n + n : n;
}
function p(num) {
return s(Math.round(num * 2.55));
}
if (result = /rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/.exec(color))
return '#' + s(result[1]) + s(result[2]) + s(result[3]);
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*\)/.exec(color))
return '#' + p(result[1]) + p(result[2]) + p(result[3]);
// Look for #a0b1c2
if (result = /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/i.exec(color))
return '#' + result[1] + result[2] + result[3];
if (result = /#([a-f0-9])([a-f0-9])([a-f0-9])/i.exec(color))
return '#' + result[1] + result[1] + result[2] + result[2] + result[3] + result[3];
s = null;
p = null;
return color;
}
/**
* Ð¡Ð¾Ð·Ð´Ð°ÐµÑ HTML-ÑÐ»ÐµÐ¼ÐµÐ½Ñ <code>name</code> Ñ ÐºÐ»Ð°ÑÑом <code>class_name</code>
* @param {String} name Ðазвание ÑлеменÑа
* @param {String} class_name ÐлаÑÑ ÑлеменÑа
* @return {Element}
*/
function createElement(name, class_name) {
var elem = document.createElement(name);
if (class_name) {
elem.className = class_name;
}
return elem;
}
/**
* ÐÑоÑÑÐ°Ñ Ð¿ÑовеÑка налиÑÐ¸Ñ Ð¾Ð¿Ñеделенного клаÑÑа Ñ ÑлеменÑа
* @param {HTMLElement} elem
* @param {String} class_name
* @return {Boolean}
*/
function hasClass(elem, class_name) {
var re = new RegExp('\\b' + class_name + '\\b');
return elem.nodeType == 1 && re.test(elem.className || '');
}
/**
* Add new class to the element
* @param {String} class_name New class
* @param {HTMLElement} elem Element to add class
*/
function addClass(class_name, elem) {
elem.className += ' ' + class_name;
}
var toCamelCase = (function(){
var cache = {},
camel = function(str, p1){return p1.toUpperCase();},
re = /\-(\w)/g;
return function(name) {
if (!cache[name])
cache[name] = name.replace(re, camel);
return cache[name];
}
})();
/**
* ÐозвÑаÑÐ°ÐµÑ Ð·Ð½Ð°Ñение CSS-ÑвойÑÑва <b>name</b> ÑлеменÑа <b>elem</b>
* @author John Resig (http://ejohn.org)
* @param {Element} elem ÐлеменÑ, Ñ ÐºÐ¾ÑоÑого нÑжно полÑÑиÑÑ Ð·Ð½Ð°Ñение CSS-ÑвойÑÑва
* @param {String|Array} name Ðазвание CSS-ÑвойÑÑва
* @return {String|Object}
*/
function getStyle(elem, name) {
var cs, result = {}, n, name_camel, is_array = name instanceof Array;
var _name = is_array ? name : [name];
for (var i = 0; i < _name.length; i++) {
n = _name[i];
name_camel = toCamelCase(n);
// If the property exists in style[], then it's been set
// recently (and is current)
if (elem.style[name_camel]) {
result[n] = result[name_camel] = elem.style[name_camel];
}
//Otherwise, try to use IE's method
else if (browser.msie) {
result[n] = result[name_camel] = elem.currentStyle[name_camel];
}
// Or the W3C's method, if it exists
else if (document.defaultView && document.defaultView.getComputedStyle) {
if (!cs)
cs = document.defaultView.getComputedStyle(elem, "");
result[n] = result[name_camel] = cs && cs.getPropertyValue(n);
}
}
// walkArray(name instanceof Array ? name : [name], function(i, n){
//
// });
return is_array ? result : result[toCamelCase(name)];
}
/**
* РазвоÑаÑÐ¸Ð²Ð°ÐµÑ ÐºÑаÑкÑÑ Ð·Ð°Ð¿Ð¸ÑÑ ÑеÑÑÑеÑ
знаÑного ÑвойÑÑва в полнÑÑ:<br>
* â a -> a,a,a,a<br>
* â a_b -> a,b,a,b<br>
* â a_b_Ñ -> a,b,Ñ,b<br>
*
* @param {String} prop ÐнаÑение, коÑоÑое нÑжно ÑаÑкÑÑÑÑ
* @return {Array} ÐаÑÑив Ñ 4 знаÑениÑми
*/
function expandProperty(prop) {
var chunks = (prop || '').split(/[\-_]+/);
switch (chunks.length) {
case 1:
return [chunks[0], chunks[0], chunks[0], chunks[0]];
case 2:
return [chunks[0], chunks[1], chunks[0], chunks[1]];
case 3:
return [chunks[0], chunks[1], chunks[2], chunks[1]];
case 4:
return chunks;
}
return null;
}
/**
* ÐозвÑаÑÐ°ÐµÑ ÑÐ²ÐµÑ Ñона ÑлеменÑа
* @type {Function}
* @param {Element} elem ÐлеменÑ, Ð´Ð»Ñ ÐºÐ¾ÑоÑого нÑжно доÑÑаÑÑ ÑÐ²ÐµÑ Ñона
* @return {String}
*/
var getBg = (function() {
var session_elems = [],
default_color = '#ffffff';
/**
* ÐÑновной Ñикл Ñ Ð¸ÑполÑзованием кÑÑиÑованиÑ
*/
function mainLoopCache(elem) {
var c;
do {
if (elem.nodeType != 1)
break;
if (elem.rocon_bg) { // ÑÐ²ÐµÑ Ð±Ñл найден Ñанее
return elem.rocon_bg;
} else { // ÑÐ²ÐµÑ ÐµÑе не найден
session_elems.push(elem);
c = getStyle(elem, 'background-color');
- if (c != 'transparent')
+ if (c != 'transparent' && c != 'rgba(0, 0, 0, 0)')
return convertColorToHex(c);
}
} while (elem = elem.parentNode);
return default_color;
}
/**
* ÐÑновной Ñикл без кÑÑиÑованиÑ
*/
function mainLoopNoCache(elem) {
var c;
do {
if (elem.nodeType != 1)
break;
c = getStyle(elem, 'background-color');
if (c != 'transparent')
return convertColorToHex(c);
} while (elem = elem.parentNode);
return default_color;
}
return function(elem){
var cl = /* String */elem.className,
bg = null;
if (getBg.use_cache) {
session_elems = [];
bg = mainLoopCache(elem);
// закÑÑиÑÑем ÑÐ²ÐµÑ Ñона Ñ Ð²ÑеÑ
ÑлеменÑов, по коÑоÑÑм пÑоÑ
одилиÑÑ
walkArray(session_elems, function(){
this.rocon_bg = bg;
getBg.processed_elems.push(this);
});
session_elems = null;
} else {
bg = mainLoopNoCache(elem);
}
return bg;
};
})();
getBg.use_cache = true;
getBg.processed_elems = [];
var css_rules_cache = [];
/**
* ÐобавлÑÐµÑ CSS-пÑавило в ÑÑилÑ
* @param {String} selector CSS-ÑелекÑоÑ, Ð´Ð»Ñ ÐºÐ¾ÑоÑого нÑжно добавиÑÑ Ð¿Ñавила
* @param {String} rules CSS-пÑавила
*/
function addRule(selector, rule) {
css_rules_cache.push([selector, rule]);
}
/**
* Ð¡Ð¾Ð·Ð´Ð°ÐµÑ Ð½Ð¾Ð²ÑÑ ÑаблиÑÑ ÑÑилей на ÑÑÑаниÑе, кÑда бÑдÑÑ Ð´Ð¾Ð±Ð°Ð²Ð»ÑÑÑÑÑ Ð¿Ñавила
* Ð´Ð»Ñ Ð¾Ð¿Ð¸ÑÐ°Ð½Ð¸Ñ ÑкÑÑгленнÑÑ
Ñголков
* @return {CSSStyleSheet}
*/
function createStylesheet() {
if (!corners_ss) {
if (document.createStyleSheet) {
corners_ss = document.createStyleSheet();
} else {
var style = createElement('style');
document.getElementsByTagName('head')[0].appendChild(style);
corners_ss = style.sheet;
}
}
return corners_ss;
}
function applyCSS() {
if (css_rules_cache.length) {
var sheet = createStylesheet();
if (sheet.addRule) {
// msie way
for (var j = 0; j < css_rules_cache.length; j++) {
var r = css_rules_cache[j];
sheet.addRule(r[0], r[1]);
}
} else {
// W3C way
for (var j = 0; j < css_rules_cache.length; j++) {
var r = css_rules_cache[j];
sheet.insertRule(r[0] + '{' + r[1] + '}', j);
}
}
css_rules_cache.length = 0;
}
}
/**
* ÐозвÑаÑÐ°ÐµÑ Ð¼Ð°ÑÑив ÑлеменÑов, коÑоÑÑм нÑжно добавиÑÑ ÑкÑÑгленнÑе Ñголки.
* ÐлеменÑом маÑÑива ÑвлÑеÑÑÑ Ð¾Ð±ÑÐµÐºÑ Ñо ÑвойÑÑвами <code>node</code>
* и <code>radius</code>
* @param {Element} [context] ÐÑкÑда бÑаÑÑ ÑлеменÑÑ
* @return {Array}
*/
function getElementsToProcess(context) {
var elems = [], m;
walkArray((context || document).getElementsByTagName('*'), function(){
if (m = re_class.exec(this.className || '')) {
var p = (m[2] || '');
elems.push({
node: this,
params: {
radius: expandProperty(m[1]),
shape: (p.indexOf('shape') != -1 ),
force: (p.indexOf('force') != -1 )
}
});
}
});
return elems;
}
/**
* ÐбÑабаÑÑÐ²Ð°ÐµÑ Ð²Ñе ÑлеменÑÑ Ð½Ð° ÑÑÑаниÑе, коÑоÑÑм нÑжно добавиÑÑ ÑкÑÑгленнÑе
* Ñголки
*/
function processRoundedElements(context){
createStylesheet();
var elems = getElementsToProcess(context);
if (elems.length) {
walkArray(elems, function(i, n){
worker.add(this.params, this.node);
});
worker.run();
}
}
/**
* ÐÑименÑÐµÑ Ñголки к ÑлеменÑам, пеÑеданнÑм в маÑÑиве. РоÑновном вÑзÑваеÑÑÑ Ð¸Ð·
* <code>rocon.update()</code>
* @param {arguments} args ÐÑгÑменÑÑ ÑÑнкÑии
* @param {Function} fn ФÑнкÑиÑ, коÑоÑÑÑ Ð½Ñжно вÑполниÑÑ Ð½Ð° каждом ÑлеменÑе
*/
function applyCornersToArgs(args, fn) {
walkArray(args, function(){
walkArray((this instanceof Array) ? this : [this], fn);
});
}
/**
* ÐÐµÐ»Ð°ÐµÑ ÐºÐ¾Ð¿Ð¸Ñ Ð¾Ð±ÑекÑа
* @param {Object} obj
* @return {Object}
*/
function copyObj(obj) {
var result = {};
for (var p in obj)
if (obj.hasOwnProperty(p))
result[p] = obj[p];
return result;
}
\ No newline at end of file
diff --git a/test/draw-test.html b/test/draw-test.html
new file mode 100644
index 0000000..95561ee
--- /dev/null
+++ b/test/draw-test.html
@@ -0,0 +1 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" debug="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<style type="text/css">
.rounded {
padding:10px;
background:red;
white-space:nowrap;
zoom:1;
}
* html div.rounded {
height:20px;
}
span.rounded {
padding:3px 10px;
margin:-3px 0;
}
p{
line-height:1.5;
}
.some-class {
color: red;
}
h2 {
clear:both;
}
.wrap {
float:left;
padding:20px;
overflow:hidden;
margin:10px;
width:15%;
}
.bg-wrap {
background:url(../bg.jpg);
padding:10px;
overflow:hidden;
}
* html .bg-wrap {
float:left;
}
.with-border {
border:3px solid #000;
}
.b1{border:1px solid blue;}
.b2{border:2px solid blue;}
.b3{border:3px solid blue;}
.b4{border:4px solid blue;}
.b5{border:5px solid blue;}
.b6{border:6px solid blue;}
.b7{border:7px solid blue;}
.b8{border:8px solid blue;}
.b9{border:9px solid blue;}
.b10{border:10px solid blue;}
.b11{border:11px solid blue;}
.b12{border:12px solid blue;}
.b13{border:13px solid blue;}
.b14{border:14px solid blue;}
.b15{border:15px solid blue;}
.b16{border:16px solid blue;}
.b17{border:17px solid blue;}
.b18{border:18px solid blue;}
.b19{border:19px solid blue;}
.b20{border:20px solid blue;}
#borders .rounded {
background-image: url(../gradient.png);
background-repeat: repeat-x;
}
.rocon-init {
position:relative;
}
.rocon {
display:block;
position:absolute;
overflow:hidden;
background-repeat:no-repeat;
}
.rocon-tr {
background-position:top right;
}
.rocon-br {
background-position:bottom right;
}
.rocon .rocon-cn {
position:absolute;
}
.rocon-br .rocon-cn,
.rocon-tr .rocon-cn {
right:0;
}
</style>
<!-- <script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script> -->
<script type="text/javascript" src="../js_src/common.js"></script>
<!-- <script type="text/javascript" src="../js_src/ie.js"></script> -->
<script type="text/javascript" src="../js_src/canvas.js"></script>
<script type="text/javascript" src="../js_src/svg.js"></script>
<script type="text/javascript" src="../js_src/vml.js"></script>
<script type="text/javascript" src="../js_src/worker.js"></script>
<script type="text/javascript" src="../js_src/init.js"></script>
<script type="text/javascript">
var rocon = result;
</script>
</head>
<body>
<h2>ÐÑовеÑка ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ ÑоÑмÑ</h2>
<div class="bg-wrap">
<div class="wrap">
<div class="rounded rc10 b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
|
sergeche/rocon
|
ab755115dd8cee3289fd026a6a0755ff628bc314
|
Better corners drawing in IE
|
diff --git a/js_src/common.js b/js_src/common.js
index 2fc66a8..03c4d93 100644
--- a/js_src/common.js
+++ b/js_src/common.js
@@ -1,571 +1,531 @@
/*!
* Rocon: library that creates rounded corners
* @author Sergey Chikuyonok (serge.che@gmail.com)
* @link http://code.google.com/p/rocon/
*/
/**
* ÐбÑие меÑÐ¾Ð´Ñ Ð¸ ÑвойÑÑва Ð´Ð»Ñ rocon
* @author Sergey Chikuyonok (sc@design.ru)
* @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
* @include "worker.js"
*/
var re_rule = /\.rc(\d+)\b/,
re_class = /\brc(\d+(?:\-\d+){0,3})(\-.+?)?\b/,
re_shape_flag = /\brc-shape\b/,
/** ÐазовÑй клаÑÑ Ð´Ð»Ñ ÑоздаваемÑÑ
ÑлеменÑов */
base_class = 'rocon',
/** ÐÑеÑиÑк Ð´Ð»Ñ ÑоздаваемÑÑ
CSS-пÑавил */
rule_prefix = base_class + '__',
/** РезÑлÑÑаÑ, возвÑаÑаемÑй в обÑÐµÐºÑ <code>rocon</code> */
result = {
/**
* Ðобавление/обновление Ñголков Ð´Ð»Ñ Ð´Ð¸Ð½Ð°Ð¼Ð¸ÑеÑки ÑозданнÑÑ
ÑлеменÑов.
* ÐÐ¾Ð¶ÐµÑ Ð¿ÑинимаÑÑ Ð½ÐµÐ¾Ð³ÑаниÑенное колиÑеÑÑво ÑлеменÑов либо маÑÑивов
* ÑлеменÑов, Ñ ÐºÐ¾ÑоÑÑÑ
нÑжно обновиÑÑ Ñголки
*/
update: function(){},
process: function(context) {
processRoundedElements(context);
}
},
/** @type {CSSStyleSheet} ТаблиÑа ÑÑилей Ð´Ð»Ñ Ñголков */
corners_ss = null,
css_text = '',
/** СпиÑок ÑÑнкÑий, коÑоÑÑе нÑжно вÑполниÑÑ Ð¿Ñи загÑÑзке DOM-деÑева */
dom_ready_list = [],
/** ÐагÑÑзилÑÑ Ð»Ð¸ DOM? */
is_ready = false,
/** ÐÑивÑзано ли ÑобÑÑие, ожидаÑÑее загÑÑÐ·ÐºÑ DOM? */
readyBound = false,
userAgent = navigator.userAgent.toLowerCase(),
/** Тип и веÑÑÐ¸Ñ Ð±ÑаÑзеÑа полÑзоваÑелÑ. ÐзÑÑо Ñ jQuery */
browser = {
version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
safari: /webkit/.test( userAgent ),
opera: /opera/.test( userAgent ),
msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};
/**
* ÐÑполнÑÐµÑ Ð²Ñе ÑÑнкÑии, добавленнÑе на ÑобÑÑие onDomContentLoaded.
* ÐзÑÑо Ñ jQuery
*/
function fireReady() {
//Make sure that the DOM is not already loaded
if (!is_ready) {
// Remember that the DOM is ready
is_ready = true;
// If there are functions bound, to execute
if ( dom_ready_list.length ) {
walkArray(dom_ready_list, function(){
this.call(document);
}, true);
// Reset the list of functions
dom_ready_list = null;
}
}
}
/**
* ÐобавлÑÐµÑ ÑлÑÑаÑÐµÐ»Ñ Ð½Ð° ÑобÑÑие onDomContentLoaded
* @type {Function} fn СлÑÑаÑелÑ
*/
function addDomReady(fn) {
dom_ready_list.push(fn);
}
/**
* ÐÑовеÑка на наÑÑÑпление ÑобÑÑÐ¸Ñ onDomContentLoaded.
* ÐзÑÑо Ñ jQuery
*/
function bindReady(){
if ( readyBound ) return;
readyBound = true;
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
fireReady();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
fireReady();
}
});
// If IE and not an iframe
// continually check to see if the document is ready
if ( document.documentElement.doScroll && !window.frameElement ) (function(){
if ( is_ready ) return;
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch( error ) {
setTimeout( arguments.callee, 0 );
return;
}
// and execute any waiting functions
fireReady();
})();
}
}
/**
* ÐÑпомогаÑелÑÐ½Ð°Ñ ÑÑнкÑиÑ, коÑоÑÐ°Ñ Ð¿ÑобегаеÑÑÑ Ð¿Ð¾ вÑем ÑлеменÑам маÑÑива
* <code>ar</code> и вÑполнÑÐµÑ Ð½Ð° каждом ÑлеменÑе его ÑлеменÑе ÑÑнкÑиÑ
* <code>fn</code>. <code>this</code> внÑÑÑи ÑÑой ÑÑнкÑии ÑказÑÐ²Ð°ÐµÑ Ð½Ð°
* ÑÐ»ÐµÐ¼ÐµÐ½Ñ Ð¼Ð°ÑÑива
* @param {Array} ar ÐаÑÑив, по коÑоÑÐ¾Ð¼Ñ Ð½Ñжно пÑобежаÑÑÑÑ
* @param {Function} fn ФÑнкÑиÑ, коÑоÑÑÑ Ð½Ñжно вÑполниÑÑ Ð½Ð° каждом ÑлеменÑе маÑÑива
* @param {Boolean} forward ÐеÑебиÑаÑÑ Ð·Ð½Ð°ÑÐµÐ½Ð¸Ñ Ð¾Ñ Ð½Ð°Ñала маÑÑива (п ÑмолÑаниÑ: Ñ ÐºÐ¾Ð½Ñа)
*/
function walkArray(ar, fn, forward) {
if (forward) {
for (var i = 0, len = ar.length; i < len; i++)
if (fn.call(ar[i], i, ar[i]) === false)
break;
} else {
for (var i = ar.length - 1; i >= 0; i--)
if (fn.call(ar[i], i, ar[i]) === false)
break;
}
}
/**
* ÐÑеобÑазÑÐµÑ Ð¾Ð´Ð¸Ð½ маÑÑив ÑлеменÑов в дÑÑгой Ñ Ð¿Ð¾Ð¼Ð¾ÑÑÑ ÑÑнкÑии callback.
* ÐзÑÑо в jQuery
* @param {Array} elems
* @param {Function} callback
* @return {Array}
*/
function mapArray(elems, callback) {
var ret = [];
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0, length = elems.length; i < length; i++ ) {
var value = callback( elems[ i ], i );
if ( value != null )
ret[ ret.length ] = value;
}
return ret.concat.apply( [], ret );
}
// TODO ÐобавиÑÑ Ð¸ÑклÑÑение пÑи пÑавилÑной ÑабоÑе border-radius
/**
* ÐÑеобÑазÑÐµÑ ÑÐ²ÐµÑ Ð¸Ð· RGB-пÑедÑÑÐ²Ð»ÐµÐ½Ð¸Ñ Ð² hex
* @param {String} color
* @return {String}
*/
function convertColorToHex(color) {
var result;
function s(num) {
var n = parseInt(num, 10).toString(16);
return (n.length == 1) ? n + n : n;
}
function p(num) {
return s(Math.round(num * 2.55));
}
if (result = /rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/.exec(color))
return '#' + s(result[1]) + s(result[2]) + s(result[3]);
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*\)/.exec(color))
return '#' + p(result[1]) + p(result[2]) + p(result[3]);
// Look for #a0b1c2
if (result = /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/i.exec(color))
return '#' + result[1] + result[2] + result[3];
if (result = /#([a-f0-9])([a-f0-9])([a-f0-9])/i.exec(color))
return '#' + result[1] + result[1] + result[2] + result[2] + result[3] + result[3];
s = null;
p = null;
return color;
}
/**
* Ð¡Ð¾Ð·Ð´Ð°ÐµÑ HTML-ÑÐ»ÐµÐ¼ÐµÐ½Ñ <code>name</code> Ñ ÐºÐ»Ð°ÑÑом <code>class_name</code>
* @param {String} name Ðазвание ÑлеменÑа
* @param {String} class_name ÐлаÑÑ ÑлеменÑа
* @return {Element}
*/
function createElement(name, class_name) {
var elem = document.createElement(name);
if (class_name) {
elem.className = class_name;
}
return elem;
}
/**
* ÐÑоÑÑÐ°Ñ Ð¿ÑовеÑка налиÑÐ¸Ñ Ð¾Ð¿Ñеделенного клаÑÑа Ñ ÑлеменÑа
* @param {HTMLElement} elem
* @param {String} class_name
* @return {Boolean}
*/
function hasClass(elem, class_name) {
var re = new RegExp('\\b' + class_name + '\\b');
return elem.nodeType == 1 && re.test(elem.className || '');
}
/**
* Add new class to the element
* @param {String} class_name New class
* @param {HTMLElement} elem Element to add class
*/
function addClass(class_name, elem) {
elem.className += ' ' + class_name;
}
var toCamelCase = (function(){
var cache = {},
camel = function(str, p1){return p1.toUpperCase();},
re = /\-(\w)/g;
return function(name) {
if (!cache[name])
cache[name] = name.replace(re, camel);
return cache[name];
}
})();
/**
* ÐозвÑаÑÐ°ÐµÑ Ð·Ð½Ð°Ñение CSS-ÑвойÑÑва <b>name</b> ÑлеменÑа <b>elem</b>
* @author John Resig (http://ejohn.org)
* @param {Element} elem ÐлеменÑ, Ñ ÐºÐ¾ÑоÑого нÑжно полÑÑиÑÑ Ð·Ð½Ð°Ñение CSS-ÑвойÑÑва
* @param {String|Array} name Ðазвание CSS-ÑвойÑÑва
* @return {String|Object}
*/
function getStyle(elem, name) {
var cs, result = {}, n, name_camel, is_array = name instanceof Array;
var _name = is_array ? name : [name];
for (var i = 0; i < _name.length; i++) {
n = _name[i];
name_camel = toCamelCase(n);
// If the property exists in style[], then it's been set
// recently (and is current)
if (elem.style[name_camel]) {
result[n] = result[name_camel] = elem.style[name_camel];
}
//Otherwise, try to use IE's method
else if (browser.msie) {
- result[name_camel] = elem.currentStyle[name_camel];
+ result[n] = result[name_camel] = elem.currentStyle[name_camel];
}
// Or the W3C's method, if it exists
else if (document.defaultView && document.defaultView.getComputedStyle) {
if (!cs)
cs = document.defaultView.getComputedStyle(elem, "");
result[n] = result[name_camel] = cs && cs.getPropertyValue(n);
}
}
// walkArray(name instanceof Array ? name : [name], function(i, n){
//
// });
return is_array ? result : result[toCamelCase(name)];
}
/**
* РазвоÑаÑÐ¸Ð²Ð°ÐµÑ ÐºÑаÑкÑÑ Ð·Ð°Ð¿Ð¸ÑÑ ÑеÑÑÑеÑ
знаÑного ÑвойÑÑва в полнÑÑ:<br>
* â a -> a,a,a,a<br>
* â a_b -> a,b,a,b<br>
* â a_b_Ñ -> a,b,Ñ,b<br>
*
* @param {String} prop ÐнаÑение, коÑоÑое нÑжно ÑаÑкÑÑÑÑ
* @return {Array} ÐаÑÑив Ñ 4 знаÑениÑми
*/
function expandProperty(prop) {
var chunks = (prop || '').split(/[\-_]+/);
switch (chunks.length) {
case 1:
return [chunks[0], chunks[0], chunks[0], chunks[0]];
case 2:
return [chunks[0], chunks[1], chunks[0], chunks[1]];
case 3:
return [chunks[0], chunks[1], chunks[2], chunks[1]];
case 4:
return chunks;
}
return null;
}
/**
* ÐозвÑаÑÐ°ÐµÑ ÑÐ²ÐµÑ Ñона ÑлеменÑа
* @type {Function}
* @param {Element} elem ÐлеменÑ, Ð´Ð»Ñ ÐºÐ¾ÑоÑого нÑжно доÑÑаÑÑ ÑÐ²ÐµÑ Ñона
* @return {String}
*/
var getBg = (function() {
var session_elems = [],
default_color = '#ffffff';
/**
* ÐÑновной Ñикл Ñ Ð¸ÑполÑзованием кÑÑиÑованиÑ
*/
function mainLoopCache(elem) {
var c;
do {
if (elem.nodeType != 1)
break;
if (elem.rocon_bg) { // ÑÐ²ÐµÑ Ð±Ñл найден Ñанее
return elem.rocon_bg;
} else { // ÑÐ²ÐµÑ ÐµÑе не найден
session_elems.push(elem);
c = getStyle(elem, 'background-color');
if (c != 'transparent')
return convertColorToHex(c);
}
} while (elem = elem.parentNode);
return default_color;
}
/**
* ÐÑновной Ñикл без кÑÑиÑованиÑ
*/
function mainLoopNoCache(elem) {
var c;
do {
if (elem.nodeType != 1)
break;
c = getStyle(elem, 'background-color');
if (c != 'transparent')
return convertColorToHex(c);
} while (elem = elem.parentNode);
return default_color;
}
return function(elem){
var cl = /* String */elem.className,
bg = null;
if (getBg.use_cache) {
session_elems = [];
bg = mainLoopCache(elem);
// закÑÑиÑÑем ÑÐ²ÐµÑ Ñона Ñ Ð²ÑеÑ
ÑлеменÑов, по коÑоÑÑм пÑоÑ
одилиÑÑ
walkArray(session_elems, function(){
this.rocon_bg = bg;
getBg.processed_elems.push(this);
});
session_elems = null;
} else {
bg = mainLoopNoCache(elem);
}
return bg;
- }
+ };
})();
getBg.use_cache = true;
getBg.processed_elems = [];
var css_rules_cache = [];
/**
* ÐобавлÑÐµÑ CSS-пÑавило в ÑÑилÑ
* @param {String} selector CSS-ÑелекÑоÑ, Ð´Ð»Ñ ÐºÐ¾ÑоÑого нÑжно добавиÑÑ Ð¿Ñавила
* @param {String} rules CSS-пÑавила
*/
-var addRule = (function(){
-
- return function(selector, rules){
- css_rules_cache[css_rules_cache.length] = selector + ' {' + rules + '}';
- }
-
-
- if (browser.msie)
- return function(selector, rules){ css_text += selector + '{' + rules + '}'; }
- else
- return function(selector, rules){ corners_ss.insertRule(selector + ' {' + rules + '}', corners_ss.cssRules.length); }
-})();
-
+function addRule(selector, rule) {
+ css_rules_cache.push([selector, rule]);
+}
/**
* Ð¡Ð¾Ð·Ð´Ð°ÐµÑ Ð½Ð¾Ð²ÑÑ ÑаблиÑÑ ÑÑилей на ÑÑÑаниÑе, кÑда бÑдÑÑ Ð´Ð¾Ð±Ð°Ð²Ð»ÑÑÑÑÑ Ð¿Ñавила
* Ð´Ð»Ñ Ð¾Ð¿Ð¸ÑÐ°Ð½Ð¸Ñ ÑкÑÑгленнÑÑ
Ñголков
* @return {CSSStyleSheet}
*/
function createStylesheet() {
if (!corners_ss) {
if (document.createStyleSheet) {
corners_ss = document.createStyleSheet();
} else {
var style = createElement('style');
- style.rel = 'rocon';
document.getElementsByTagName('head')[0].appendChild(style);
-
- /*
- * ÐÑоÑÑо полÑÑиÑÑ ÑамÑй поÑледний ÑÑÐ¸Ð»Ñ Ð½Ðµ полÑÑиÑÑÑ: иногда ÑÑили
- * добавлÑÑÑÑÑ Ð²Ð½ÑÑÑÑ <body> (Ñак Ð´ÐµÐ»Ð°ÐµÑ ÑÑеÑÑик ЯндекÑа, напÑимеÑ),
- * в ÑÑом ÑлÑÑае Ð¼Ñ Ð½Ðµ можем бÑÑÑ ÑвеÑенÑ, ÑÑо ÑолÑко ÑÑо
- * Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð½Ð°Ñ ÑаблиÑа ÑÑилей â поÑледнÑÑ. ÐоÑÑÐ¾Ð¼Ñ Ð¿ÑобегаеÑмÑÑ
- * по вÑем ÑаблиÑам в поиÑкаÑ
наÑей
- */
- walkArray(document.styleSheets, function(){
- if (this.ownerNode.rel == 'rocon') {
- corners_ss = this;
- return false;
- }
- });
+ corners_ss = style.sheet;
}
}
return corners_ss;
}
function applyCSS() {
if (css_rules_cache.length) {
- var style = createElement('style');
- document.getElementsByTagName('head')[0].appendChild(style);
-
- var sheet = style.sheet;
- document.body.style.display = 'none';
-
- for (var j = 0; j < css_rules_cache.length; j++) {
- sheet.insertRule(css_rules_cache[j], j);
+ var sheet = createStylesheet();
+ if (sheet.addRule) {
+ // msie way
+ for (var j = 0; j < css_rules_cache.length; j++) {
+ var r = css_rules_cache[j];
+ sheet.addRule(r[0], r[1]);
+ }
+ } else {
+ // W3C way
+ for (var j = 0; j < css_rules_cache.length; j++) {
+ var r = css_rules_cache[j];
+ sheet.insertRule(r[0] + '{' + r[1] + '}', j);
+ }
}
- document.body.style.display = '';
-
-
-// style.title = 'rocon';
-
-
-
-// console.dir(style);
-
-// var sheets = document.styleSheets;
-//
-// for (var i = sheets.length - 1; i >= 0; i--) {
-// var sheet = sheets[i];
-// if (sheet.title == 'rocon') {
-// for (var j = 0; j < css_rules_cache.length; j++) {
-// sheet.insertRule(css_rules_cache[j], j);
-// }
-// break;
-// }
-// }
-
+ css_rules_cache.length = 0;
}
- css_rules_cache = [];
}
/**
* ÐозвÑаÑÐ°ÐµÑ Ð¼Ð°ÑÑив ÑлеменÑов, коÑоÑÑм нÑжно добавиÑÑ ÑкÑÑгленнÑе Ñголки.
* ÐлеменÑом маÑÑива ÑвлÑеÑÑÑ Ð¾Ð±ÑÐµÐºÑ Ñо ÑвойÑÑвами <code>node</code>
* и <code>radius</code>
* @param {Element} [context] ÐÑкÑда бÑаÑÑ ÑлеменÑÑ
* @return {Array}
*/
function getElementsToProcess(context) {
var elems = [], m;
walkArray((context || document).getElementsByTagName('*'), function(){
if (m = re_class.exec(this.className || '')) {
var p = (m[2] || '');
elems.push({
node: this,
params: {
radius: expandProperty(m[1]),
shape: (p.indexOf('shape') != -1 ),
force: (p.indexOf('force') != -1 )
}
});
}
});
return elems;
}
/**
* ÐбÑабаÑÑÐ²Ð°ÐµÑ Ð²Ñе ÑлеменÑÑ Ð½Ð° ÑÑÑаниÑе, коÑоÑÑм нÑжно добавиÑÑ ÑкÑÑгленнÑе
* Ñголки
*/
function processRoundedElements(context){
createStylesheet();
var elems = getElementsToProcess(context);
if (elems.length) {
walkArray(elems, function(i, n){
worker.add(this.params, this.node);
});
worker.run();
}
}
/**
* ÐÑименÑÐµÑ Ñголки к ÑлеменÑам, пеÑеданнÑм в маÑÑиве. РоÑновном вÑзÑваеÑÑÑ Ð¸Ð·
* <code>rocon.update()</code>
* @param {arguments} args ÐÑгÑменÑÑ ÑÑнкÑии
* @param {Function} fn ФÑнкÑиÑ, коÑоÑÑÑ Ð½Ñжно вÑполниÑÑ Ð½Ð° каждом ÑлеменÑе
*/
function applyCornersToArgs(args, fn) {
walkArray(args, function(){
walkArray((this instanceof Array) ? this : [this], fn);
});
}
/**
* ÐÐµÐ»Ð°ÐµÑ ÐºÐ¾Ð¿Ð¸Ñ Ð¾Ð±ÑекÑа
* @param {Object} obj
* @return {Object}
*/
function copyObj(obj) {
var result = {};
for (var p in obj)
if (obj.hasOwnProperty(p))
result[p] = obj[p];
return result;
}
\ No newline at end of file
diff --git a/js_src/init.js b/js_src/init.js
index e762a5e..bb91b63 100644
--- a/js_src/init.js
+++ b/js_src/init.js
@@ -1,52 +1,52 @@
/**
* @author Sergey Chikuyonok (serge.che@gmail.com)
* @link http://chikuyonok.ru
* @include "common.js"
* @include "worker.js"
* @include "canvas.js"
* @include "vml.js"
*/
addDomReady(processRoundedElements);
// поÑле Ñого, как добавили Ñголки, необÑ
одимо оÑиÑÑиÑÑ ÐºÑÑ Ñона,
// инаÑе бÑдÑÑ Ð¿ÑÐ¾Ð±Ð»ÐµÐ¼Ñ Ñ Ð´Ð¸Ð½Ð°Ð¼Ð¸ÑеÑким обновлением блоков
addDomReady(function(){
walkArray(getBg.processed_elems, function(){
this.removeAttribute('rocon_bg');
});
getBg.use_cache = false;
});
// set browser-specific properties
if (browser.msie) {
worker.setAdapter(vml);
addDomReady(function(){
- corners_ss.cssText += css_text;
- css_text = '';
- addRule = corners_ss.addRule;
+// corners_ss.cssText += css_text;
+// css_text = '';
+// addRule = corners_ss.addRule;
});
} else {
worker.setAdapter(canvas);
//canvas.returnType(2);
if (browser.safari) {
- canvas.returnType(2);
+ canvas.returnType(1);
// worker.nativeProperties(
// '-webkit-border-top-left-radius',
// '-webkit-border-top-right-radius',
// '-webkit-border-bottom-right-radius',
// '-webkit-border-bottom-left-radius'
// );
} else if (browser.mozilla) {
// worker.nativeProperties(
// '-moz-border-radius-topleft',
// '-moz-border-radius-topright',
// '-moz-border-radius-bottomright',
// '-moz-border-radius-bottomleft'
// );
}
//else if (browser.opera)
// worker.setAdapter(svg);
}
bindReady();
\ No newline at end of file
diff --git a/js_src/vml.js b/js_src/vml.js
index 1e74131..a265f2d 100644
--- a/js_src/vml.js
+++ b/js_src/vml.js
@@ -1,198 +1,202 @@
/**
* VML adapter for drawing rounded corners
* @author Sergey Chikuyonok (serge.che@gmail.com)
* @link http://chikuyonok.ru
*
* @include "common.js"
*/
var vml = (function(){
// init VML (took from RaphaÑl lib)
var ns = 'rc_vml',
doc = document,
vml_ns = '',
common_style = 'position:absolute;display:inline-block;',
is_inited = false;
/** Stroke drawing raw string */
var stroke_path = '<' + ns + ':shape ' + vml_ns + ' class="' + ns + ' ' + ns + '_stroke" fillcolor="%top_color%" style="' + common_style + 'width:%width%px;height:%height%px;%offset%;%rotation%" stroked="false" coordsize="%c_width% %c_height%" coordorigin="5 5" ' +
'path="m0,%c_height% l0,%radius% qy%radius%,0 l%c_width%,0 r0,%top% l%radius%,%top% qx%left%,%radius% l%left%,%c_height% l0,%c_height% e x">' +
'<' + ns + ':fill ' + vml_ns + ' class="' + ns + '" color="%left_color%" color2="%top_color%" type="gradient" colors="%grd_start%% %grd_color_start%, %grd_end%% %grd_color_end%"/>' +
'</' + ns + ':shape>',
/** Fill drawing raw string */
fill_path = '<' + ns + ':shape ' + vml_ns + ' class="' + ns + '" fillcolor="%color%" stroked="false" style="' + common_style + 'width:%width%px;height:%height%px;%rotation%;%offset%" coordsize="%c_width% %c_height%" coordorigin="5 5" ' +
'path="m%offset_x%,%c_height% l%offset_x%,%radius% qy%radius%,%offset_y% l%c_width%,%offset_y% l%c_width%,0 %shape% l0,%c_height% e x"></' + ns + ':shape>',
/** All numeric properies of <code>params</code> object */
num_properties = ['top', 'left', 'radius', 'c_width', 'c_height'],
/** VML coordinate space multiplier for crispy edges of shapes */
multiplier = 10;
/**
* Replaces entities (like %entity%) in string with values passed in
* <code>params</code>: {entity1: value, entity2: value, ...}
* @param {String} str Raw string
* @param {Object} params Entity values
* @return {String} New string with replaced entities
*/
function replaceEntities(str, params) {
// merge objects
var _params = {};
for (var i = 1; i < arguments.length; i++) {
var obj = arguments[i];
if (obj)
for (var a in obj) if (obj.hasOwnProperty(a))
_params[a] = obj[a];
}
// replace entities
return str.replace(/\%(\w+)\%/g, function(s, p1){
return _params[p1];
});
}
/**
* Create border shape (stroke).
*
* @param {Number} params.radius Corner radius
* @param {Number} params.left Left border width, pixels
* @param {String} params.left_color Left border color
* @param {Number} params.top Top border width, pixels
* @param {String} params.top_color Top border color
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
*
* @return {String} String containing SVG tags
*/
function drawStroke(params) {
var extra_params = {
grd_start: (1 - params.top / params.radius) * 100,
grd_color_start: params.top_color,
grd_end: (1 - params.radius / params.height) * 100,
grd_color_end: params.left_color
};
if ((params.type || '').charAt(0) == 'b') {
// swap colors
var tmp_color = params.top_color;
params.top_color = params.left_color;
params.left_color = tmp_color;
extra_params.grd_start = 100 - extra_params.grd_start;
extra_params.grd_end = 100 - extra_params.grd_end;
}
return (params.top + params.left) ?
// replaceEntities(stroke_gradient, params, extra_params) +
replaceEntities(stroke_path, params, extra_params)
: '';
}
/**
* Draw background for corner image
*
* @param {Number} params.radius Corner radius
* @param {Number} params.left Left border width, pixels
* @param {Number} params.top Top border width, pixels
* @param {String} params.color Color of background
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
*/
function drawBackground(params) {
var t = {
shape: params.use_shape ? 'r0,' + params.c_height : 'l0,0'
};
return replaceEntities(fill_path, params, t);
}
/**
* Returns transformation params for different types of corners
* @param {String} Corner type: tl, tr, bl, br
* @param {Number} radius Corner radius
*/
function rotate(type, radius) {
switch (type) {
case 'tr': // top right corner
return 'flip:x;margin-left:-1px;';
case 'bl': // bottom left corner
return 'flip:y;margin-top:-1px';
case 'br': // bottom right corner
return 'rotation:180;margin-left:-1px;margin-top:-1px;';
default:
return '';
}
}
return {
init: function() {
if (!is_inited) {
doc.createStyleSheet().addRule("." + ns, "behavior:url(#default#VML)");
try {
!doc.namespaces[ns] && doc.namespaces.add(ns, "urn:schemas-microsoft-com:vml");
} catch (e) {
vml_ns = 'xmlns="urn:schemas-microsoft.com:vml"';
}
}
is_inited = true;
},
/**
* Draw rounded corner
*
* @param {Number} params.radius Corner radius
* @param {Number} params.left Left border width, pixels
* @param {String} params.left_color Left border color
* @param {Number} params.top Top border width, pixels
* @param {String} params.top_color Top border color
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
* @param {String} params.color Color of background
* @param {String} params.type Corner type: tl, tr, bl, br
*
* @return {String} Image in data:URL format
*/
draw: function(params) {
params = copyObj(params);
params.width = params.c_width = params.width || params.radius;
params.height = params.c_height = params.height || params.radius;
params.offset = '';
if (params.type.charAt(0) == 'b')
params.offset += 'top: 0px;';
+
if (params.type.charAt(1) == 'r')
params.offset += 'left: 0px;';
+ else if (params.use_shape) {
+ params.offset += 'left: ' + (params.radius - params.left - params.opposite.left) + 'px;';
+ }
+
params.offset_x = (!params.use_shape && params.left) ? 0.5 * multiplier : 0;
params.offset_y = (!params.use_shape && params.top) ? 0.5 * multiplier : 0;
params.rotation = rotate(params.type);
// multiply all numeric values
walkArray(num_properties, function(i, n){
params[n] *= multiplier;
});
var data = /* '<v:group class="vml" ' + replaceEntities(group_data, params) + '>' + */
drawBackground(params) +
drawStroke(params) +
/* '</v:group>' */
'';
// if (params.type == 'tl')
// alert(data);
// var elem = createElement('div', 'rocon-cn');
// elem.innerHTML = data;
return data;
},
returnType: function() {
return 2;
}
- }
-
+ };
})();
\ No newline at end of file
diff --git a/js_src/worker.js b/js_src/worker.js
index b72653d..2e0d994 100644
--- a/js_src/worker.js
+++ b/js_src/worker.js
@@ -1,528 +1,533 @@
/**
* Main worker and caching mechanism used for storing and applying of drawn
* corners to the elements
*
* @author Sergey Chikuyonok (serge.che@gmail.com)
* @link http://chikuyonok.ru
* @include "common.js"
* @include "canvas.js"
*/
var worker = (function(){
/** @type {canvas} Drawing adapter (canvas, SVG, VML) */
var adapter = null,
/** Cached corners */
cache = {},
/** Number of keys in cache */
key_count = 0,
/** Native browser properties used to draw browser corners */
native_props = [],
queue = [],
/** Corner type index in array */
type_pos = {tl: 0, tr: 1, br: 2, bl: 3},
/** CSS properties for corner types */
corner_type_map = {
tl: {
left: 'border-left-width',
left_color: 'border-left-color',
top: 'border-top-width',
top_color: 'border-top-color'
},
tr: {
left: 'border-right-width',
left_color: 'border-right-color',
top: 'border-top-width',
top_color: 'border-top-color'
},
br: {
left: 'border-right-width',
left_color: 'border-right-color',
top: 'border-bottom-width',
top_color: 'border-bottom-color'
},
bl: {
left: 'border-left-width',
left_color: 'border-left-color',
top: 'border-bottom-width',
top_color: 'border-bottom-color'
}
},
opposite_corners = {
tl: 'tr',
tr: 'tl',
bl: 'br',
br: 'bl'
},
css_props = [];
//fill-up CSS properties
walkArray(['left', 'top', 'right', 'bottom'], function(i, n){
var prefix = 'border-' + n;
css_props.push(prefix + '-color', prefix + '-width');
});
/**
* Check if we need to add extra width for image (for shape-type corners)
* @param {Object} params
* @param {String} params
* @return {Boolean}
*/
function needExtraWidth(params, type) {
- return params.shape && (type || 'tl').charAt(1) == 'r';
+ return params.shape && (type || 'tl').charAt(1) == 'l';
}
/**
* Returns the smallest numbers
* @return {Number}
*/
function min() {
var args = mapArray(arguments, function(n, i){
return parseInt(n) || 0;
});
if (args.length == 2) {
return args[0] < args[1] ? args[0] : args[1];
} else {
var result = args[0];
for (var i = 1; i < args.length; i++) {
if (args[i] < result)
result = args[i];
}
return result;
}
}
/**
* Returns the highest numbers
* @return {Number}
*/
function max() {
var args = mapArray(arguments, function(n, i){
return parseInt(n) || 0;
});
if (args.length == 2)
return args[0] > args[1] ? args[0] : args[1];
else {
var result = args[0];
for (var i = 1; i < args.length; i++) {
if (args[i] > result)
result = args[i];
}
return result;
}
}
/**
* Returns key used to store image data
* @param {Array|Object} params Corner parameters
* @return {String}
*/
function cacheKey(params) {
var result = [];
if (params instanceof Array)
for (var i = 0; i < params.length; i++)
result.push(params[i]);
else
for (var a in params) if (params.hasOwnProperty(a))
result.push(a + ':' + params[a]);
return result.join(';');
}
/**
* Add value to cache
* @param {String} key Cache key
* @param {String} [value] Cache value. If not set, internal class name will be used
* @return {String} Internal class name
*/
function addToCache(key, value) {
if (getCachedValue(key))
return getCachedValue(key);
key_count++;
cache[key] = value || rule_prefix + key_count;
return rule_prefix + key_count;
}
/**
* Returns cached value
* @param {String} key cache key
* @return {String|null}
*/
function getCachedValue(key) {
return cache[key];
}
/**
* Add native CSS corners to the element
* @param {Array} radius Set of border radius values
* @param {HTMLElement} elem Element to add corners
*/
function addNativeCorners(radius, elem) {
var key = cacheKey(radius),
css_class = getCachedValue(key),
css_rules = '';
if (!css_class) {
css_class = addToCache(key);
walkArray(native_props, function(i, n){
css_rules += n + ':' + radius[i] + 'px;';
});
addRule('.' + css_class, css_rules);
}
addClass(css_class, elem);
}
/**
* Creates, if necessary, new corner elements and returns them
* @param {HTMLElement} elem Container element
* @return {Object}
*/
function createCornerElements(elem) {
var result = {},
found = 0,
re = new RegExp('\\b' + base_class + '-([tblr]{2})\\b', 'i'),
m;
walkArray(elem.childNodes, function(i, /* HTMLElement */ n){
if (m = re.exec(n.className)) {
found++;
result[m[1]] = n;
}
});
if (!found) {
walkArray(['tl', 'tr', 'bl', 'br'], function(i, n) {
var e = createElement('span', base_class + ' ' + base_class +'-' + n);
elem.appendChild(e);
result[n] = e;
});
}
return result;
}
/**
* Add element to drawing queue
* @param {Object} params Parent element params
* @param {HTMLElement} parent Parent element
* @param {Object} corners Corner elements
*/
function addToQueue(params, parent, corners) {
queue.push([params, parent, corners]);
}
/**
* Removes old internal classes from element
* @param {HTMLElement} elem
* @param {String} new_class New class name to add (optional)
* @return {HTMLElement}
*/
function cleanUp(elem, new_class) {
elem.className = elem.className.replace(/\s*rocon__\d+/, '');
if (new_class)
elem.className += ' ' + new_class;
return elem;
}
/**
* Returns width that must be set for specified corner type
* @param {Object} params Corner's container element params
* @param {String} type Corner type (tl, tr, bl, br)
* @return {Number}
*/
function getCornerWidth(params, type) {
return needExtraWidth(params, type) ? 2000 : params.radius[type_pos[type]];
}
/**
* Returns height that must be set for specified corner type
* @param {Object} params Corner's container element params
* @param {String} type Corner type (tl, tr, bl, br)
* @return {Number}
*/
function getCornerHeight(params, type) {
var cur_pos = type_pos[type],
op_pos = type_pos[ opposite_corners[type] ];
return Math.max(params.radius[cur_pos], params.radius[op_pos]);
}
/**
* Draw corners using adapter
* @param {Object} params Parent element params
* @param {HTMLElement} parent Parent element
* @param {HTMLElement[]} corners Corner elements
* @param {Object} style Cached CSS properties
*/
function drawCorners(params, parent, corners, style) {
// gather all params for all corners
var all_params = {}, css_map, elem, style;
- for (var corner_type in corners) {
+ for (var corner_type in corners) if (corners.hasOwnProperty(corner_type)) {
css_map = corner_type_map[corner_type];
/** @type {HTMLElement} */
elem = corners[corner_type];
style = style || getStyle(parent, css_props);
// debugger;
// gather params for current corner
var r = parseInt(params.radius[ type_pos[corner_type] ]);
all_params[corner_type] = {
radius: r,
top: min(style[css_map.top], r),
real_top: parseInt(style[css_map.top]) || 0,
top_color: convertColorToHex(style[css_map.top_color]),
left: min(style[css_map.left], r),
real_left: parseInt(style[css_map.left]) || 0,
left_color: convertColorToHex(style[css_map.left_color]),
color: getBg(params.shape ? parent : parent.parentNode),
use_shape: params.shape,
type: corner_type,
width: max(getCornerWidth(params, corner_type), parseInt(style[css_map.left]) || 0),
height: getCornerHeight(params, corner_type)
};
}
// create corners
for (var corner_type in corners) {
/** @type {HTMLElement} */
elem = corners[corner_type];
var cparams = all_params[corner_type];
// calculate X and Y offsets
cparams.offset_x = -cparams.real_left;
cparams.offset_y = -(params.shape ? max(cparams.height, cparams.radius, cparams.real_top) : cparams.real_top);
var op_corner = opposite_corners[corner_type],
key = cacheKey(cparams);
+ cparams.opposite = all_params[op_corner];
+
if (needExtraWidth(params, corner_type)) {
//add extra properties for cache key
key += '--' + (cparams.left + all_params[op_corner].left) +
':' + params.radius[ type_pos[op_corner] ];
}
var css_class = getCachedValue(key);
if (!css_class) {
// image is not yet created
css_class = addToCache(key);
var css_rules = 'height:' + cparams.height + 'px;';
- if (adapter.returnType() != 2)
+ if (adapter.returnType() != 2) // adapter draws image in data:url format
css_rules += 'background-image:url(' + adapter.draw(cparams) + ');';
+ var offset_top = -(params.shape ? Math.max(cparams.height, cparams.radius) : cparams.top);
+
+ css_rules += ( corner_type.charAt(0) == 't' ? 'top:' : 'bottom:' ) + cparams.offset_y + 'px;';
+ css_rules += ( corner_type.charAt(1) == 'l' ? 'left:' : 'right:' ) + cparams.offset_x + 'px;';
if (needExtraWidth(params, corner_type)) {
css_rules += 'width:100%;' +
- 'padding-left:' + (cparams.real_left + all_params[op_corner].left) + 'px;' +
- 'clip:rect(auto,auto,auto,' + params.radius[ type_pos[op_corner] ] + 'px);' +
- 'background-position:top right;';
+ 'background-position:' + (cparams.radius - cparams.left - cparams.opposite.left) + 'px 0px;' +
+ 'left:' + (-cparams.radius + cparams.opposite.left) + 'px;';
+// css_rules += 'width:100%;' +
+// 'padding-left:' + (cparams.real_left + all_params[op_corner].left) + 'px;' +
+// 'clip:rect(auto,auto,auto,' + params.radius[ type_pos[op_corner] ] + 'px);' +
+// 'background-position:top right;';
} else {
css_rules += 'width:' + cparams.width + 'px;';
}
- var offset_top = -(params.shape ? Math.max(cparams.height, cparams.radius) : cparams.top);
-
- css_rules += ( corner_type.charAt(0) == 't' ? 'top:' : 'bottom:' ) + cparams.offset_y + 'px;';
- css_rules += ( corner_type.charAt(1) == 'l' ? 'left:' : 'right:' ) + cparams.offset_x + 'px;';
addRule('.' + css_class, css_rules);
}
cleanUp(elem, css_class);
if (adapter.returnType() == 2) {
var corner = adapter.draw(cparams);
if (typeof(corner) == 'string') {
- elem.innerHTML = adapter.draw(cparams);
+ elem.innerHTML = corner;
} else {
elem.innerHTML = '';
- elem.appendChild(adapter.draw(cparams));
+ elem.appendChild(corner);
}
}
}
cleanUp(parent);
if (!hasClass(parent, 'rocon-init'))
addClass('rocon-init', parent);
if (params.shape)
adjustBox(params, parent);
}
/**
* Add corners drawn by <code>adapter</code> to the element
* @param {Array} params.radius Array of radius values
* @param {Boolean} params.shape Use shape instead of counter-shape
* @param {HTMLElement} elem Element to apply corners
* @param {Boolean} [is_immediate] Draw corners immediately instead adding element to the queue (may cause performance issues in Opera)
*/
function addAdapterCorners(params, elem, is_immediate) {
/*
* Due to stupid Opera bug (http://chikuyonok.ru/playground/opera-bug/)
* we need to split this single process into two loops:
* 1. Add corner elements to the container
* 2. Draw images and apply them to the corners
*/
var corners = createCornerElements(elem);
if (is_immediate)
drawCorners(params, elem, corners);
else
addToQueue(params, elem, corners);
}
/**
* Main processing function
* @param {Array} params.radius Array of radius values
* @param {Boolean} params.shape Use shape instead of counter-shape
* @param {Boolean} params.force {Boolean} Force usage of drawing adapter instead of native properties
* @param {HTMLElement} elem Element to apply corners
* @param {Boolean} [is_immediate] Draw corners immediately instead adding element to the queue (may cause performance issues in Opera)
*/
function process(params, elem, is_immediate) {
if (native_props.length && !params.force) {
addNativeCorners(params.radius, elem);
} else {
addAdapterCorners(params, elem, is_immediate);
}
}
/**
* ÐоÑÑекÑиÑÑÐµÑ CSS-ÑвойÑÑва ÑлеменÑа Ð´Ð»Ñ Ð¿ÑавилÑного ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ Ñголков в виде
* ÑоÑмÑ
* @param {Object} params Corner params
* @param {HTMLElement} elem ÐлеменÑ, коÑоÑÑй нÑжно подкоÑÑекÑиÑоваÑÑ
*/
function adjustBox(params, elem) {
var pt = 'padding-top',
pb = 'padding-bottom',
mt = 'margin-top',
mb = 'margin-bottom',
btw = 'border-top-width',
bbw = 'border-bottom-width',
getProp = function(prop) {
return parseInt(elem_styles[prop], 10) || 0;
},
addCSSRule = function(property, value) {
return property + ':' + value + 'px !important;';
},
elem_styles = getStyle(elem, [pt, pb, mt, mb, btw, bbw]),
offset_top = Math.max(params.radius[ type_pos['tl'] ], params.radius[ type_pos['tr'] ]),
offset_bottom = Math.max(params.radius[ type_pos['bl'] ], params.radius[ type_pos['br'] ]),
offset_border_top = Math.min(offset_top, getProp(btw)),
offset_border_bottom = Math.min(offset_bottom, getProp(bbw));
/*
* ÐÑполÑзÑем ÑоÑмÑ, поÑÑÐ¾Ð¼Ñ Ñ Ð±Ð»Ð¾ÐºÐ° Ñнижаем веÑÑ
ние и нижние
* боÑдÑÑÑ, а Ñакже на велиÑÐ¸Ð½Ñ ÑадиÑÑа Ñнижаем веÑÑ
ний
* и нижний паддинг
*/
var padding_top = Math.max(getProp(pt) - offset_top + offset_border_top, 0),
padding_bottom = Math.max(getProp(pb) - offset_bottom + offset_border_bottom, 0),
margin_top = getProp(mt) + offset_top,
margin_bottom = getProp(mb) + offset_bottom,
border_top_width = getProp(btw) - offset_border_top,
border_bottom_width = getProp(bbw) - offset_border_bottom,
key = cacheKey([padding_top, padding_bottom, margin_top, margin_bottom, border_top_width, border_bottom_width]),
class_name = getCachedValue(key);
if (!class_name) {
class_name = addToCache(key);
addRule('.' + class_name,
addCSSRule(btw, border_top_width) +
addCSSRule(bbw, border_bottom_width) +
addCSSRule(pt, padding_top) +
addCSSRule(pb, padding_bottom) +
addCSSRule(mt, margin_top) +
addCSSRule(mb, margin_bottom));
}
elem.className += ' ' + class_name;
}
return {
/**
* Set drawing adapter
*/
setAdapter: function(obj) {
adapter = obj;
if ('init' in adapter)
adapter.init();
},
/**
* Set native CSS properties for drawing rounded borders
* @param {String} tl Top-left corner
* @param {String} tr Top-right corner
* @param {String} br Bottom-right corner
* @param {String} bl Bottom-left corner
*/
nativeProperties: function(tl, tr, br, bl) {
native_props = [tl, tr, br, bl];
},
/**
* Enqueue element for corners addition
* @param {Array} params.radius Array of radius values
* @param {Boolean} params.shape Use shape instead of counter-shape
* @param {Boolean} params.force {Boolean} Force usage of drawing adapter instead of native properties
* @param {HTMLElement} elem Element to apply corners
*/
add: function(params, elem) {
process(params, elem);
},
/**
* Add corners to enqueued elements
*/
run: function() {
var start = (new Date).getTime();
walkArray(queue, function(i, n){
drawCorners(n[0], n[1], n[2]);
});
var stop1 = (new Date).getTime();
applyCSS();
var stop2 = (new Date).getTime();
- alert('Draw: ' + (stop1 - start) + ' ms, CSS: ' + (stop2 - stop1) + ' ms');
+// alert('Draw: ' + (stop1 - start) + ' ms, CSS: ' + (stop2 - stop1) + ' ms');
},
/**
* Add corners to the element
*/
apply: function(params, elem) {
process(params, elem, true);
}
}
})();
\ No newline at end of file
diff --git a/test/speed-test.html b/test/speed-test.html
index dc24aec..a110f5e 100644
--- a/test/speed-test.html
+++ b/test/speed-test.html
@@ -1 +1 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" debug="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<style type="text/css">
.rounded {
padding:10px;
background:red;
white-space:nowrap;
zoom:1;
}
* html div.rounded {
height:20px;
}
span.rounded {
padding:3px 10px;
margin:-3px 0;
}
p{
line-height:1.5;
}
.some-class {
color: red;
}
h2 {
clear:both;
}
.wrap {
float:left;
padding:20px;
overflow:hidden;
margin:10px;
width:15%;
}
.bg-wrap {
background:url(../bg.jpg);
padding:10px;
overflow:hidden;
}
* html .bg-wrap {
float:left;
}
.with-border {
border:3px solid #000;
}
.b1{border:1px solid blue;}
.b2{border:2px solid blue;}
.b3{border:3px solid blue;}
.b4{border:4px solid blue;}
.b5{border:5px solid blue;}
.b6{border:6px solid blue;}
.b7{border:7px solid blue;}
.b8{border:8px solid blue;}
.b9{border:9px solid blue;}
.b10{border:10px solid blue;}
.b11{border:11px solid blue;}
.b12{border:12px solid blue;}
.b13{border:13px solid blue;}
.b14{border:14px solid blue;}
.b15{border:15px solid blue;}
.b16{border:16px solid blue;}
.b17{border:17px solid blue;}
.b18{border:18px solid blue;}
.b19{border:19px solid blue;}
.b20{border:20px solid blue;}
#borders .rounded {
background-image: url(../gradient.png);
background-repeat: repeat-x;
}
.rocon-init {
position:relative;
}
.rocon {
display:block;
position:absolute;
overflow:hidden;
}
.rocon-tr {
background-position:top right;
}
.rocon-br {
background-position:bottom right;
}
.rocon .rocon-cn {
position:absolute;
}
.rocon-br .rocon-cn,
.rocon-tr .rocon-cn {
right:0;
}
</style>
<!-- <script type="text/javascript" src="../js_src/firebug.js"></script> -->
<script type="text/javascript" src="../js_src/common.js"></script>
<script type="text/javascript" src="../js_src/canvas.js"></script>
<script type="text/javascript" src="../js_src/svg.js"></script>
<script type="text/javascript" src="../js_src/vml.js"></script>
<script type="text/javascript" src="../js_src/worker.js"></script>
<script type="text/javascript" src="../js_src/init.js"></script>
<script type="text/javascript">
var rocon = result;
</script>
</head>
<body>
<h2>ÐÑовеÑка ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ ÑоÑмÑ</h2>
<div class="bg-wrap">
<div class="wrap">
<div class="rounded rc10-shape">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" debug="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<style type="text/css">
.rounded {
padding:10px;
background:red;
white-space:nowrap;
zoom:1;
}
* html div.rounded {
height:20px;
}
span.rounded {
padding:3px 10px;
margin:-3px 0;
}
p{
line-height:1.5;
}
.some-class {
color: red;
}
h2 {
clear:both;
}
.wrap {
float:left;
padding:20px;
overflow:hidden;
margin:10px;
width:15%;
}
.bg-wrap {
background:url(../bg.jpg);
padding:10px;
overflow:hidden;
}
* html .bg-wrap {
float:left;
}
.with-border {
border:3px solid #000;
}
.b1{border:1px solid blue;}
.b2{border:2px solid blue;}
.b3{border:3px solid blue;}
.b4{border:4px solid blue;}
.b5{border:5px solid blue;}
.b6{border:6px solid blue;}
.b7{border:7px solid blue;}
.b8{border:8px solid blue;}
.b9{border:9px solid blue;}
.b10{border:10px solid blue;}
.b11{border:11px solid blue;}
.b12{border:12px solid blue;}
.b13{border:13px solid blue;}
.b14{border:14px solid blue;}
.b15{border:15px solid blue;}
.b16{border:16px solid blue;}
.b17{border:17px solid blue;}
.b18{border:18px solid blue;}
.b19{border:19px solid blue;}
.b20{border:20px solid blue;}
#borders .rounded {
background-image: url(../gradient.png);
background-repeat: repeat-x;
}
.rocon-init {
position:relative;
}
.rocon {
display:block;
position:absolute;
overflow:hidden;
}
.rocon-tr {
background-position:top right;
}
.rocon-br {
background-position:bottom right;
}
.rocon .rocon-cn {
position:absolute;
}
.rocon-br .rocon-cn,
.rocon-tr .rocon-cn {
right:0;
}
</style>
<!-- <script type="text/javascript" src="../js_src/firebug.js"></script> -->
<script type="text/javascript" src="../js_src/common.js"></script>
<!-- <script type="text/javascript" src="../js_src/ie.js"></script> -->
<script type="text/javascript" src="../js_src/canvas.js"></script>
<script type="text/javascript" src="../js_src/svg.js"></script>
<script type="text/javascript" src="../js_src/vml.js"></script>
<script type="text/javascript" src="../js_src/worker.js"></script>
<script type="text/javascript" src="../js_src/init.js"></script>
<script type="text/javascript">
var rocon = result;
</script>
</head>
<body>
<h2>ÐÑовеÑка ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ ÑоÑмÑ</h2>
<div class="bg-wrap">
<div class="wrap">
<div class="rounded rc10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10 b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b1">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b2">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b3">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b4">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b5">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b6">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b7">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b8">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b9">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b10">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b11">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b12">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b13">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b14">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b15">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b16">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b17">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b18">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b19">hello world</div>
</div>
<div class="wrap">
<div class="rounded rc10-shape b20">hello world</div>
</div>
</div>
</body>
</html>
\ No newline at end of file
|
sergeche/rocon
|
16dcd092e61e9eccccac07d1aa5cecd9e6844d1e
|
Changed code layout
|
diff --git a/js_src/ie copy.js b/js_src/ie copy.js
deleted file mode 100644
index 3f316ec..0000000
--- a/js_src/ie copy.js
+++ /dev/null
@@ -1,241 +0,0 @@
-/**
- * Ðобавление Ñголков Ð´Ð»Ñ IE
- * @author Sergey Chikuyonok (sc@design.ru)
- * @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
- * @include "common.js"
- */
-
-if (browser.msie) {
- // Ñголки Ð´Ð»Ñ IE Ñоздаем ÑеÑез VML
- _corner_cache.ix = 0;
- _corner_cache.created = {};
-
- var vml_class = 'vml-' + base_class; //иÑполÑзÑÑ Ð¸Ð¼ÐµÐ½Ð½Ð¾ клаÑÑ, ÑÑÐ¾Ð±Ñ ÑабоÑало в IE8
-
- try {
- if (!document.namespaces["v"])
- document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
- } catch(e) { }
-
- createStylesheet();
- var dot_class = '.' + base_class;
- corners_ss.cssText = "." + vml_class + " {behavior:url(#default#VML);display:inline-block;position:absolute}" +
- dot_class + "-init {position:relative;zoom:1;}" +
- dot_class + " {position:absolute; display:inline-block; zoom: 1; overflow:hidden}" +
- dot_class + "-tl ." + vml_class + "{flip: 'y'}" +
- dot_class + "-tr ." + vml_class + "{rotation: 180;right:1px;}" +
- dot_class + "-br ." + vml_class + "{flip: 'x'; right:1px;}";
-
- if (browser.version < 7) {
- corners_ss.cssText += dot_class + '-tr, ' + dot_class + '-br {margin-left: 100%;}';
-// dot_class + ' .' + vml_class + '{position:absolute}' +
-// dot_class + '-tr .' + vml_class + '{right: 0}';
- }
-
- addRule = function(selector, rules){
- corners_ss.cssText += selector + '{' + rules + '}';
- };
-
- /**
- * Ð¡Ð¾Ð·Ð´Ð°ÐµÑ ÑÐ»ÐµÐ¼ÐµÐ½Ñ Ñо ÑкÑÑгленнÑм Ñголком. Ð ÑÑнкÑии иÑполÑзÑеÑÑÑ
- * кÑÑиÑование, Ñо еÑÑÑ Ñанее ÑозданнÑй Ñголок дÑблиÑÑеÑÑÑ,
- * а не ÑоздаеÑÑÑ Ð·Ð°Ð½Ð¾Ð²Ð¾
- * @param {getCornerParams()} options ÐаÑамеÑÑÑ ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ Ñголка
- * @return {HTMLElement}
- */
- function createCornerElementIE(options) {
- var radius = options.radius,
- border_width = options.border_width,
- cache_key = radius + ':' + border_width + ':' + options.use_shape;
-
- if (!createCornerElementIE._cache[cache_key]) { // ÑÐ»ÐµÐ¼ÐµÐ½Ñ ÐµÑе не Ñоздан
-
- var multiplier = 10;
-
- var cv = createElement('v:shape');
- cv.className = vml_class;
- cv.strokeweight = border_width + 'px';
- cv.stroked = (border_width) ? true : false;
- var stroke = createElement('v:stroke');
- stroke.className = vml_class;
- stroke.joinstyle = 'miter';
- cv.appendChild(stroke);
-
- var w = radius, h = w;
-
- cv.style.width = w + 'px';
- cv.style.height = h + 'px';
-
- radius -= border_width / 2;
- radius *= multiplier;
- var bo = border_width / 2 * multiplier;
- var px = Math.round((radius + bo) / w);
- var rbo = radius + bo;
-
- cv.coordorigin = Math.round(px / 2) + ' ' + Math.round(px / 2);
- cv.coordsize = rbo + ' ' + rbo;
-
- var path = '';
- var max_width = rbo + px;
-
- if (options.use_shape) {
- max_width = 2000 * multiplier;
- path = 'm' + max_width + ',0 ns l' + bo +',0 qy' + rbo + ',' + radius + ' l' + max_width + ',' + radius + ' e ';
- } else {
- path = 'm0,0 ns l' + bo +',0 qy' + rbo + ',' + radius + ' l' + rbo + ',' + rbo + ' l0,' + rbo + ' e ';
- }
-
-
- // stroke
- path += 'm' + bo + ',' + (-px) + ' nf l' + bo + ',0 qy' + rbo + ',' + radius + ' l ' + (max_width) +','+ radius +' e x';
-
- cv.path = path;
-
- createCornerElementIE._cache[cache_key] = cv;
- }
-
- return createCornerElementIE._cache[cache_key].cloneNode(true);
- }
-
- createCornerElementIE._cache = {};
-
- /**
- * Ð¡Ð¾Ð·Ð´Ð°ÐµÑ ÑкÑÑгленнÑй Ñголок
- * @param {getCornerParams()} cparams паÑамеÑÑÑ Ñголка
- * @param {String} type Тип Ñголка (tl, tr, bl, br)
- */
- function drawCornerIE(cparams, type){
- var cv = createCornerElementIE(cparams);
- cv.fillcolor = cparams.bg_color || '#000';
- cv.strokecolor = cparams.border_color || '#000';
-
- var elem = createElement('span', base_class + ' ' + base_class + '-' + type);
- elem.appendChild(cv);
-
- return elem;
- }
-
- /**
- * УдалÑÐµÑ Ñ ÑлеменÑа ÑÑаÑÑе Ñголки
- * @param {HTMLElement} elem ÐлеменÑ, Ñ ÐºÐ¾ÑоÑого нÑжно ÑдалиÑÑ Ñголки
- */
- function removeOldCorners(elem) {
- walkArray(elem.childNodes, function(){
- if (hasClass(this, base_class)) {
- elem.removeChild(this);
- }
- });
-
- cleanUp(elem);
- }
-
- /**
- * ÐозвÑаÑÐ°ÐµÑ Ð¸Ð¼Ñ ÐºÐ»Ð°ÑÑа Ð´Ð»Ñ Ð¿ÐµÑеданнÑÑ
паÑамеÑÑов. ÐÑполÑзÑеÑÑÑ Ð´Ð»Ñ
- * Ñого, ÑÑÐ¾Ð±Ñ Ð½Ðµ плодиÑÑ Ð¼Ð½Ð¾Ð³Ð¾ ÑазнÑÑ
клаÑÑов Ð´Ð»Ñ Ð¾Ð´Ð½Ð¸Ñ
и ÑеÑ
же пÑавил
- * @param {getCornerParams()} options ÐаÑамеÑÑÑ ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ Ñголка
- * @return {String}
- */
- function getClassName(options) {
- var key = options.radius + ':' + (options.real_border_width || 0) + ':' + options.use_shape;
- if (!_corner_cache[key]) {
- _corner_cache[key] = rule_prefix + _corner_cache.ix++;
- }
-
- return _corner_cache[key];
- }
-
- /**
- * Ð¡Ð¾Ð·Ð´Ð°ÐµÑ CSS-пÑавила Ð´Ð»Ñ ÑкÑÑгленнÑÑ
Ñголков
- * @param {getCornerParams()} options ÐаÑамеÑÑÑ ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ Ñголка
- * @param {HTMLElement} elem ÐлеменÑ, коÑоÑÐ¾Ð¼Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÑÑÑÑÑ Ñголки
- * @param {Number} border_width ТолÑина боÑдÑÑа
- */
- function createCSSRules(options, elem) {
- var radius = options.radius,
- border_width = options.real_border_width || 0,
- diff = (options.use_shape) ? options.real_border_width - options.border_width : 0;
-// border_width += 10;
-
-// corners_ss.disabled = true;
-
- var class_name = getClassName(options);
- if (!_corner_cache.created[class_name]) {
- // Ñакое пÑавило еÑе не Ñоздано в CSS, Ñоздадим его
- var prefix = (browser.version < 7)
- ? '.' + class_name + ' .' + base_class // IE6
- : '.' + class_name + '>.' + base_class; // IE7+
-
- var offset_x = -border_width,
- offset_y = -1 -border_width;
-
-
- addRule(prefix, 'width:' + (radius + border_width + 1) + 'px;height:' + (radius + 1) + 'px');
-
- if (options.use_shape) {
- offset_y = -radius - 1 - diff;
- var left_adjust = radius + options.border_width * 2 + diff;
- adjustBox(elem, class_name, options);
- var clip_size = Math.max(radius - border_width * 2, 0);
- var pad_size = Math.min(radius - border_width * 2, 0) * -1;
-
- if (browser.version < 7) {
- pad_size += parseInt(getStyle(elem, 'padding-left') || 0) + parseInt(getStyle(elem, 'padding-right') || 0);
- }
-
- var css_rules = 'width:100%;clip:rect(auto auto auto ' + (clip_size) + 'px);padding-right:' + (pad_size) + 'px;left:' + (-border_width - clip_size) + 'px;';
- addRule(prefix + '-tl', css_rules + 'top:' + offset_y + 'px;');
- addRule(prefix + '-tl .' + vml_class, 'left:' + (clip_size) + 'px');
-
- addRule(prefix + '-bl', css_rules +'bottom:' + offset_y + 'px;');
- addRule(prefix + '-bl .' + vml_class, 'left:' + (clip_size) + 'px');
- } else {
- addRule(prefix + '-tl', 'left:' + offset_x + 'px;top:' + offset_y + 'px;');
- addRule(prefix + '-bl', 'left:' + offset_x + 'px;bottom:' + offset_y + 'px;');
- }
-
- if (browser.version < 7) {
- offset_x = -radius;
- if (border_width) {
- offset_x += -border_width % 2 + radius % 2;
- } else {
- offset_x -= (radius) % 2;
- }
-// var padding = parseInt(getStyle(elem, 'padding-left') || 0) + parseInt(getStyle(elem, 'padding-right') || 0);
- addRule(prefix + '-tr', 'left:' + offset_x + 'px;top:' + offset_y + 'px;');
- addRule(prefix + '-br', 'left:' + offset_x + 'px;bottom:' + offset_y + 'px;');
-// addRule(prefix + '-tl', 'padding-right:'+ padding +'px');
-// addRule(prefix + '-bl', 'padding-right:'+ padding +'px');
- } else {
- addRule(prefix + '-tr', 'right:' + offset_x + 'px;top:' + offset_y + 'px;');
- addRule(prefix + '-br', 'right:' + offset_x + 'px;bottom:' + offset_y + 'px;');
- }
-
- _corner_cache.created[class_name] = true;
- }
-
-// corners_ss.disabled = false;
- }
-
- addCorners = function(elem, radius) {
- var cparams = getCornerParams(elem, radius);
-
- createCSSRules(cparams, elem);
-
- // ÑепеÑÑ Ð´Ð¾Ð±Ð°Ð²Ð»Ñем Ñами Ñголки в ÑлеменÑ
- walkArray(['tl', 'tr', 'bl', 'br'], function(){
- elem.appendChild(drawCornerIE(cparams, this));
- });
-
-
- // говоÑим, ÑÑо вÑе добавилоÑÑ
- elem.className += ' ' + getClassName(cparams) + ' ' + base_class + '-init';
-
- };
-
- result.update = function() {
- applyCornersToArgs(arguments, function(){
- removeOldCorners(this);
- addCorners(this);
- });
- };
-}
\ No newline at end of file
diff --git a/js_src/ie-test.js b/js_src/ie-test.js
deleted file mode 100644
index a63d618..0000000
--- a/js_src/ie-test.js
+++ /dev/null
@@ -1,128 +0,0 @@
-/**
- * Ðобавление Ñголков Ð´Ð»Ñ IE
- * @author Sergey Chikuyonok (sc@design.ru)
- * @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
- * @include "common.js"
- */
-
-if (browser.msie) {
- _corner_cache.ix = 0;
- _corner_cache.created = {};
-
- /**
- * ÐозвÑаÑÐ°ÐµÑ Ð¸Ð¼Ñ ÐºÐ»Ð°ÑÑа Ð´Ð»Ñ Ð¿ÐµÑеданнÑÑ
паÑамеÑÑов. ÐÑполÑзÑеÑÑÑ Ð´Ð»Ñ
- * Ñого, ÑÑÐ¾Ð±Ñ Ð½Ðµ плодиÑÑ Ð¼Ð½Ð¾Ð³Ð¾ ÑазнÑÑ
клаÑÑов Ð´Ð»Ñ Ð¾Ð´Ð½Ð¸Ñ
и ÑеÑ
же пÑавил
- * @param {Number} radius РадиÑÑ ÑкÑÑÐ³Ð»ÐµÐ½Ð¸Ñ Ñголка
- * @param {Number} border_width ТолÑина боÑдÑÑа
- * @return {String}
- */
- function getClassName(radius, border_width) {
- border_width = border_width || 0;
- var key = radius + ':' + border_width;
- if (!_corner_cache[key]) {
- _corner_cache[key] = rule_prefix + _corner_cache.ix++;
- }
-
- return _corner_cache[key];
- }
-
- /**
- * Ð¡Ð¾Ð·Ð´Ð°ÐµÑ CSS-пÑавила Ð´Ð»Ñ ÑкÑÑгленнÑÑ
Ñголков
- * @param {Number} radius РадиÑÑ ÑкÑÑглениÑ
- * @param {Number} border_width ТолÑина боÑдÑÑа
- */
- function createCSSRules(radius, border_width) {
- border_width = border_width || 0;
- var class_name = getClassName(radius, border_width);
- if (!_corner_cache.created[class_name]) {
- // Ñакое пÑавило еÑе не Ñоздано в CSS, Ñоздадим его
- var prefix, b = border_width;
-
- if (browser.version < 7) {
- prefix = '.' + class_name + ' .' + base_class;
-
- addRule(prefix + '-tl', 'left:' + (-b) + 'px; top:' + (-1 - b) + 'px;');
-
- addRule(
- prefix + '-tr',
- 'left:' + (b - 1 ) + 'px; ' +
- 'width: ' + (1) + 'px; ' +
- 'top:' + (-1 - b) + 'px;'
- );
-
- addRule(
- prefix + '-bl',
- 'left:' + (- border_width) + 'px; ' +
- 'bottom:' + (-border_width) + 'px;' +
- 'height:' + radius + 'px'
- );
-
- addRule(
- prefix + '-br',
- 'left:' + (-radius + border_width - 1) + 'px; ' +
- 'width: ' + (radius) + 'px; ' +
- 'bottom:' + (-border_width) + 'px;' +
- 'height:' + radius + 'px'
- );
- } else {
- prefix = '.' + class_name + '>.' + base_class;
- addRule(
- prefix + '-tl',
- 'left:' + (-1 - border_width) + 'px; ' +
- 'top:' + (-1 - border_width) + 'px;'
- );
-
- addRule(
- prefix + '-tr',
- 'right:' + ( - border_width) + 'px; ' +
- 'top:' + (-1 - border_width) + 'px;'
- );
-
- addRule(
- prefix + '-bl',
- 'left:' + (-1 - border_width) + 'px; ' +
- 'bottom:' + (-border_width) + 'px;'
- );
-
- addRule(
- prefix + '-br',
- 'right:' + (-border_width) + 'px; ' +
- 'bottom:' + (-border_width) + 'px;'
- );
-
- }
-
-
- _corner_cache.created[class_name] = true;
- }
- }
-
- createStylesheet();
- try {
- if (!document.namespaces["v"])
- document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
- } catch(e) { }
-
- addRule = function(selector, rules){
- alert(selector);
- corners_ss.addRule('p', rules);
- };
-
- addCorners = function(elem, radius){
- var cparams = getCornerParams(elem, radius);
-
-// addRule('body', 'background:blue');
-
- createCSSRules(cparams.radius, cparams.real_border_width);
-
-// // ÑепеÑÑ Ð´Ð¾Ð±Ð°Ð²Ð»Ñем Ñами Ñголки в ÑлеменÑ
-// walkArray(['tl', 'tr', 'bl', 'br'], function(){
-// elem.appendChild(drawCornerIE(cparams, this));
-// });
-
-
- // говоÑим, ÑÑо вÑе добавилоÑÑ
-// alert(getClassName(cparams.radius, cparams.real_border_width) + ' ' + base_class + '-init');
- elem.className += ' ' + getClassName(cparams.radius, cparams.real_border_width) + ' ' + base_class + '-init';
- };
-}
\ No newline at end of file
diff --git a/js_src/init.js b/js_src/init.js
index f3b23b2..e762a5e 100644
--- a/js_src/init.js
+++ b/js_src/init.js
@@ -1,49 +1,52 @@
/**
* @author Sergey Chikuyonok (serge.che@gmail.com)
* @link http://chikuyonok.ru
* @include "common.js"
* @include "worker.js"
* @include "canvas.js"
* @include "vml.js"
*/
addDomReady(processRoundedElements);
// поÑле Ñого, как добавили Ñголки, необÑ
одимо оÑиÑÑиÑÑ ÐºÑÑ Ñона,
// инаÑе бÑдÑÑ Ð¿ÑÐ¾Ð±Ð»ÐµÐ¼Ñ Ñ Ð´Ð¸Ð½Ð°Ð¼Ð¸ÑеÑким обновлением блоков
addDomReady(function(){
walkArray(getBg.processed_elems, function(){
this.removeAttribute('rocon_bg');
});
getBg.use_cache = false;
});
// set browser-specific properties
-//canvas.returnType(2);
-worker.setAdapter(canvas);
-if (browser.safari) {
- canvas.returnType(2);
-// worker.nativeProperties(
-// '-webkit-border-top-left-radius',
-// '-webkit-border-top-right-radius',
-// '-webkit-border-bottom-right-radius',
-// '-webkit-border-bottom-left-radius'
-// );
-} else if (browser.mozilla) {
-// worker.nativeProperties(
-// '-moz-border-radius-topleft',
-// '-moz-border-radius-topright',
-// '-moz-border-radius-bottomright',
-// '-moz-border-radius-bottomleft'
-// );
-} else if (browser.msie) {
+if (browser.msie) {
worker.setAdapter(vml);
addDomReady(function(){
corners_ss.cssText += css_text;
css_text = '';
addRule = corners_ss.addRule;
});
+} else {
+ worker.setAdapter(canvas);
+ //canvas.returnType(2);
+ if (browser.safari) {
+ canvas.returnType(2);
+ // worker.nativeProperties(
+ // '-webkit-border-top-left-radius',
+ // '-webkit-border-top-right-radius',
+ // '-webkit-border-bottom-right-radius',
+ // '-webkit-border-bottom-left-radius'
+ // );
+ } else if (browser.mozilla) {
+ // worker.nativeProperties(
+ // '-moz-border-radius-topleft',
+ // '-moz-border-radius-topright',
+ // '-moz-border-radius-bottomright',
+ // '-moz-border-radius-bottomleft'
+ // );
+ }
+ //else if (browser.opera)
+ // worker.setAdapter(svg);
+
}
-//else if (browser.opera)
-// worker.setAdapter(svg);
bindReady();
\ No newline at end of file
diff --git a/js_src/DD_roundies.js b/js_src/lib/DD_roundies.js
similarity index 100%
rename from js_src/DD_roundies.js
rename to js_src/lib/DD_roundies.js
diff --git a/js_src/base64.js b/js_src/lib/base64.js
similarity index 100%
rename from js_src/base64.js
rename to js_src/lib/base64.js
diff --git a/js_src/firebug.js b/js_src/lib/firebug.js
similarity index 100%
rename from js_src/firebug.js
rename to js_src/lib/firebug.js
diff --git a/js_src/worker.js b/js_src/worker.js
index 2c6d9d5..b72653d 100644
--- a/js_src/worker.js
+++ b/js_src/worker.js
@@ -1,522 +1,528 @@
/**
* Main worker and caching mechanism used for storing and applying of drawn
* corners to the elements
*
* @author Sergey Chikuyonok (serge.che@gmail.com)
* @link http://chikuyonok.ru
* @include "common.js"
* @include "canvas.js"
*/
var worker = (function(){
/** @type {canvas} Drawing adapter (canvas, SVG, VML) */
var adapter = null,
/** Cached corners */
cache = {},
/** Number of keys in cache */
key_count = 0,
/** Native browser properties used to draw browser corners */
native_props = [],
queue = [],
/** Corner type index in array */
type_pos = {tl: 0, tr: 1, br: 2, bl: 3},
/** CSS properties for corner types */
corner_type_map = {
tl: {
left: 'border-left-width',
left_color: 'border-left-color',
top: 'border-top-width',
top_color: 'border-top-color'
},
tr: {
left: 'border-right-width',
left_color: 'border-right-color',
top: 'border-top-width',
top_color: 'border-top-color'
},
br: {
left: 'border-right-width',
left_color: 'border-right-color',
top: 'border-bottom-width',
top_color: 'border-bottom-color'
},
bl: {
left: 'border-left-width',
left_color: 'border-left-color',
top: 'border-bottom-width',
top_color: 'border-bottom-color'
}
},
opposite_corners = {
tl: 'tr',
tr: 'tl',
bl: 'br',
br: 'bl'
},
css_props = [];
//fill-up CSS properties
walkArray(['left', 'top', 'right', 'bottom'], function(i, n){
var prefix = 'border-' + n;
css_props.push(prefix + '-color', prefix + '-width');
});
/**
* Check if we need to add extra width for image (for shape-type corners)
* @param {Object} params
* @param {String} params
* @return {Boolean}
*/
function needExtraWidth(params, type) {
return params.shape && (type || 'tl').charAt(1) == 'r';
}
/**
* Returns the smallest numbers
* @return {Number}
*/
function min() {
var args = mapArray(arguments, function(n, i){
return parseInt(n) || 0;
});
if (args.length == 2) {
return args[0] < args[1] ? args[0] : args[1];
} else {
var result = args[0];
for (var i = 1; i < args.length; i++) {
if (args[i] < result)
result = args[i];
}
return result;
}
}
/**
* Returns the highest numbers
* @return {Number}
*/
function max() {
var args = mapArray(arguments, function(n, i){
return parseInt(n) || 0;
});
if (args.length == 2)
return args[0] > args[1] ? args[0] : args[1];
else {
var result = args[0];
for (var i = 1; i < args.length; i++) {
if (args[i] > result)
result = args[i];
}
return result;
}
}
/**
* Returns key used to store image data
* @param {Array|Object} params Corner parameters
* @return {String}
*/
function cacheKey(params) {
var result = [];
if (params instanceof Array)
for (var i = 0; i < params.length; i++)
result.push(params[i]);
else
for (var a in params) if (params.hasOwnProperty(a))
result.push(a + ':' + params[a]);
return result.join(';');
}
/**
* Add value to cache
* @param {String} key Cache key
* @param {String} [value] Cache value. If not set, internal class name will be used
* @return {String} Internal class name
*/
function addToCache(key, value) {
if (getCachedValue(key))
return getCachedValue(key);
key_count++;
cache[key] = value || rule_prefix + key_count;
return rule_prefix + key_count;
}
/**
* Returns cached value
* @param {String} key cache key
* @return {String|null}
*/
function getCachedValue(key) {
return cache[key];
}
/**
* Add native CSS corners to the element
* @param {Array} radius Set of border radius values
* @param {HTMLElement} elem Element to add corners
*/
function addNativeCorners(radius, elem) {
var key = cacheKey(radius),
css_class = getCachedValue(key),
css_rules = '';
if (!css_class) {
css_class = addToCache(key);
walkArray(native_props, function(i, n){
css_rules += n + ':' + radius[i] + 'px;';
});
addRule('.' + css_class, css_rules);
}
addClass(css_class, elem);
}
/**
* Creates, if necessary, new corner elements and returns them
* @param {HTMLElement} elem Container element
* @return {Object}
*/
function createCornerElements(elem) {
var result = {},
found = 0,
re = new RegExp('\\b' + base_class + '-([tblr]{2})\\b', 'i'),
m;
walkArray(elem.childNodes, function(i, /* HTMLElement */ n){
if (m = re.exec(n.className)) {
found++;
result[m[1]] = n;
}
});
if (!found) {
walkArray(['tl', 'tr', 'bl', 'br'], function(i, n) {
var e = createElement('span', base_class + ' ' + base_class +'-' + n);
elem.appendChild(e);
result[n] = e;
});
}
return result;
}
/**
* Add element to drawing queue
* @param {Object} params Parent element params
* @param {HTMLElement} parent Parent element
* @param {Object} corners Corner elements
*/
function addToQueue(params, parent, corners) {
queue.push([params, parent, corners]);
}
/**
* Removes old internal classes from element
* @param {HTMLElement} elem
* @param {String} new_class New class name to add (optional)
* @return {HTMLElement}
*/
function cleanUp(elem, new_class) {
elem.className = elem.className.replace(/\s*rocon__\d+/, '');
if (new_class)
elem.className += ' ' + new_class;
return elem;
}
/**
* Returns width that must be set for specified corner type
* @param {Object} params Corner's container element params
* @param {String} type Corner type (tl, tr, bl, br)
* @return {Number}
*/
function getCornerWidth(params, type) {
return needExtraWidth(params, type) ? 2000 : params.radius[type_pos[type]];
}
/**
* Returns height that must be set for specified corner type
* @param {Object} params Corner's container element params
* @param {String} type Corner type (tl, tr, bl, br)
* @return {Number}
*/
function getCornerHeight(params, type) {
var cur_pos = type_pos[type],
op_pos = type_pos[ opposite_corners[type] ];
return Math.max(params.radius[cur_pos], params.radius[op_pos]);
}
/**
* Draw corners using adapter
* @param {Object} params Parent element params
* @param {HTMLElement} parent Parent element
* @param {HTMLElement[]} corners Corner elements
* @param {Object} style Cached CSS properties
*/
function drawCorners(params, parent, corners, style) {
// gather all params for all corners
var all_params = {}, css_map, elem, style;
for (var corner_type in corners) {
css_map = corner_type_map[corner_type];
/** @type {HTMLElement} */
elem = corners[corner_type];
style = style || getStyle(parent, css_props);
// debugger;
// gather params for current corner
var r = parseInt(params.radius[ type_pos[corner_type] ]);
all_params[corner_type] = {
radius: r,
top: min(style[css_map.top], r),
real_top: parseInt(style[css_map.top]) || 0,
top_color: convertColorToHex(style[css_map.top_color]),
left: min(style[css_map.left], r),
real_left: parseInt(style[css_map.left]) || 0,
left_color: convertColorToHex(style[css_map.left_color]),
color: getBg(params.shape ? parent : parent.parentNode),
use_shape: params.shape,
type: corner_type,
width: max(getCornerWidth(params, corner_type), parseInt(style[css_map.left]) || 0),
height: getCornerHeight(params, corner_type)
};
}
// create corners
for (var corner_type in corners) {
/** @type {HTMLElement} */
elem = corners[corner_type];
var cparams = all_params[corner_type];
// calculate X and Y offsets
cparams.offset_x = -cparams.real_left;
cparams.offset_y = -(params.shape ? max(cparams.height, cparams.radius, cparams.real_top) : cparams.real_top);
var op_corner = opposite_corners[corner_type],
key = cacheKey(cparams);
if (needExtraWidth(params, corner_type)) {
//add extra properties for cache key
key += '--' + (cparams.left + all_params[op_corner].left) +
':' + params.radius[ type_pos[op_corner] ];
}
var css_class = getCachedValue(key);
if (!css_class) {
// image is not yet created
css_class = addToCache(key);
var css_rules = 'height:' + cparams.height + 'px;';
if (adapter.returnType() != 2)
css_rules += 'background-image:url(' + adapter.draw(cparams) + ');';
if (needExtraWidth(params, corner_type)) {
css_rules += 'width:100%;' +
'padding-left:' + (cparams.real_left + all_params[op_corner].left) + 'px;' +
'clip:rect(auto,auto,auto,' + params.radius[ type_pos[op_corner] ] + 'px);' +
'background-position:top right;';
} else {
css_rules += 'width:' + cparams.width + 'px;';
}
var offset_top = -(params.shape ? Math.max(cparams.height, cparams.radius) : cparams.top);
css_rules += ( corner_type.charAt(0) == 't' ? 'top:' : 'bottom:' ) + cparams.offset_y + 'px;';
css_rules += ( corner_type.charAt(1) == 'l' ? 'left:' : 'right:' ) + cparams.offset_x + 'px;';
addRule('.' + css_class, css_rules);
}
cleanUp(elem, css_class);
+
if (adapter.returnType() == 2) {
- elem.innerHTML = '';
- elem.appendChild(adapter.draw(cparams));
+ var corner = adapter.draw(cparams);
+ if (typeof(corner) == 'string') {
+ elem.innerHTML = adapter.draw(cparams);
+ } else {
+ elem.innerHTML = '';
+ elem.appendChild(adapter.draw(cparams));
+ }
}
}
cleanUp(parent);
if (!hasClass(parent, 'rocon-init'))
addClass('rocon-init', parent);
if (params.shape)
adjustBox(params, parent);
}
/**
* Add corners drawn by <code>adapter</code> to the element
* @param {Array} params.radius Array of radius values
* @param {Boolean} params.shape Use shape instead of counter-shape
* @param {HTMLElement} elem Element to apply corners
* @param {Boolean} [is_immediate] Draw corners immediately instead adding element to the queue (may cause performance issues in Opera)
*/
function addAdapterCorners(params, elem, is_immediate) {
/*
* Due to stupid Opera bug (http://chikuyonok.ru/playground/opera-bug/)
* we need to split this single process into two loops:
* 1. Add corner elements to the container
* 2. Draw images and apply them to the corners
*/
var corners = createCornerElements(elem);
if (is_immediate)
drawCorners(params, elem, corners);
else
addToQueue(params, elem, corners);
}
/**
* Main processing function
* @param {Array} params.radius Array of radius values
* @param {Boolean} params.shape Use shape instead of counter-shape
* @param {Boolean} params.force {Boolean} Force usage of drawing adapter instead of native properties
* @param {HTMLElement} elem Element to apply corners
* @param {Boolean} [is_immediate] Draw corners immediately instead adding element to the queue (may cause performance issues in Opera)
*/
function process(params, elem, is_immediate) {
if (native_props.length && !params.force) {
addNativeCorners(params.radius, elem);
} else {
addAdapterCorners(params, elem, is_immediate);
}
}
/**
* ÐоÑÑекÑиÑÑÐµÑ CSS-ÑвойÑÑва ÑлеменÑа Ð´Ð»Ñ Ð¿ÑавилÑного ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ Ñголков в виде
* ÑоÑмÑ
* @param {Object} params Corner params
* @param {HTMLElement} elem ÐлеменÑ, коÑоÑÑй нÑжно подкоÑÑекÑиÑоваÑÑ
*/
function adjustBox(params, elem) {
var pt = 'padding-top',
pb = 'padding-bottom',
mt = 'margin-top',
mb = 'margin-bottom',
btw = 'border-top-width',
bbw = 'border-bottom-width',
getProp = function(prop) {
return parseInt(elem_styles[prop], 10) || 0;
},
addCSSRule = function(property, value) {
return property + ':' + value + 'px !important;';
},
elem_styles = getStyle(elem, [pt, pb, mt, mb, btw, bbw]),
offset_top = Math.max(params.radius[ type_pos['tl'] ], params.radius[ type_pos['tr'] ]),
offset_bottom = Math.max(params.radius[ type_pos['bl'] ], params.radius[ type_pos['br'] ]),
offset_border_top = Math.min(offset_top, getProp(btw)),
offset_border_bottom = Math.min(offset_bottom, getProp(bbw));
/*
* ÐÑполÑзÑем ÑоÑмÑ, поÑÑÐ¾Ð¼Ñ Ñ Ð±Ð»Ð¾ÐºÐ° Ñнижаем веÑÑ
ние и нижние
* боÑдÑÑÑ, а Ñакже на велиÑÐ¸Ð½Ñ ÑадиÑÑа Ñнижаем веÑÑ
ний
* и нижний паддинг
*/
var padding_top = Math.max(getProp(pt) - offset_top + offset_border_top, 0),
padding_bottom = Math.max(getProp(pb) - offset_bottom + offset_border_bottom, 0),
margin_top = getProp(mt) + offset_top,
margin_bottom = getProp(mb) + offset_bottom,
border_top_width = getProp(btw) - offset_border_top,
border_bottom_width = getProp(bbw) - offset_border_bottom,
key = cacheKey([padding_top, padding_bottom, margin_top, margin_bottom, border_top_width, border_bottom_width]),
class_name = getCachedValue(key);
if (!class_name) {
class_name = addToCache(key);
addRule('.' + class_name,
addCSSRule(btw, border_top_width) +
addCSSRule(bbw, border_bottom_width) +
addCSSRule(pt, padding_top) +
addCSSRule(pb, padding_bottom) +
addCSSRule(mt, margin_top) +
addCSSRule(mb, margin_bottom));
}
elem.className += ' ' + class_name;
}
return {
/**
* Set drawing adapter
*/
setAdapter: function(obj) {
adapter = obj;
if ('init' in adapter)
adapter.init();
},
/**
* Set native CSS properties for drawing rounded borders
* @param {String} tl Top-left corner
* @param {String} tr Top-right corner
* @param {String} br Bottom-right corner
* @param {String} bl Bottom-left corner
*/
nativeProperties: function(tl, tr, br, bl) {
native_props = [tl, tr, br, bl];
},
/**
* Enqueue element for corners addition
* @param {Array} params.radius Array of radius values
* @param {Boolean} params.shape Use shape instead of counter-shape
* @param {Boolean} params.force {Boolean} Force usage of drawing adapter instead of native properties
* @param {HTMLElement} elem Element to apply corners
*/
add: function(params, elem) {
process(params, elem);
},
/**
* Add corners to enqueued elements
*/
run: function() {
var start = (new Date).getTime();
walkArray(queue, function(i, n){
drawCorners(n[0], n[1], n[2]);
});
var stop1 = (new Date).getTime();
applyCSS();
var stop2 = (new Date).getTime();
alert('Draw: ' + (stop1 - start) + ' ms, CSS: ' + (stop2 - stop1) + ' ms');
},
/**
* Add corners to the element
*/
apply: function(params, elem) {
process(params, elem, true);
}
}
})();
\ No newline at end of file
diff --git a/js_src/firebug.css b/test/firebug.css
similarity index 100%
rename from js_src/firebug.css
rename to test/firebug.css
diff --git a/js_src/firebug.html b/test/firebug.html
similarity index 100%
rename from js_src/firebug.html
rename to test/firebug.html
|
sergeche/rocon
|
53b2ee934db5068d0f1831149cf634f4e5186cf7
|
Added canvas init method
|
diff --git a/js_src/canvas.js b/js_src/canvas.js
index 92686d2..2df142e 100644
--- a/js_src/canvas.js
+++ b/js_src/canvas.js
@@ -1,235 +1,243 @@
/**
* Canvas adapter for drawing rounded corners
* @author Sergey Chikuyonok (serge.che@gmail.com)
* @link http://chikuyonok.ru
*
* @include "common.js"
* @include "/js-libs/canvas-doc.js"
*/
var canvas = (function(){
var composite_op = 'destination-out',
- /** Canvas where all images are drawn */
- cv = createElement('canvas'),
+ /** @type {Element} Canvas where all images are drawn */
+ cv,
+ /** @type {Element} Canvas for stroke */
+ stroke_cv,
+
/** @type {CanvasRenderingContext2D} Drawing context */
- ctx = cv.getContext('2d'),
+ ctx,
+ /** @type {CanvasRenderingContext2D} Stroke drawing context */
+ stroke_ctx,
/** Type of returnerd object of <code>draw()</code> method (1 â image string, 2 â canvas element) */
return_type = 1;
// debug only
// document.body.appendChild(cv);
- cv.width = 10;
- cv.height = 10;
-
- var stroke_cv = createElement('canvas'),
- /** @type {CanvasRenderingContext2D} Drawing context */
- stroke_ctx = stroke_cv.getContext('2d');
-
/**
* Prepare canvas for drawing: removes old paintings, restores original
* transform matrix, scales canvas
*
* @param {Number} params.radius Corner radius
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
* @param {String} params.type Corner type: tl, tr, bl, br
*/
function prepare(params) {
ctx.restore();
cv.width = params.width;
cv.height = params.height;
ctx.clearRect(0, 0, cv.width, cv.height);
ctx.save();
}
/**
* Draw border shape (stroke) on <code>ctx</code>. Canvas must be already
* scaled to the size of corner.
*
* @param {Number} params.radius Corner radius
* @param {Number} params.left Left border width, pixels
* @param {String} params.left_color Left border color
* @param {Number} params.top Top border width, pixels
* @param {String} params.top_color Top border color
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
*/
function drawStroke(params) {
// create short-hand vars for better YUICompressor mungin
var radius = params.radius,
border_left = params.left,
border_top = params.top;
if (!(border_left + border_top))
// nothing to draw
return;
stroke_cv.width = params.width;
stroke_cv.height = params.height;
stroke_ctx.clearRect(0, 0, params.width, params.height);
if (border_top) {
stroke_ctx.fillStyle = params.top_color;
stroke_ctx.fillRect(radius, 0, cv.width, border_top);
}
if (border_left) {
stroke_ctx.fillStyle = params.left_color;
stroke_ctx.fillRect(0, radius, border_left, cv.height);
}
stroke_ctx.save();
if (params.top_color != params.left_color) {
var grd = ctx.createLinearGradient(0, border_top, 0, radius);
grd.addColorStop(0, border_top ? params.top_color : params.left_color);
grd.addColorStop(1, border_left ? params.left_color : params.top_color);
stroke_ctx.fillStyle = grd;
} else {
stroke_ctx.fillStyle = params.top_color;
}
// start drawing two circles to create border arc
ctx.save();
stroke_ctx.beginPath();
stroke_ctx.arc(radius, radius, radius, 0, Math.PI * 2, true);
stroke_ctx.fill();
ctx.restore();
// change composite operation so the next circle will be extracted from the previous one
stroke_ctx.globalCompositeOperation = composite_op;
stroke_ctx.translate(border_left, border_top);
if (radius) {
stroke_ctx.scale(Math.max(1 - border_left / radius, 0) || 0.01, Math.max(1 - border_top / radius, 0) || 0.01);
}
stroke_ctx.beginPath();
stroke_ctx.arc(radius, radius, radius, 0, Math.PI * 2, true);
stroke_ctx.fill();
stroke_ctx.restore();
// leave only one quarter of circle
stroke_ctx.clearRect(radius, border_top, radius, cv.height);
stroke_ctx.clearRect(border_left, radius, cv.width, cv.height);
ctx.drawImage(stroke_cv, 0, 0);
}
/**
* Rotate canvas for specified corner type
*
* @param {String} Corner type: tl, tr, bl, br
* @param {Number} radius Corner radius
*/
function rotate(params) {
switch (params.type) {
case 'tr': // top right corner
ctx.scale(-1, 1);
ctx.translate(-params.width, 0);
break;
case 'bl': // bottom left corner
ctx.scale(1, -1);
ctx.translate(0, -params.height);
break;
case 'br': // bottom right corner
ctx.scale(-1, -1);
ctx.translate(-params.width, -params.height);
break;
}
}
/**
* Draw background for corner image
*
* @param {Number} params.radius Corner radius
* @param {Number} params.left Left border width, pixels
* @param {Number} params.top Top border width, pixels
* @param {String} params.color Color of background
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
*/
function drawBackground(params) {
var radius = params.radius,
offset_x = 0,
offset_y = 0;
ctx.save();
ctx.fillStyle = params.color;
if (!params.use_shape) {
ctx.fillRect(0, 0, radius, radius);
if (params.left)
offset_x = .5;
if (params.top)
offset_y = .5;
ctx.globalCompositeOperation = composite_op;
} else {
if (params.left)
offset_x = 1;
if (params.top)
offset_y = 1;
}
ctx.translate(offset_x, offset_y);
ctx.beginPath();
ctx.fillStyle = params.color;
ctx.arc(radius, radius, radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.restore();
if (params.use_shape) {
ctx.fillStyle = params.color;
ctx.fillRect(radius, 0, cv.width, cv.height);
ctx.fillRect(0, radius, cv.width, cv.height);
}
}
return {
+ init: function() {
+ cv = createElement('canvas');
+ ctx = cv.getContext('2d');
+ cv.width = 10;
+ cv.height = 10;
+
+ stroke_cv = createElement('canvas');
+ stroke_ctx = stroke_cv.getContext('2d');
+ },
+
/**
* Draw rounded corner
*
* @param {Number} params.radius Corner radius
* @param {Number} params.left Left border width, pixels
* @param {String} params.left_color Left border color
* @param {Number} params.top Top border width, pixels
* @param {String} params.top_color Top border color
* @param {Boolean} params.use_shape Flag, indicating that shape, not counter-shape, must be drawn
* @param {String} params.color Color of background
* @param {String} params.type Corner type: tl, tr, bl, br
*
* @return {String} Image in data:URL format
*/
draw: function(params) {
// TODO delete this
params.width = params.width || params.radius;
params.height = params.height || params.radius;
if (return_type == 2) {
cv = createElement('canvas', 'rocon-cn');
ctx = cv.getContext('2d');
}
prepare(params);
rotate(params);
drawBackground(params);
drawStroke(params);
return (return_type == 2) ? cv : cv.toDataURL();
},
returnType: function(type) {
if (typeof(type) != 'undefined')
return_type = type;
return return_type;
}
};
})();
\ No newline at end of file
diff --git a/js_src/worker.js b/js_src/worker.js
index 9297649..2c6d9d5 100644
--- a/js_src/worker.js
+++ b/js_src/worker.js
@@ -1,537 +1,522 @@
/**
* Main worker and caching mechanism used for storing and applying of drawn
* corners to the elements
*
* @author Sergey Chikuyonok (serge.che@gmail.com)
* @link http://chikuyonok.ru
* @include "common.js"
* @include "canvas.js"
*/
var worker = (function(){
/** @type {canvas} Drawing adapter (canvas, SVG, VML) */
var adapter = null,
/** Cached corners */
cache = {},
/** Number of keys in cache */
key_count = 0,
/** Native browser properties used to draw browser corners */
native_props = [],
queue = [],
/** Corner type index in array */
type_pos = {tl: 0, tr: 1, br: 2, bl: 3},
/** CSS properties for corner types */
corner_type_map = {
tl: {
left: 'border-left-width',
left_color: 'border-left-color',
top: 'border-top-width',
top_color: 'border-top-color'
},
tr: {
left: 'border-right-width',
left_color: 'border-right-color',
top: 'border-top-width',
top_color: 'border-top-color'
},
br: {
left: 'border-right-width',
left_color: 'border-right-color',
top: 'border-bottom-width',
top_color: 'border-bottom-color'
},
bl: {
left: 'border-left-width',
left_color: 'border-left-color',
top: 'border-bottom-width',
top_color: 'border-bottom-color'
}
},
opposite_corners = {
tl: 'tr',
tr: 'tl',
bl: 'br',
br: 'bl'
},
css_props = [];
//fill-up CSS properties
walkArray(['left', 'top', 'right', 'bottom'], function(i, n){
var prefix = 'border-' + n;
css_props.push(prefix + '-color', prefix + '-width');
});
/**
* Check if we need to add extra width for image (for shape-type corners)
* @param {Object} params
* @param {String} params
* @return {Boolean}
*/
function needExtraWidth(params, type) {
return params.shape && (type || 'tl').charAt(1) == 'r';
}
/**
* Returns the smallest numbers
* @return {Number}
*/
function min() {
var args = mapArray(arguments, function(n, i){
return parseInt(n) || 0;
});
if (args.length == 2) {
return args[0] < args[1] ? args[0] : args[1];
} else {
var result = args[0];
for (var i = 1; i < args.length; i++) {
if (args[i] < result)
result = args[i];
}
return result;
}
}
/**
* Returns the highest numbers
* @return {Number}
*/
function max() {
var args = mapArray(arguments, function(n, i){
return parseInt(n) || 0;
});
if (args.length == 2)
return args[0] > args[1] ? args[0] : args[1];
else {
var result = args[0];
for (var i = 1; i < args.length; i++) {
if (args[i] > result)
result = args[i];
}
return result;
}
}
/**
* Returns key used to store image data
* @param {Array|Object} params Corner parameters
* @return {String}
*/
function cacheKey(params) {
var result = [];
if (params instanceof Array)
for (var i = 0; i < params.length; i++)
result.push(params[i]);
else
for (var a in params) if (params.hasOwnProperty(a))
result.push(a + ':' + params[a]);
return result.join(';');
}
/**
* Add value to cache
* @param {String} key Cache key
* @param {String} [value] Cache value. If not set, internal class name will be used
* @return {String} Internal class name
*/
function addToCache(key, value) {
if (getCachedValue(key))
return getCachedValue(key);
key_count++;
cache[key] = value || rule_prefix + key_count;
return rule_prefix + key_count;
}
/**
* Returns cached value
* @param {String} key cache key
* @return {String|null}
*/
function getCachedValue(key) {
return cache[key];
}
/**
* Add native CSS corners to the element
* @param {Array} radius Set of border radius values
* @param {HTMLElement} elem Element to add corners
*/
function addNativeCorners(radius, elem) {
var key = cacheKey(radius),
css_class = getCachedValue(key),
css_rules = '';
if (!css_class) {
css_class = addToCache(key);
walkArray(native_props, function(i, n){
css_rules += n + ':' + radius[i] + 'px;';
});
addRule('.' + css_class, css_rules);
}
addClass(css_class, elem);
}
/**
* Creates, if necessary, new corner elements and returns them
* @param {HTMLElement} elem Container element
* @return {Object}
*/
function createCornerElements(elem) {
var result = {},
found = 0,
re = new RegExp('\\b' + base_class + '-([tblr]{2})\\b', 'i'),
m;
walkArray(elem.childNodes, function(i, /* HTMLElement */ n){
if (m = re.exec(n.className)) {
found++;
result[m[1]] = n;
}
});
if (!found) {
walkArray(['tl', 'tr', 'bl', 'br'], function(i, n) {
var e = createElement('span', base_class + ' ' + base_class +'-' + n);
elem.appendChild(e);
result[n] = e;
});
}
return result;
}
/**
* Add element to drawing queue
* @param {Object} params Parent element params
* @param {HTMLElement} parent Parent element
* @param {Object} corners Corner elements
*/
function addToQueue(params, parent, corners) {
queue.push([params, parent, corners]);
}
/**
* Removes old internal classes from element
* @param {HTMLElement} elem
* @param {String} new_class New class name to add (optional)
* @return {HTMLElement}
*/
function cleanUp(elem, new_class) {
elem.className = elem.className.replace(/\s*rocon__\d+/, '');
if (new_class)
elem.className += ' ' + new_class;
return elem;
}
/**
* Returns width that must be set for specified corner type
* @param {Object} params Corner's container element params
* @param {String} type Corner type (tl, tr, bl, br)
* @return {Number}
*/
function getCornerWidth(params, type) {
return needExtraWidth(params, type) ? 2000 : params.radius[type_pos[type]];
}
/**
* Returns height that must be set for specified corner type
* @param {Object} params Corner's container element params
* @param {String} type Corner type (tl, tr, bl, br)
* @return {Number}
*/
function getCornerHeight(params, type) {
var cur_pos = type_pos[type],
op_pos = type_pos[ opposite_corners[type] ];
return Math.max(params.radius[cur_pos], params.radius[op_pos]);
}
/**
* Draw corners using adapter
* @param {Object} params Parent element params
* @param {HTMLElement} parent Parent element
* @param {HTMLElement[]} corners Corner elements
* @param {Object} style Cached CSS properties
*/
function drawCorners(params, parent, corners, style) {
// gather all params for all corners
var all_params = {}, css_map, elem, style;
for (var corner_type in corners) {
css_map = corner_type_map[corner_type];
/** @type {HTMLElement} */
elem = corners[corner_type];
style = style || getStyle(parent, css_props);
// debugger;
// gather params for current corner
var r = parseInt(params.radius[ type_pos[corner_type] ]);
all_params[corner_type] = {
radius: r,
top: min(style[css_map.top], r),
real_top: parseInt(style[css_map.top]) || 0,
top_color: convertColorToHex(style[css_map.top_color]),
left: min(style[css_map.left], r),
real_left: parseInt(style[css_map.left]) || 0,
left_color: convertColorToHex(style[css_map.left_color]),
color: getBg(params.shape ? parent : parent.parentNode),
use_shape: params.shape,
type: corner_type,
width: max(getCornerWidth(params, corner_type), parseInt(style[css_map.left]) || 0),
height: getCornerHeight(params, corner_type)
};
}
// create corners
for (var corner_type in corners) {
/** @type {HTMLElement} */
elem = corners[corner_type];
var cparams = all_params[corner_type];
// calculate X and Y offsets
cparams.offset_x = -cparams.real_left;
cparams.offset_y = -(params.shape ? max(cparams.height, cparams.radius, cparams.real_top) : cparams.real_top);
var op_corner = opposite_corners[corner_type],
key = cacheKey(cparams);
if (needExtraWidth(params, corner_type)) {
//add extra properties for cache key
key += '--' + (cparams.left + all_params[op_corner].left) +
':' + params.radius[ type_pos[op_corner] ];
}
var css_class = getCachedValue(key);
if (!css_class) {
// image is not yet created
css_class = addToCache(key);
var css_rules = 'height:' + cparams.height + 'px;';
if (adapter.returnType() != 2)
css_rules += 'background-image:url(' + adapter.draw(cparams) + ');';
if (needExtraWidth(params, corner_type)) {
css_rules += 'width:100%;' +
'padding-left:' + (cparams.real_left + all_params[op_corner].left) + 'px;' +
'clip:rect(auto,auto,auto,' + params.radius[ type_pos[op_corner] ] + 'px);' +
'background-position:top right;';
} else {
css_rules += 'width:' + cparams.width + 'px;';
}
var offset_top = -(params.shape ? Math.max(cparams.height, cparams.radius) : cparams.top);
css_rules += ( corner_type.charAt(0) == 't' ? 'top:' : 'bottom:' ) + cparams.offset_y + 'px;';
css_rules += ( corner_type.charAt(1) == 'l' ? 'left:' : 'right:' ) + cparams.offset_x + 'px;';
addRule('.' + css_class, css_rules);
}
cleanUp(elem, css_class);
if (adapter.returnType() == 2) {
elem.innerHTML = '';
elem.appendChild(adapter.draw(cparams));
}
}
cleanUp(parent);
if (!hasClass(parent, 'rocon-init'))
addClass('rocon-init', parent);
if (params.shape)
adjustBox(params, parent);
}
/**
* Add corners drawn by <code>adapter</code> to the element
* @param {Array} params.radius Array of radius values
* @param {Boolean} params.shape Use shape instead of counter-shape
* @param {HTMLElement} elem Element to apply corners
* @param {Boolean} [is_immediate] Draw corners immediately instead adding element to the queue (may cause performance issues in Opera)
*/
function addAdapterCorners(params, elem, is_immediate) {
/*
* Due to stupid Opera bug (http://chikuyonok.ru/playground/opera-bug/)
* we need to split this single process into two loops:
* 1. Add corner elements to the container
* 2. Draw images and apply them to the corners
*/
var corners = createCornerElements(elem);
if (is_immediate)
drawCorners(params, elem, corners);
else
addToQueue(params, elem, corners);
}
/**
* Main processing function
* @param {Array} params.radius Array of radius values
* @param {Boolean} params.shape Use shape instead of counter-shape
* @param {Boolean} params.force {Boolean} Force usage of drawing adapter instead of native properties
* @param {HTMLElement} elem Element to apply corners
* @param {Boolean} [is_immediate] Draw corners immediately instead adding element to the queue (may cause performance issues in Opera)
*/
function process(params, elem, is_immediate) {
if (native_props.length && !params.force) {
addNativeCorners(params.radius, elem);
} else {
addAdapterCorners(params, elem, is_immediate);
}
}
/**
* ÐоÑÑекÑиÑÑÐµÑ CSS-ÑвойÑÑва ÑлеменÑа Ð´Ð»Ñ Ð¿ÑавилÑного ÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ Ñголков в виде
* ÑоÑмÑ
* @param {Object} params Corner params
* @param {HTMLElement} elem ÐлеменÑ, коÑоÑÑй нÑжно подкоÑÑекÑиÑоваÑÑ
*/
function adjustBox(params, elem) {
var pt = 'padding-top',
pb = 'padding-bottom',
mt = 'margin-top',
mb = 'margin-bottom',
btw = 'border-top-width',
bbw = 'border-bottom-width',
getProp = function(prop) {
return parseInt(elem_styles[prop], 10) || 0;
},
addCSSRule = function(property, value) {
return property + ':' + value + 'px !important;';
},
elem_styles = getStyle(elem, [pt, pb, mt, mb, btw, bbw]),
offset_top = Math.max(params.radius[ type_pos['tl'] ], params.radius[ type_pos['tr'] ]),
offset_bottom = Math.max(params.radius[ type_pos['bl'] ], params.radius[ type_pos['br'] ]),
offset_border_top = Math.min(offset_top, getProp(btw)),
offset_border_bottom = Math.min(offset_bottom, getProp(bbw));
/*
* ÐÑполÑзÑем ÑоÑмÑ, поÑÑÐ¾Ð¼Ñ Ñ Ð±Ð»Ð¾ÐºÐ° Ñнижаем веÑÑ
ние и нижние
* боÑдÑÑÑ, а Ñакже на велиÑÐ¸Ð½Ñ ÑадиÑÑа Ñнижаем веÑÑ
ний
* и нижний паддинг
*/
var padding_top = Math.max(getProp(pt) - offset_top + offset_border_top, 0),
padding_bottom = Math.max(getProp(pb) - offset_bottom + offset_border_bottom, 0),
margin_top = getProp(mt) + offset_top,
margin_bottom = getProp(mb) + offset_bottom,
border_top_width = getProp(btw) - offset_border_top,
border_bottom_width = getProp(bbw) - offset_border_bottom,
key = cacheKey([padding_top, padding_bottom, margin_top, margin_bottom, border_top_width, border_bottom_width]),
class_name = getCachedValue(key);
if (!class_name) {
class_name = addToCache(key);
addRule('.' + class_name,
addCSSRule(btw, border_top_width) +
addCSSRule(bbw, border_bottom_width) +
addCSSRule(pt, padding_top) +
addCSSRule(pb, padding_bottom) +
addCSSRule(mt, margin_top) +
addCSSRule(mb, margin_bottom));
}
elem.className += ' ' + class_name;
}
return {
/**
* Set drawing adapter
*/
setAdapter: function(obj) {
adapter = obj;
if ('init' in adapter)
adapter.init();
},
/**
* Set native CSS properties for drawing rounded borders
* @param {String} tl Top-left corner
* @param {String} tr Top-right corner
* @param {String} br Bottom-right corner
* @param {String} bl Bottom-left corner
*/
nativeProperties: function(tl, tr, br, bl) {
native_props = [tl, tr, br, bl];
},
/**
* Enqueue element for corners addition
* @param {Array} params.radius Array of radius values
* @param {Boolean} params.shape Use shape instead of counter-shape
* @param {Boolean} params.force {Boolean} Force usage of drawing adapter instead of native properties
* @param {HTMLElement} elem Element to apply corners
*/
add: function(params, elem) {
process(params, elem);
},
/**
* Add corners to enqueued elements
*/
run: function() {
- // first, we need to cache all required CSS properies
- // to get rid of nasty Opera bug
-// console.profile();
-// console.time('get_style');
-
-// var styles = [];
-// walkArray(queue, function(i, n){
-// styles[i] = getStyle(n[1], css_props);
-// });
-
-// console.timeEnd('get_style');
-
- console.time('create_corner');
- // then, draw and add corners
+ var start = (new Date).getTime();
walkArray(queue, function(i, n){
drawCorners(n[0], n[1], n[2]);
});
- console.timeEnd('create_corner');
- console.time('apply_css');
+ var stop1 = (new Date).getTime();
applyCSS();
- console.timeEnd('apply_css');
-
-// console.profileEnd();
+ var stop2 = (new Date).getTime();
+ alert('Draw: ' + (stop1 - start) + ' ms, CSS: ' + (stop2 - stop1) + ' ms');
},
/**
* Add corners to the element
*/
apply: function(params, elem) {
process(params, elem, true);
}
}
})();
\ No newline at end of file
diff --git a/test/canvas-adapter.html b/test/canvas-adapter.html
index 5c9d558..79fb4d0 100644
--- a/test/canvas-adapter.html
+++ b/test/canvas-adapter.html
@@ -1 +1 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<script type="text/javascript" src="../js_src/common.js"></script>
<script type="text/javascript" src="../js_src/canvas.js"></script>
<link rel="stylesheet" href="adapter_test.css" />
<style type="text/css">
#tl {
width:100px;
height:100px;
background:#fff;
}
#tr {
}
</style>
</head>
<body>
<div id="rocon" class="sample">
<div id="tl"></div>
<div id="tr"></div>
<div id="bl"></div>
<div id="br"></div>
</div>
<div id="reference" class="sample"></div>
<script type="text/javascript">
document.getElementById('tl').style.backgroundImage = 'url(' + canvas.draw({
radius: 50,
width: 100,
height: 100,
top: 5,
top_color: '#f00',
left: 2,
left_color: '#0f0',
color: '#eee',
use_shape: true,
type: 'tl'
}) + ')';
document.getElementById('tr').style.backgroundImage = 'url(' + canvas.draw({
radius: 10,
top: 3,
top_color: '#f00',
left: 10,
left_color: '#00f',
color: '#fff',
use_shape: false,
width: 10,
height: 10,
type: 'tr'
}) + ')';
document.getElementById('bl').style.backgroundImage = 'url(' + canvas.draw({
radius: 10,
top: 1,
top_color: '#fc0',
left: 2,
left_color: '#0f0',
color: '#fff',
use_shape: false,
type: 'bl'
}) + ')';
document.getElementById('br').style.backgroundImage = 'url(' + canvas.draw({
radius: 20,
top: 1,
top_color: '#fc0',
left: 10,
left_color: '#00f',
color: '#fff',
use_shape: false,
type: 'br'
}) + ')';
document.documentElement.style.outline = 'none';
</script>
</body>
</html>
\ No newline at end of file
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<script type="text/javascript" src="../js_src/common.js"></script>
<script type="text/javascript" src="../js_src/canvas.js"></script>
<link rel="stylesheet" href="adapter_test.css" />
<style type="text/css">
#tl {
width:100px;
height:100px;
background:#fff;
}
#tr {
}
</style>
</head>
<body>
<div id="rocon" class="sample">
<div id="tl"></div>
<div id="tr"></div>
<div id="bl"></div>
<div id="br"></div>
</div>
<div id="reference" class="sample"></div>
<script type="text/javascript">
canvas.init();
document.getElementById('tl').style.backgroundImage = 'url(' + canvas.draw({
radius: 50,
width: 100,
height: 100,
top: 5,
top_color: '#f00',
left: 2,
left_color: '#0f0',
color: '#eee',
use_shape: true,
type: 'tl'
}) + ')';
document.getElementById('tr').style.backgroundImage = 'url(' + canvas.draw({
radius: 10,
top: 3,
top_color: '#f00',
left: 10,
left_color: '#00f',
color: '#fff',
use_shape: false,
width: 10,
height: 10,
type: 'tr'
}) + ')';
document.getElementById('bl').style.backgroundImage = 'url(' + canvas.draw({
radius: 10,
top: 1,
top_color: '#fc0',
left: 2,
left_color: '#0f0',
color: '#fff',
use_shape: false,
type: 'bl'
}) + ')';
document.getElementById('br').style.backgroundImage = 'url(' + canvas.draw({
radius: 20,
top: 1,
top_color: '#fc0',
left: 10,
left_color: '#00f',
color: '#fff',
use_shape: false,
type: 'br'
}) + ')';
document.documentElement.style.outline = 'none';
</script>
</body>
</html>
\ No newline at end of file
|
sergeche/rocon
|
0a6b8e1ae1476b73984cc359033eb9bf677ccfe1
|
Add VML initialization on test page
|
diff --git a/test/vml-adapter.html b/test/vml-adapter.html
index 783850b..0b118b0 100644
--- a/test/vml-adapter.html
+++ b/test/vml-adapter.html
@@ -1 +1 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<script type="text/javascript" src="../js_src/common.js"></script>
<script type="text/javascript" src="../js_src/vml.js"></script>
<script type="text/javascript">
// try {
// if (!document.namespaces["v"])
// document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
// } catch(e) { }
</script>
<link rel="stylesheet" href="adapter_test.css" />
<style type="text/css">
.sample .vml {
top:-1px;
left:-1px;
/* display:block; */
margin:0;
padding:0;
}
#tl {
width:100px;
height:100px;
background:white;
}
</style>
</head>
<body>
<div id="rocon" class="sample">
<div id="tl"></div>
<div id="tr"></div>
<div id="bl"></div>
<div id="br"></div>
</div>
<div id="reference" class="sample"></div>
<script type="text/javascript">
document.getElementById('tl').innerHTML = vml.draw({
radius: 50,
width: 100,
height: 100,
top: 5,
top_color: '#f00',
left: 2,
left_color: '#0f0',
color: '#eee',
use_shape: true,
type: 'tl'
});
document.getElementById('tr').innerHTML = vml.draw({
radius: 10,
top: 5,
top_color: '#f00',
left: 10,
left_color: '#00f',
color: '#fff',
use_shape: false,
type: 'tr'
});
document.getElementById('bl').innerHTML = vml.draw({
radius: 10,
top: 1,
top_color: '#fc0',
left: 2,
left_color: '#0f0',
color: '#fff',
use_shape: false,
type: 'bl'
});
document.getElementById('br').innerHTML = vml.draw({
radius: 20,
top: 1,
top_color: '#fc0',
left: 10,
left_color: '#00f',
color: '#fff',
use_shape: false,
type: 'br'
});
</script>
</body>
</html>
\ No newline at end of file
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>
<script type="text/javascript" src="../js_src/common.js"></script>
<script type="text/javascript" src="../js_src/vml.js"></script>
<script type="text/javascript">
// try {
// if (!document.namespaces["v"])
// document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
// } catch(e) { }
</script>
<link rel="stylesheet" href="adapter_test.css" />
<style type="text/css">
.sample .vml {
top:-1px;
left:-1px;
/* display:block; */
margin:0;
padding:0;
}
#tl {
width:100px;
height:100px;
background:white;
}
</style>
</head>
<body>
<div id="rocon" class="sample">
<div id="tl"></div>
<div id="tr"></div>
<div id="bl"></div>
<div id="br"></div>
</div>
<div id="reference" class="sample"></div>
<script type="text/javascript">
vml.init();
document.getElementById('tl').innerHTML = vml.draw({
radius: 50,
width: 100,
height: 100,
top: 5,
top_color: '#f00',
left: 2,
left_color: '#0f0',
color: '#eee',
use_shape: true,
type: 'tl'
});
document.getElementById('tr').innerHTML = vml.draw({
radius: 10,
top: 5,
top_color: '#f00',
left: 10,
left_color: '#00f',
color: '#fff',
use_shape: false,
type: 'tr'
});
document.getElementById('bl').innerHTML = vml.draw({
radius: 10,
top: 1,
top_color: '#fc0',
left: 2,
left_color: '#0f0',
color: '#fff',
use_shape: false,
type: 'bl'
});
document.getElementById('br').innerHTML = vml.draw({
radius: 20,
top: 1,
top_color: '#fc0',
left: 10,
left_color: '#00f',
color: '#fff',
use_shape: false,
type: 'br'
});
</script>
</body>
</html>
\ No newline at end of file
|
sergeche/rocon
|
f73791d03dd966e09032dfc11644386ed1158fed
|
Added Eclipse project nature
|
diff --git a/.project b/.project
new file mode 100644
index 0000000..2dfc35c
--- /dev/null
+++ b/.project
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>rocon</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.wst.jsdt.core.jsNature</nature>
+ </natures>
+</projectDescription>
diff --git a/.settings/.jsdtscope b/.settings/.jsdtscope
new file mode 100644
index 0000000..1db689f
--- /dev/null
+++ b/.settings/.jsdtscope
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="js_src"/>
+ <classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
+</classpath>
diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.container b/.settings/org.eclipse.wst.jsdt.ui.superType.container
new file mode 100644
index 0000000..49c8cd4
--- /dev/null
+++ b/.settings/org.eclipse.wst.jsdt.ui.superType.container
@@ -0,0 +1 @@
+org.eclipse.wst.jsdt.launching.JRE_CONTAINER
\ No newline at end of file
diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.name b/.settings/org.eclipse.wst.jsdt.ui.superType.name
new file mode 100644
index 0000000..11006e2
--- /dev/null
+++ b/.settings/org.eclipse.wst.jsdt.ui.superType.name
@@ -0,0 +1 @@
+Global
\ No newline at end of file
|
fng/hanging-scm-poller-plugin
|
e661d39cb4566613e4164c908557fbea8d6be6c9
|
set version to 1.2-SNAPSHOT
|
diff --git a/pom.xml b/pom.xml
index 1512862..4d56a3c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,31 +1,31 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jvnet.hudson.plugins</groupId>
<artifactId>plugin</artifactId>
<version>1.376</version><!-- which version of Hudson is this plugin built against? -->
<relativePath>../pom.xml</relativePath>
</parent>
<groupId>name.wydler.hudson.plugin</groupId>
<artifactId>hanging-scm-poller-plugin</artifactId>
<name>Hanging SCM Poller Plugin</name>
<description>Is taking care of hanging SCM Poller Threads</description>
- <version>1.1</version>
+ <version>1.2-SNAPSHOT</version>
<packaging>hpi</packaging>
<!-- get every artifact through maven.glassfish.org, which proxies all the artifacts that we need -->
<repositories>
<repository>
<id>m.g.o-public</id>
<url>http://maven.glassfish.org/content/groups/public/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>m.g.o-public</id>
<url>http://maven.glassfish.org/content/groups/public/</url>
</pluginRepository>
</pluginRepositories>
</project>
|
fng/hanging-scm-poller-plugin
|
cf7ae999afb387631537a9bd0aeecea3e28f5928
|
set version to 1.1 for release
|
diff --git a/hanging-scm-poller-plugin.iml b/hanging-scm-poller-plugin.iml
index 4c673d8..8cc388c 100644
--- a/hanging-scm-poller-plugin.iml
+++ b/hanging-scm-poller-plugin.iml
@@ -1,171 +1,170 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/generated-sources/localizer" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target/classes" />
<excludeFolder url="file://$MODULE_DIR$/target/generated-sources/groovy-stubs" />
<excludeFolder url="file://$MODULE_DIR$/target/hanging-scm-poller-plugin" />
<excludeFolder url="file://$MODULE_DIR$/target/hudson-for-test" />
<excludeFolder url="file://$MODULE_DIR$/target/inject-tests" />
<excludeFolder url="file://$MODULE_DIR$/target/surefire-reports" />
<excludeFolder url="file://$MODULE_DIR$/target/test-classes" />
- <excludeFolder url="file://$MODULE_DIR$/target/work" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.main:hudson-core:1.376" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.main:remoting:1.376" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.main:cli:1.376" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.localizer:localizer:1.10" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:crypto-util:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-io:commons-io:1.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:jtidy:4aug2000r7-dev-hudson-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jruby.ext.posix:jna-posix:1.0.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke:trilead-putty-extension:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:trilead-ssh2:build212-hudson-5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:stapler-jelly:1.150" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:stapler:1.150" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-discovery:commons-discovery:0.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-logging:commons-logging:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-beanutils:commons-beanutils:1.8.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:json-lib:2.1-rev6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-collections:commons-collections:3.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-lang:commons-lang:2.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.sf.ezmorph:ezmorph:1.0.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet:tiger-types:1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.google.guava:guava:r06" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-fileupload:commons-fileupload:1.2.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.3.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:commons-jelly:1.1-hudson-20100305" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:commons-jexl:1.1-hudson-20090508" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.dom4j:dom4j:1.6.1-hudson-3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:stapler-adjunct-timeline:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.infradna.tool:bridge-method-annotation:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:annotation-indexer:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: args4j:args4j:2.0.16" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:task-reactor:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke:graph-layouter:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: antlr:antlr:2.7.6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:xstream:1.3.1-hudson-7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: xpp3:xpp3_min:1.1.4c" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jfree:jfreechart:1.0.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jfree:jcommon:1.0.12" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.ant:ant:1.8.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.ant:ant-launcher:1.8.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-digester:commons-digester:1.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.mail:mail:1.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:activation:1.1.1-hudson-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jaxen:jaxen:1.1-beta-11" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-jelly:commons-jelly-tags-fmt:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-jelly:commons-jelly-tags-xml:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:commons-jelly-tags-define:1.0.1-hudson-20071021" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.acegisecurity:acegi-security:1.0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-core:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-jdbc:1.2.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-beans:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-dao:1.2.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-context:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-codec:commons-codec:1.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: oro:oro:2.0.8" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: log4j:log4j:1.2.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.codehaus.groovy:groovy-all:1.6.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jline:jline:0.9.94" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-web:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: aopalliance:aopalliance:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-aop:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: xpp3:xpp3:1.1.4c" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:jstl:1.1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: logkit:logkit:1.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: avalon-framework:avalon-framework:4.1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:servlet-api:2.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sun.xml.txw2:txw2:20070624" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.winp:winp:1.14" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:memory-monitor:1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.dev.jna:jna:3.2.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.octo.captcha:jcaptcha-all:1.0-RC6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-pool:commons-pool:1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.codehaus.woodstox:wstx-asl:3.2.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: stax:stax-api:1.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:jmdns:3.1.6-hudson-2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sun.akuma:akuma:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.libpam4j:libpam4j:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.libzfs:libzfs:0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sun.solaris:embedded_su4j:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.sezpoz:sezpoz:1.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:jinterop-wmi:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.jinterop:jinterop-proxy:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.jinterop:j-interop:2.0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.jinterop:j-interopdeps:2.0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.samba.jcifs:jcifs:1.3.14-kohsuke-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:windows-remote-command:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.robust-http-client:robust-http-client:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: asm:asm-commons:2.2.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: asm:asm-tree:2.2.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: asm:asm:2.2.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke:access-modifier-annotation:1.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:hudson-test-harness:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:hudson-war:war-for-test:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:maven-plugin:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:maven-agent:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:maven-interceptor:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-core:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-settings:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-model:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.plexus:plexus-utils:1.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.plexus:plexus-container-default:1.0-alpha-9-stable-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: classworlds:classworlds:1.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-file:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-provider-api:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-parameter-documenter:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: slide:slide-webdavlib:2.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: commons-httpclient:commons-httpclient:3.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: de.zeigermann.xml:xml-im-exporter:1.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-http-lightweight:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-http-shared:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.reporting:maven-reporting-api:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.doxia:doxia-sink-api:1.0-alpha-10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-profile:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-artifact:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-repository-metadata:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-error-diagnostics:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-project:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-artifact-manager:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-registry:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-api:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-ssh-external:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-ssh-common:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.plexus:plexus-interactivity-api:1.0-alpha-4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-descriptor:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-monitor:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-ssh:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jcraft:jsch:0.1.27" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:maven2.1-interceptor:1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:maven-embedder:2.0.4-hudson-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-embedder:2.0.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:wagon-webdav:1.0-beta-2-hudson-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.plugins:subversion:1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.svnkit:svnkit:1.3.0-hudson-4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mortbay.jetty:jetty:6.1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mortbay.jetty:jetty-util:6.1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mortbay.jetty:servlet-api-2.5:6.1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.mock-javamail:mock-javamail:1.7" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:htmlunit:2.6-hudson-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: xalan:xalan:2.7.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: xalan:serializer:2.7.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:htmlunit-core-js:2.6-hudson-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: xerces:xercesImpl:2.9.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.sourceforge.nekohtml:nekohtml:1.9.13" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.sourceforge.cssparser:cssparser:0.9.5" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.w3c.css:sac:1.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:embedded-rhino-debugger:1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:netx:0.5-hudson-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.easymock:easymock:2.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:ui-samples-plugin:1.376" level="project" />
</component>
</module>
diff --git a/pom.xml b/pom.xml
index 08a5d93..1512862 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,31 +1,31 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jvnet.hudson.plugins</groupId>
<artifactId>plugin</artifactId>
<version>1.376</version><!-- which version of Hudson is this plugin built against? -->
<relativePath>../pom.xml</relativePath>
</parent>
<groupId>name.wydler.hudson.plugin</groupId>
<artifactId>hanging-scm-poller-plugin</artifactId>
<name>Hanging SCM Poller Plugin</name>
<description>Is taking care of hanging SCM Poller Threads</description>
- <version>1.1-SNAPSHOT</version>
+ <version>1.1</version>
<packaging>hpi</packaging>
<!-- get every artifact through maven.glassfish.org, which proxies all the artifacts that we need -->
<repositories>
<repository>
<id>m.g.o-public</id>
<url>http://maven.glassfish.org/content/groups/public/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>m.g.o-public</id>
<url>http://maven.glassfish.org/content/groups/public/</url>
</pluginRepository>
</pluginRepositories>
</project>
|
fng/hanging-scm-poller-plugin
|
d3593ab05372fe1960c85f3ee94e6bd3f34330e2
|
show found scm poller thread to each job. slightly change the pattern to finde the thread for a poller job
|
diff --git a/hanging-scm-poller-plugin.iml b/hanging-scm-poller-plugin.iml
index 8cc388c..4c673d8 100644
--- a/hanging-scm-poller-plugin.iml
+++ b/hanging-scm-poller-plugin.iml
@@ -1,170 +1,171 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/generated-sources/localizer" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target/classes" />
<excludeFolder url="file://$MODULE_DIR$/target/generated-sources/groovy-stubs" />
<excludeFolder url="file://$MODULE_DIR$/target/hanging-scm-poller-plugin" />
<excludeFolder url="file://$MODULE_DIR$/target/hudson-for-test" />
<excludeFolder url="file://$MODULE_DIR$/target/inject-tests" />
<excludeFolder url="file://$MODULE_DIR$/target/surefire-reports" />
<excludeFolder url="file://$MODULE_DIR$/target/test-classes" />
+ <excludeFolder url="file://$MODULE_DIR$/target/work" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.main:hudson-core:1.376" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.main:remoting:1.376" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.main:cli:1.376" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.localizer:localizer:1.10" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:crypto-util:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-io:commons-io:1.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:jtidy:4aug2000r7-dev-hudson-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jruby.ext.posix:jna-posix:1.0.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke:trilead-putty-extension:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:trilead-ssh2:build212-hudson-5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:stapler-jelly:1.150" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:stapler:1.150" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-discovery:commons-discovery:0.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-logging:commons-logging:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-beanutils:commons-beanutils:1.8.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:json-lib:2.1-rev6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-collections:commons-collections:3.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-lang:commons-lang:2.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.sf.ezmorph:ezmorph:1.0.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet:tiger-types:1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.google.guava:guava:r06" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-fileupload:commons-fileupload:1.2.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.3.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:commons-jelly:1.1-hudson-20100305" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:commons-jexl:1.1-hudson-20090508" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.dom4j:dom4j:1.6.1-hudson-3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:stapler-adjunct-timeline:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.infradna.tool:bridge-method-annotation:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:annotation-indexer:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: args4j:args4j:2.0.16" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:task-reactor:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke:graph-layouter:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: antlr:antlr:2.7.6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:xstream:1.3.1-hudson-7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: xpp3:xpp3_min:1.1.4c" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jfree:jfreechart:1.0.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jfree:jcommon:1.0.12" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.ant:ant:1.8.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.ant:ant-launcher:1.8.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-digester:commons-digester:1.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.mail:mail:1.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:activation:1.1.1-hudson-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jaxen:jaxen:1.1-beta-11" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-jelly:commons-jelly-tags-fmt:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-jelly:commons-jelly-tags-xml:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:commons-jelly-tags-define:1.0.1-hudson-20071021" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.acegisecurity:acegi-security:1.0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-core:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-jdbc:1.2.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-beans:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-dao:1.2.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-context:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-codec:commons-codec:1.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: oro:oro:2.0.8" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: log4j:log4j:1.2.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.codehaus.groovy:groovy-all:1.6.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jline:jline:0.9.94" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-web:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: aopalliance:aopalliance:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-aop:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: xpp3:xpp3:1.1.4c" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:jstl:1.1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: logkit:logkit:1.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: avalon-framework:avalon-framework:4.1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:servlet-api:2.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sun.xml.txw2:txw2:20070624" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.winp:winp:1.14" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:memory-monitor:1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.dev.jna:jna:3.2.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.octo.captcha:jcaptcha-all:1.0-RC6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-pool:commons-pool:1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.codehaus.woodstox:wstx-asl:3.2.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: stax:stax-api:1.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:jmdns:3.1.6-hudson-2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sun.akuma:akuma:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.libpam4j:libpam4j:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.libzfs:libzfs:0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sun.solaris:embedded_su4j:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.sezpoz:sezpoz:1.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:jinterop-wmi:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.jinterop:jinterop-proxy:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.jinterop:j-interop:2.0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.jinterop:j-interopdeps:2.0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.samba.jcifs:jcifs:1.3.14-kohsuke-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:windows-remote-command:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.robust-http-client:robust-http-client:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: asm:asm-commons:2.2.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: asm:asm-tree:2.2.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: asm:asm:2.2.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke:access-modifier-annotation:1.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:hudson-test-harness:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:hudson-war:war-for-test:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:maven-plugin:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:maven-agent:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:maven-interceptor:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-core:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-settings:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-model:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.plexus:plexus-utils:1.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.plexus:plexus-container-default:1.0-alpha-9-stable-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: classworlds:classworlds:1.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-file:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-provider-api:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-parameter-documenter:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: slide:slide-webdavlib:2.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: commons-httpclient:commons-httpclient:3.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: de.zeigermann.xml:xml-im-exporter:1.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-http-lightweight:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-http-shared:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.reporting:maven-reporting-api:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.doxia:doxia-sink-api:1.0-alpha-10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-profile:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-artifact:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-repository-metadata:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-error-diagnostics:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-project:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-artifact-manager:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-registry:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-api:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-ssh-external:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-ssh-common:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.plexus:plexus-interactivity-api:1.0-alpha-4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-descriptor:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-monitor:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-ssh:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jcraft:jsch:0.1.27" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:maven2.1-interceptor:1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:maven-embedder:2.0.4-hudson-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-embedder:2.0.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:wagon-webdav:1.0-beta-2-hudson-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.plugins:subversion:1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.svnkit:svnkit:1.3.0-hudson-4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mortbay.jetty:jetty:6.1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mortbay.jetty:jetty-util:6.1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mortbay.jetty:servlet-api-2.5:6.1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.mock-javamail:mock-javamail:1.7" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:htmlunit:2.6-hudson-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: xalan:xalan:2.7.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: xalan:serializer:2.7.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:htmlunit-core-js:2.6-hudson-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: xerces:xercesImpl:2.9.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.sourceforge.nekohtml:nekohtml:1.9.13" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.sourceforge.cssparser:cssparser:0.9.5" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.w3c.css:sac:1.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:embedded-rhino-debugger:1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:netx:0.5-hudson-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.easymock:easymock:2.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:ui-samples-plugin:1.376" level="project" />
</component>
</module>
diff --git a/src/main/java/name/wydler/hudson/plugin/HangingSCMPollingTrigger.java b/src/main/java/name/wydler/hudson/plugin/HangingSCMPollingTrigger.java
index e33fde6..fecea2f 100644
--- a/src/main/java/name/wydler/hudson/plugin/HangingSCMPollingTrigger.java
+++ b/src/main/java/name/wydler/hudson/plugin/HangingSCMPollingTrigger.java
@@ -1,88 +1,130 @@
package name.wydler.hudson.plugin;
import hudson.Extension;
import hudson.model.ManagementLink;
import hudson.triggers.SCMTrigger;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Extension
public class HangingSCMPollingTrigger extends ManagementLink {
@Override
public String getIconFileName() {
return "orange-square.gif";
}
public String getDisplayName() {
return "Hanging SCM Polling Triggers";
}
@Override
public String getUrlName() {
return "hangingScmPollingTriggers";
}
@Override
public String getDescription() {
return "Display and interrupt hanging SCM polling triggers";
}
public Long getStarvationThreshold() {
return SCMTrigger.STARVATION_THRESHOLD;
}
public void doInterrupt(StaplerRequest req, StaplerResponse rsp, @QueryParameter(value = "job") String job) throws IOException, ServletException {
SCMTrigger.Runner runner = getHangingRunnerForJob(job);
Thread thread = getThreadForHangingScmPoller(job);
if (runner == null || thread == null) {
throw new RuntimeException("No hanging SCM Polling runner found for job " + job);
} else {
thread.interrupt();
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
}
rsp.forwardToPreviousPage(req);
}
//TODO return functionaljava Option to avoid null
private SCMTrigger.Runner getHangingRunnerForJob(String job) {
- for (SCMTrigger.Runner runner : getHangingScmTriggerRunners()) {
- if (runner.getTarget().getName().equals(job)) {
- return runner;
+ for (RunnerWithThreads runner : getHangingScmTriggerRunners()) {
+ if (runner.getRunner().getTarget().getName().equals(job)) {
+ return runner.getRunner();
}
}
return null;
}
//TODO return functionaljava Option to avoid null
private Thread getThreadForHangingScmPoller(String job) {
for (Thread thread : Thread.getAllStackTraces().keySet()) {
String threadName = thread.getName();
- if (threadName.startsWith("SCM polling for") && threadName.endsWith("[" + job + "]")) {
+ if (threadName.startsWith("SCM polling for") && threadName.contains(job)) {
return thread;
}
}
return null;
}
+ private List<Thread> getThreadsForHangingScmRunner(String job) {
+ ArrayList<Thread> threads = new ArrayList<Thread>();
+ for (Thread thread : Thread.getAllStackTraces().keySet()) {
+ String threadName = thread.getName();
+ if (threadName.startsWith("SCM polling for") && threadName.contains(job)) {
+ threads.add(thread);
+ }
+ }
+ return threads;
+ }
+
- public List<SCMTrigger.Runner> getHangingScmTriggerRunners() {
+
+ public List<RunnerWithThreads> getHangingScmTriggerRunners() {
SCMTrigger.DescriptorImpl scmTriggerDescriptor = (SCMTrigger.DescriptorImpl) SCMTrigger.all().find(SCMTrigger.class);
- return scmTriggerDescriptor.getRunners();
+ List<SCMTrigger.Runner> runners = scmTriggerDescriptor.getRunners();
+
+ ArrayList<RunnerWithThreads> runnerWithThreadsList = new ArrayList<RunnerWithThreads>();
+ for (SCMTrigger.Runner runner : runners) {
+ String job = runner.getTarget().getName();
+ runnerWithThreadsList.add(new RunnerWithThreads(runner, getThreadsForHangingScmRunner(job)));
+ }
+ return runnerWithThreadsList;
}
//is called to map to any url below hangingScmPollingTriggers
//e.g. hangingScmPollingTriggers/x -> token = x
public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
System.out.println("HangingSCMPollingTrigger.getDynamic token: " + token);
return null;
}
+
+ public class RunnerWithThreads{
+ private final SCMTrigger.Runner runner;
+ private final List<Thread> threads;
+
+ public RunnerWithThreads(SCMTrigger.Runner runner, List<Thread> threads) {
+ this.runner = runner;
+ this.threads = threads;
+ }
+
+ public SCMTrigger.Runner getRunner() {
+ return runner;
+ }
+
+ public List<Thread> getThreads() {
+ return threads;
+ }
+ }
}
diff --git a/src/main/resources/name/wydler/hudson/plugin/HangingSCMPollingTrigger/index.jelly b/src/main/resources/name/wydler/hudson/plugin/HangingSCMPollingTrigger/index.jelly
index 06c65dc..28cc5b2 100644
--- a/src/main/resources/name/wydler/hudson/plugin/HangingSCMPollingTrigger/index.jelly
+++ b/src/main/resources/name/wydler/hudson/plugin/HangingSCMPollingTrigger/index.jelly
@@ -1,39 +1,45 @@
<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define" xmlns:l="/lib/layout"
xmlns:t="/lib/hudson" xmlns:f="/lib/form" xmlns:i="jelly:fmt">
<l:layout title="${it.displayName}">
<l:header/>
<l:side-panel>
<l:tasks>
<l:task icon="images/24x24/up.gif" href=".." title="${%Back to List}"/>
</l:tasks>
</l:side-panel>
<l:main-panel>
<p>${%The following polling activities exceed the} ${%StarvationThreshold}</p>
<p>${%StarvationThreshold} = ${it.starvationThreshold}</p>
<table id="runners" class="sortable pane bigtable">
<tr>
<th initialSortDir="down">${%Job}</th>
<th>${%Log}</th>
<th>${%Running for}</th>
<th>${%Interrupt}</th>
+ <th>${%Threads}</th>
</tr>
- <j:forEach var="runner" items="${it.HangingScmTriggerRunners}">
+ <j:forEach var="runnerWithThreads" items="${it.HangingScmTriggerRunners}">
<tr>
<td>
- <a href="${rootURL}/${runner.target.url}">${runner.target.displayName}</a>
+ <a href="${rootURL}/${runnerWithThreads.runner.target.url}">${runnerWithThreads.runner.target.displayName}</a>
</td>
<td>
- <a href="${rootURL}/${runner.target.url}scmPollLog/">${runner.target.displayName} Polling Log</a>
+ <a href="${rootURL}/${runnerWithThreads.runner.target.url}scmPollLog/">${runnerWithThreads.runner.target.displayName} Polling Log</a>
</td>
<td>
- ${runner.duration}
+ ${runnerWithThreads.runner.duration}
</td>
<td>
- <a href="interrupt?job=${runner.target.name}">${%Interrupt}</a>
+ <a href="interrupt?job=${runnerWithThreads.runner.target.name}">${%Interrupt}</a>
+ </td>
+ <td>
+ <j:forEach var="t" items="${runnerWithThreads.threads}">
+ <p>${t.name}</p>
+ </j:forEach>
</td>
</tr>
</j:forEach>
</table>
</l:main-panel>
</l:layout>
</j:jelly>
\ No newline at end of file
|
fng/hanging-scm-poller-plugin
|
1881527f7a19dc24f06c73142a62b4db652d1630
|
change to version 1.1-SNAPSHOT
|
diff --git a/.idea/runConfigurations/hanging_scm_poller_plugin__clean_package_source_jar_.xml b/.idea/runConfigurations/hanging_scm_poller_plugin__clean_package_source_jar_.xml
new file mode 100644
index 0000000..e009969
--- /dev/null
+++ b/.idea/runConfigurations/hanging_scm_poller_plugin__clean_package_source_jar_.xml
@@ -0,0 +1,50 @@
+<component name="ProjectRunConfigurationManager">
+ <configuration default="false" name="hanging-scm-poller-plugin [clean package source:jar]" type="MavenRunConfiguration" factoryName="Maven">
+ <MavenSettings>
+ <option name="myGeneralSettings">
+ <MavenGeneralSettings>
+ <option name="checksumPolicy" value="FAIL" />
+ <option name="failureBehavior" value="FAST" />
+ <option name="mavenHome" value="" />
+ <option name="mavenSettingsFile" value="" />
+ <option name="nonRecursive" value="false" />
+ <option name="overridenLocalRepository" value="" />
+ <option name="pluginUpdatePolicy" value="DO_NOT_UPDATE" />
+ <option name="printErrorStackTraces" value="false" />
+ <option name="snapshotUpdatePolicy" value="ALWAYS_UPDATE" />
+ <option name="usePluginRegistry" value="false" />
+ <option name="workOffline" value="false" />
+ </MavenGeneralSettings>
+ </option>
+ <option name="myRunnerSettings">
+ <MavenRunnerSettings>
+ <option name="jreName" value="1.6" />
+ <option name="mavenProperties">
+ <map />
+ </option>
+ <option name="runMavenInBackground" value="true" />
+ <option name="skipTests" value="false" />
+ <option name="vmOptions" value="" />
+ </MavenRunnerSettings>
+ </option>
+ <option name="myRunnerParameters">
+ <MavenRunnerParameters>
+ <option name="goals">
+ <list>
+ <option value="clean" />
+ <option value="package" />
+ <option value="source:jar" />
+ </list>
+ </option>
+ <option name="profiles">
+ <set />
+ </option>
+ <option name="workingDirPath" value="$PROJECT_DIR$" />
+ </MavenRunnerParameters>
+ </option>
+ </MavenSettings>
+ <RunnerSettings RunnerId="Run" />
+ <ConfigurationWrapper RunnerId="Run" />
+ <method />
+ </configuration>
+</component>
\ No newline at end of file
diff --git a/hanging-scm-poller-plugin.iml b/hanging-scm-poller-plugin.iml
index 4c673d8..8cc388c 100644
--- a/hanging-scm-poller-plugin.iml
+++ b/hanging-scm-poller-plugin.iml
@@ -1,171 +1,170 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/target/generated-sources/localizer" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target/classes" />
<excludeFolder url="file://$MODULE_DIR$/target/generated-sources/groovy-stubs" />
<excludeFolder url="file://$MODULE_DIR$/target/hanging-scm-poller-plugin" />
<excludeFolder url="file://$MODULE_DIR$/target/hudson-for-test" />
<excludeFolder url="file://$MODULE_DIR$/target/inject-tests" />
<excludeFolder url="file://$MODULE_DIR$/target/surefire-reports" />
<excludeFolder url="file://$MODULE_DIR$/target/test-classes" />
- <excludeFolder url="file://$MODULE_DIR$/target/work" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.main:hudson-core:1.376" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.main:remoting:1.376" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.main:cli:1.376" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.localizer:localizer:1.10" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:crypto-util:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-io:commons-io:1.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:jtidy:4aug2000r7-dev-hudson-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jruby.ext.posix:jna-posix:1.0.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke:trilead-putty-extension:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:trilead-ssh2:build212-hudson-5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:stapler-jelly:1.150" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:stapler:1.150" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-discovery:commons-discovery:0.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-logging:commons-logging:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-beanutils:commons-beanutils:1.8.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:json-lib:2.1-rev6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-collections:commons-collections:3.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-lang:commons-lang:2.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.sf.ezmorph:ezmorph:1.0.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet:tiger-types:1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.google.guava:guava:r06" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-fileupload:commons-fileupload:1.2.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.3.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:commons-jelly:1.1-hudson-20100305" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:commons-jexl:1.1-hudson-20090508" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.dom4j:dom4j:1.6.1-hudson-3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:stapler-adjunct-timeline:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.infradna.tool:bridge-method-annotation:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:annotation-indexer:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: args4j:args4j:2.0.16" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:task-reactor:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke:graph-layouter:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: antlr:antlr:2.7.6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:xstream:1.3.1-hudson-7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: xpp3:xpp3_min:1.1.4c" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jfree:jfreechart:1.0.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jfree:jcommon:1.0.12" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.ant:ant:1.8.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.ant:ant-launcher:1.8.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-digester:commons-digester:1.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.mail:mail:1.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:activation:1.1.1-hudson-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jaxen:jaxen:1.1-beta-11" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-jelly:commons-jelly-tags-fmt:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-jelly:commons-jelly-tags-xml:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:commons-jelly-tags-define:1.0.1-hudson-20071021" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.acegisecurity:acegi-security:1.0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-core:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-jdbc:1.2.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-beans:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-dao:1.2.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-context:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-codec:commons-codec:1.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: oro:oro:2.0.8" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: log4j:log4j:1.2.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.codehaus.groovy:groovy-all:1.6.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jline:jline:0.9.94" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-web:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: aopalliance:aopalliance:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-aop:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: xpp3:xpp3:1.1.4c" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:jstl:1.1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: logkit:logkit:1.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: avalon-framework:avalon-framework:4.1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:servlet-api:2.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sun.xml.txw2:txw2:20070624" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.winp:winp:1.14" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:memory-monitor:1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.dev.jna:jna:3.2.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.octo.captcha:jcaptcha-all:1.0-RC6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-pool:commons-pool:1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.codehaus.woodstox:wstx-asl:3.2.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: stax:stax-api:1.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:jmdns:3.1.6-hudson-2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sun.akuma:akuma:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.libpam4j:libpam4j:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.libzfs:libzfs:0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sun.solaris:embedded_su4j:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.sezpoz:sezpoz:1.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:jinterop-wmi:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.jinterop:jinterop-proxy:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.jinterop:j-interop:2.0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.jinterop:j-interopdeps:2.0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.samba.jcifs:jcifs:1.3.14-kohsuke-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:windows-remote-command:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.robust-http-client:robust-http-client:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: asm:asm-commons:2.2.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: asm:asm-tree:2.2.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: asm:asm:2.2.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke:access-modifier-annotation:1.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:hudson-test-harness:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:hudson-war:war-for-test:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:maven-plugin:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:maven-agent:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:maven-interceptor:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-core:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-settings:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-model:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.plexus:plexus-utils:1.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.plexus:plexus-container-default:1.0-alpha-9-stable-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: classworlds:classworlds:1.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-file:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-provider-api:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-parameter-documenter:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: slide:slide-webdavlib:2.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: commons-httpclient:commons-httpclient:3.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: de.zeigermann.xml:xml-im-exporter:1.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-http-lightweight:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-http-shared:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.reporting:maven-reporting-api:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.doxia:doxia-sink-api:1.0-alpha-10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-profile:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-artifact:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-repository-metadata:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-error-diagnostics:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-project:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-artifact-manager:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-registry:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-api:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-ssh-external:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-ssh-common:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.plexus:plexus-interactivity-api:1.0-alpha-4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-descriptor:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-monitor:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-ssh:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jcraft:jsch:0.1.27" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:maven2.1-interceptor:1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:maven-embedder:2.0.4-hudson-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-embedder:2.0.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:wagon-webdav:1.0-beta-2-hudson-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.plugins:subversion:1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.svnkit:svnkit:1.3.0-hudson-4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mortbay.jetty:jetty:6.1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mortbay.jetty:jetty-util:6.1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mortbay.jetty:servlet-api-2.5:6.1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.mock-javamail:mock-javamail:1.7" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:htmlunit:2.6-hudson-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: xalan:xalan:2.7.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: xalan:serializer:2.7.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:htmlunit-core-js:2.6-hudson-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: xerces:xercesImpl:2.9.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.sourceforge.nekohtml:nekohtml:1.9.13" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.sourceforge.cssparser:cssparser:0.9.5" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.w3c.css:sac:1.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:embedded-rhino-debugger:1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:netx:0.5-hudson-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.easymock:easymock:2.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:ui-samples-plugin:1.376" level="project" />
</component>
</module>
diff --git a/pom.xml b/pom.xml
index d00172a..08a5d93 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,31 +1,31 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jvnet.hudson.plugins</groupId>
<artifactId>plugin</artifactId>
<version>1.376</version><!-- which version of Hudson is this plugin built against? -->
<relativePath>../pom.xml</relativePath>
</parent>
<groupId>name.wydler.hudson.plugin</groupId>
<artifactId>hanging-scm-poller-plugin</artifactId>
<name>Hanging SCM Poller Plugin</name>
<description>Is taking care of hanging SCM Poller Threads</description>
- <version>1.0</version>
+ <version>1.1-SNAPSHOT</version>
<packaging>hpi</packaging>
<!-- get every artifact through maven.glassfish.org, which proxies all the artifacts that we need -->
<repositories>
<repository>
<id>m.g.o-public</id>
<url>http://maven.glassfish.org/content/groups/public/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>m.g.o-public</id>
<url>http://maven.glassfish.org/content/groups/public/</url>
</pluginRepository>
</pluginRepositories>
</project>
|
fng/hanging-scm-poller-plugin
|
aeff2054ae9780bd8136e48c0c50d28aee77a82c
|
change to version 1.0
|
diff --git a/pom.xml b/pom.xml
index d727e0f..d00172a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,31 +1,31 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jvnet.hudson.plugins</groupId>
<artifactId>plugin</artifactId>
<version>1.376</version><!-- which version of Hudson is this plugin built against? -->
<relativePath>../pom.xml</relativePath>
</parent>
<groupId>name.wydler.hudson.plugin</groupId>
<artifactId>hanging-scm-poller-plugin</artifactId>
<name>Hanging SCM Poller Plugin</name>
<description>Is taking care of hanging SCM Poller Threads</description>
- <version>1.0-SNAPSHOT</version>
+ <version>1.0</version>
<packaging>hpi</packaging>
<!-- get every artifact through maven.glassfish.org, which proxies all the artifacts that we need -->
<repositories>
<repository>
<id>m.g.o-public</id>
<url>http://maven.glassfish.org/content/groups/public/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>m.g.o-public</id>
<url>http://maven.glassfish.org/content/groups/public/</url>
</pluginRepository>
</pluginRepositories>
</project>
|
fng/hanging-scm-poller-plugin
|
515be96cf046573fbef8e96c959dbbbe1e10380d
|
the plugin
|
diff --git a/.idea/runConfigurations/Debug.xml b/.idea/runConfigurations/Debug.xml
new file mode 100644
index 0000000..991ee78
--- /dev/null
+++ b/.idea/runConfigurations/Debug.xml
@@ -0,0 +1,16 @@
+<component name="ProjectRunConfigurationManager">
+ <configuration default="false" name="Debug" type="Remote" factoryName="Remote">
+ <option name="USE_SOCKET_TRANSPORT" value="true" />
+ <option name="SERVER_MODE" value="false" />
+ <option name="SHMEM_ADDRESS" value="javadebug" />
+ <option name="HOST" value="localhost" />
+ <option name="PORT" value="8000" />
+ <RunnerSettings RunnerId="Debug">
+ <option name="DEBUG_PORT" value="8000" />
+ <option name="TRANSPORT" value="0" />
+ <option name="LOCAL" value="false" />
+ </RunnerSettings>
+ <ConfigurationWrapper RunnerId="Debug" />
+ <method />
+ </configuration>
+</component>
\ No newline at end of file
diff --git a/.idea/runConfigurations/hpi_run__http___localhost_8090_.xml b/.idea/runConfigurations/hpi_run__http___localhost_8090_.xml
new file mode 100644
index 0000000..d60d277
--- /dev/null
+++ b/.idea/runConfigurations/hpi_run__http___localhost_8090_.xml
@@ -0,0 +1,48 @@
+<component name="ProjectRunConfigurationManager">
+ <configuration default="false" name="hpi:run [http://localhost:8090]" type="MavenRunConfiguration" factoryName="Maven">
+ <MavenSettings>
+ <option name="myGeneralSettings">
+ <MavenGeneralSettings>
+ <option name="checksumPolicy" value="FAIL" />
+ <option name="failureBehavior" value="FAST" />
+ <option name="mavenHome" value="" />
+ <option name="mavenSettingsFile" value="" />
+ <option name="nonRecursive" value="false" />
+ <option name="overridenLocalRepository" value="" />
+ <option name="pluginUpdatePolicy" value="DO_NOT_UPDATE" />
+ <option name="printErrorStackTraces" value="false" />
+ <option name="snapshotUpdatePolicy" value="ALWAYS_UPDATE" />
+ <option name="usePluginRegistry" value="false" />
+ <option name="workOffline" value="false" />
+ </MavenGeneralSettings>
+ </option>
+ <option name="myRunnerSettings">
+ <MavenRunnerSettings>
+ <option name="jreName" value="1.6" />
+ <option name="mavenProperties">
+ <map />
+ </option>
+ <option name="runMavenInBackground" value="true" />
+ <option name="skipTests" value="false" />
+ <option name="vmOptions" value="-Djetty.port=8090 -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=8000,suspend=n -Dhudson.triggers.SCMTrigger.starvationThreshold=1000" />
+ </MavenRunnerSettings>
+ </option>
+ <option name="myRunnerParameters">
+ <MavenRunnerParameters>
+ <option name="goals">
+ <list>
+ <option value="org.jvnet.hudson.tools:maven-hpi-plugin:1.54:run" />
+ </list>
+ </option>
+ <option name="profiles">
+ <set />
+ </option>
+ <option name="workingDirPath" value="$PROJECT_DIR$" />
+ </MavenRunnerParameters>
+ </option>
+ </MavenSettings>
+ <RunnerSettings RunnerId="Run" />
+ <ConfigurationWrapper RunnerId="Run" />
+ <method />
+ </configuration>
+</component>
\ No newline at end of file
diff --git a/hanging-scm-poller-plugin.iml b/hanging-scm-poller-plugin.iml
index c649010..4c673d8 100644
--- a/hanging-scm-poller-plugin.iml
+++ b/hanging-scm-poller-plugin.iml
@@ -1,164 +1,171 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5" inherit-compiler-output="false">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
- <exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" isTestSource="false" />
- <excludeFolder url="file://$MODULE_DIR$/target" />
+ <sourceFolder url="file://$MODULE_DIR$/target/generated-sources/localizer" isTestSource="false" />
+ <excludeFolder url="file://$MODULE_DIR$/target/classes" />
+ <excludeFolder url="file://$MODULE_DIR$/target/generated-sources/groovy-stubs" />
+ <excludeFolder url="file://$MODULE_DIR$/target/hanging-scm-poller-plugin" />
+ <excludeFolder url="file://$MODULE_DIR$/target/hudson-for-test" />
+ <excludeFolder url="file://$MODULE_DIR$/target/inject-tests" />
+ <excludeFolder url="file://$MODULE_DIR$/target/surefire-reports" />
+ <excludeFolder url="file://$MODULE_DIR$/target/test-classes" />
+ <excludeFolder url="file://$MODULE_DIR$/target/work" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.main:hudson-core:1.376" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.main:remoting:1.376" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.main:cli:1.376" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.localizer:localizer:1.10" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:crypto-util:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-io:commons-io:1.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:jtidy:4aug2000r7-dev-hudson-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jruby.ext.posix:jna-posix:1.0.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke:trilead-putty-extension:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:trilead-ssh2:build212-hudson-5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:stapler-jelly:1.150" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:stapler:1.150" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-discovery:commons-discovery:0.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-logging:commons-logging:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-beanutils:commons-beanutils:1.8.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:json-lib:2.1-rev6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-collections:commons-collections:3.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-lang:commons-lang:2.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.sf.ezmorph:ezmorph:1.0.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet:tiger-types:1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.google.guava:guava:r06" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-fileupload:commons-fileupload:1.2.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.3.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:commons-jelly:1.1-hudson-20100305" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:commons-jexl:1.1-hudson-20090508" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson.dom4j:dom4j:1.6.1-hudson-3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.stapler:stapler-adjunct-timeline:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.infradna.tool:bridge-method-annotation:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:annotation-indexer:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: args4j:args4j:2.0.16" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:task-reactor:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke:graph-layouter:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: antlr:antlr:2.7.6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:xstream:1.3.1-hudson-7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: xpp3:xpp3_min:1.1.4c" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jfree:jfreechart:1.0.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jfree:jcommon:1.0.12" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.ant:ant:1.8.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.apache.ant:ant-launcher:1.8.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-digester:commons-digester:1.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.mail:mail:1.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:activation:1.1.1-hudson-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jaxen:jaxen:1.1-beta-11" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-jelly:commons-jelly-tags-fmt:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-jelly:commons-jelly-tags-xml:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:commons-jelly-tags-define:1.0.1-hudson-20071021" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.acegisecurity:acegi-security:1.0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-core:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-jdbc:1.2.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-beans:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-dao:1.2.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-context:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-codec:commons-codec:1.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: oro:oro:2.0.8" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: log4j:log4j:1.2.9" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.codehaus.groovy:groovy-all:1.6.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: jline:jline:0.9.94" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-web:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: aopalliance:aopalliance:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.springframework:spring-aop:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: xpp3:xpp3:1.1.4c" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:jstl:1.1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: logkit:logkit:1.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: avalon-framework:avalon-framework:4.1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:servlet-api:2.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sun.xml.txw2:txw2:20070624" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.winp:winp:1.14" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:memory-monitor:1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.dev.jna:jna:3.2.4" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.octo.captcha:jcaptcha-all:1.0-RC6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-pool:commons-pool:1.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.codehaus.woodstox:wstx-asl:3.2.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: stax:stax-api:1.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:jmdns:3.1.6-hudson-2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sun.akuma:akuma:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.libpam4j:libpam4j:1.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.libzfs:libzfs:0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.sun.solaris:embedded_su4j:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.java.sezpoz:sezpoz:1.7" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:jinterop-wmi:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.jinterop:jinterop-proxy:1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.jinterop:j-interop:2.0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke.jinterop:j-interopdeps:2.0.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.samba.jcifs:jcifs:1.3.14-kohsuke-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.hudson:windows-remote-command:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.jvnet.robust-http-client:robust-http-client:1.0" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: asm:asm-commons:2.2.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: asm:asm-tree:2.2.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: asm:asm:2.2.3" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.kohsuke:access-modifier-annotation:1.0" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:hudson-test-harness:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:hudson-war:war-for-test:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:maven-plugin:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:maven-agent:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:maven-interceptor:1.376" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-core:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-settings:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-model:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.plexus:plexus-utils:1.5.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.plexus:plexus-container-default:1.0-alpha-9-stable-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: classworlds:classworlds:1.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-file:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-provider-api:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-parameter-documenter:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: slide:slide-webdavlib:2.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: commons-httpclient:commons-httpclient:3.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: de.zeigermann.xml:xml-im-exporter:1.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-http-lightweight:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-http-shared:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.reporting:maven-reporting-api:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.doxia:doxia-sink-api:1.0-alpha-10" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-profile:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-artifact:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-repository-metadata:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-error-diagnostics:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-project:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-artifact-manager:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-registry:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-api:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-ssh-external:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-ssh-common:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.codehaus.plexus:plexus-interactivity-api:1.0-alpha-4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-plugin-descriptor:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-monitor:2.0.9" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven.wagon:wagon-ssh:1.0-beta-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: com.jcraft:jsch:0.1.27" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:maven2.1-interceptor:1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:maven-embedder:2.0.4-hudson-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.apache.maven:maven-embedder:2.0.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:wagon-webdav:1.0-beta-2-hudson-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.plugins:subversion:1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.svnkit:svnkit:1.3.0-hudson-4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mortbay.jetty:jetty:6.1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mortbay.jetty:jetty-util:6.1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.mortbay.jetty:servlet-api-2.5:6.1.11" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.mock-javamail:mock-javamail:1.7" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:htmlunit:2.6-hudson-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: xalan:xalan:2.7.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: xalan:serializer:2.7.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:htmlunit-core-js:2.6-hudson-1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: xerces:xercesImpl:2.9.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.sourceforge.nekohtml:nekohtml:1.9.13" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: net.sourceforge.cssparser:cssparser:0.9.5" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.w3c.css:sac:1.3" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:embedded-rhino-debugger:1.2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson:netx:0.5-hudson-2" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.easymock:easymock:2.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.jvnet.hudson.main:ui-samples-plugin:1.376" level="project" />
</component>
</module>
diff --git a/src/main/java/name/wydler/hudson/plugin/HangingSCMPollingTrigger.java b/src/main/java/name/wydler/hudson/plugin/HangingSCMPollingTrigger.java
new file mode 100644
index 0000000..e33fde6
--- /dev/null
+++ b/src/main/java/name/wydler/hudson/plugin/HangingSCMPollingTrigger.java
@@ -0,0 +1,88 @@
+package name.wydler.hudson.plugin;
+
+import hudson.Extension;
+import hudson.model.ManagementLink;
+import hudson.triggers.SCMTrigger;
+import org.kohsuke.stapler.QueryParameter;
+import org.kohsuke.stapler.StaplerRequest;
+import org.kohsuke.stapler.StaplerResponse;
+
+import javax.servlet.ServletException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+@Extension
+public class HangingSCMPollingTrigger extends ManagementLink {
+ @Override
+ public String getIconFileName() {
+ return "orange-square.gif";
+ }
+
+ public String getDisplayName() {
+ return "Hanging SCM Polling Triggers";
+ }
+
+ @Override
+ public String getUrlName() {
+ return "hangingScmPollingTriggers";
+ }
+
+ @Override
+ public String getDescription() {
+ return "Display and interrupt hanging SCM polling triggers";
+ }
+
+ public Long getStarvationThreshold() {
+ return SCMTrigger.STARVATION_THRESHOLD;
+ }
+
+
+ public void doInterrupt(StaplerRequest req, StaplerResponse rsp, @QueryParameter(value = "job") String job) throws IOException, ServletException {
+ SCMTrigger.Runner runner = getHangingRunnerForJob(job);
+ Thread thread = getThreadForHangingScmPoller(job);
+ if (runner == null || thread == null) {
+ throw new RuntimeException("No hanging SCM Polling runner found for job " + job);
+ } else {
+ thread.interrupt();
+ }
+
+ rsp.forwardToPreviousPage(req);
+
+ }
+
+ //TODO return functionaljava Option to avoid null
+ private SCMTrigger.Runner getHangingRunnerForJob(String job) {
+ for (SCMTrigger.Runner runner : getHangingScmTriggerRunners()) {
+ if (runner.getTarget().getName().equals(job)) {
+ return runner;
+ }
+ }
+ return null;
+ }
+
+ //TODO return functionaljava Option to avoid null
+ private Thread getThreadForHangingScmPoller(String job) {
+ for (Thread thread : Thread.getAllStackTraces().keySet()) {
+ String threadName = thread.getName();
+ if (threadName.startsWith("SCM polling for") && threadName.endsWith("[" + job + "]")) {
+ return thread;
+ }
+ }
+ return null;
+ }
+
+
+ public List<SCMTrigger.Runner> getHangingScmTriggerRunners() {
+ SCMTrigger.DescriptorImpl scmTriggerDescriptor = (SCMTrigger.DescriptorImpl) SCMTrigger.all().find(SCMTrigger.class);
+ return scmTriggerDescriptor.getRunners();
+ }
+
+ //is called to map to any url below hangingScmPollingTriggers
+ //e.g. hangingScmPollingTriggers/x -> token = x
+ public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
+ System.out.println("HangingSCMPollingTrigger.getDynamic token: " + token);
+ return null;
+ }
+}
diff --git a/src/main/java/name/wydler/hudson/plugin/HelloWorldBuilder.java b/src/main/java/name/wydler/hudson/plugin/HelloWorldBuilder.java
deleted file mode 100644
index 571b33f..0000000
--- a/src/main/java/name/wydler/hudson/plugin/HelloWorldBuilder.java
+++ /dev/null
@@ -1,139 +0,0 @@
-package name.wydler.hudson.plugin;
-import hudson.Launcher;
-import hudson.Extension;
-import hudson.util.FormValidation;
-import hudson.model.AbstractBuild;
-import hudson.model.BuildListener;
-import hudson.model.AbstractProject;
-import hudson.tasks.Builder;
-import hudson.tasks.BuildStepDescriptor;
-import net.sf.json.JSONObject;
-import org.kohsuke.stapler.DataBoundConstructor;
-import org.kohsuke.stapler.StaplerRequest;
-import org.kohsuke.stapler.QueryParameter;
-
-import javax.servlet.ServletException;
-import java.io.IOException;
-
-/**
- * Sample {@link Builder}.
- *
- * <p>
- * When the user configures the project and enables this builder,
- * {@link DescriptorImpl#newInstance(StaplerRequest)} is invoked
- * and a new {@link HelloWorldBuilder} is created. The created
- * instance is persisted to the project configuration XML by using
- * XStream, so this allows you to use instance fields (like {@link #name})
- * to remember the configuration.
- *
- * <p>
- * When a build is performed, the {@link #perform(AbstractBuild, Launcher, BuildListener)} method
- * will be invoked.
- *
- * @author Kohsuke Kawaguchi
- */
-public class HelloWorldBuilder extends Builder {
-
- private final String name;
-
- // Fields in config.jelly must match the parameter names in the "DataBoundConstructor"
- @DataBoundConstructor
- public HelloWorldBuilder(String name) {
- this.name = name;
- }
-
- /**
- * We'll use this from the <tt>config.jelly</tt>.
- */
- public String getName() {
- return name;
- }
-
- @Override
- public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
- // this is where you 'build' the project
- // since this is a dummy, we just say 'hello world' and call that a build
-
- // this also shows how you can consult the global configuration of the builder
- if(getDescriptor().useFrench())
- listener.getLogger().println("Bonjour, "+name+"!");
- else
- listener.getLogger().println("Hello, "+name+"!");
- return true;
- }
-
- // overrided for better type safety.
- // if your plugin doesn't really define any property on Descriptor,
- // you don't have to do this.
- @Override
- public DescriptorImpl getDescriptor() {
- return (DescriptorImpl)super.getDescriptor();
- }
-
- /**
- * Descriptor for {@link HelloWorldBuilder}. Used as a singleton.
- * The class is marked as public so that it can be accessed from views.
- *
- * <p>
- * See <tt>views/hudson/plugins/hello_world/HelloWorldBuilder/*.jelly</tt>
- * for the actual HTML fragment for the configuration screen.
- */
- @Extension // this marker indicates Hudson that this is an implementation of an extension point.
- public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
- /**
- * To persist global configuration information,
- * simply store it in a field and call save().
- *
- * <p>
- * If you don't want fields to be persisted, use <tt>transient</tt>.
- */
- private boolean useFrench;
-
- /**
- * Performs on-the-fly validation of the form field 'name'.
- *
- * @param value
- * This parameter receives the value that the user has typed.
- * @return
- * Indicates the outcome of the validation. This is sent to the browser.
- */
- public FormValidation doCheckName(@QueryParameter String value) throws IOException, ServletException {
- if(value.length()==0)
- return FormValidation.error("Please set a name");
- if(value.length()<4)
- return FormValidation.warning("Isn't the name too short?");
- return FormValidation.ok();
- }
-
- public boolean isApplicable(Class<? extends AbstractProject> aClass) {
- // indicates that this builder can be used with all kinds of project types
- return true;
- }
-
- /**
- * This human readable name is used in the configuration screen.
- */
- public String getDisplayName() {
- return "Say hello world";
- }
-
- @Override
- public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
- // To persist global configuration information,
- // set that to properties and call save().
- useFrench = formData.getBoolean("useFrench");
- // ^Can also use req.bindJSON(this, formData);
- // (easier when there are many fields; need set* methods for this, like setUseFrench)
- save();
- return super.configure(req,formData);
- }
-
- /**
- * This method returns true if the global configuration says we should speak French.
- */
- public boolean useFrench() {
- return useFrench;
- }
- }
-}
-
diff --git a/src/main/resources/index.jelly b/src/main/resources/index.jelly
index de6361c..453e582 100644
--- a/src/main/resources/index.jelly
+++ b/src/main/resources/index.jelly
@@ -1,8 +1,8 @@
<!--
This view is used to render the plugin list page.
Since we don't really have anything dynamic here, let's just use static HTML.
-->
<div>
- This plugin is a sample plugin to explain how to write a Hudson plugin.
+ Is taking care of hanging SCM Poller Threads.
</div>
\ No newline at end of file
diff --git a/src/main/resources/name/wydler/hudson/plugin/HangingSCMPollingTrigger/index.jelly b/src/main/resources/name/wydler/hudson/plugin/HangingSCMPollingTrigger/index.jelly
new file mode 100644
index 0000000..06c65dc
--- /dev/null
+++ b/src/main/resources/name/wydler/hudson/plugin/HangingSCMPollingTrigger/index.jelly
@@ -0,0 +1,39 @@
+<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define" xmlns:l="/lib/layout"
+ xmlns:t="/lib/hudson" xmlns:f="/lib/form" xmlns:i="jelly:fmt">
+ <l:layout title="${it.displayName}">
+ <l:header/>
+ <l:side-panel>
+ <l:tasks>
+ <l:task icon="images/24x24/up.gif" href=".." title="${%Back to List}"/>
+ </l:tasks>
+ </l:side-panel>
+ <l:main-panel>
+ <p>${%The following polling activities exceed the} ${%StarvationThreshold}</p>
+ <p>${%StarvationThreshold} = ${it.starvationThreshold}</p>
+ <table id="runners" class="sortable pane bigtable">
+ <tr>
+ <th initialSortDir="down">${%Job}</th>
+ <th>${%Log}</th>
+ <th>${%Running for}</th>
+ <th>${%Interrupt}</th>
+ </tr>
+ <j:forEach var="runner" items="${it.HangingScmTriggerRunners}">
+ <tr>
+ <td>
+ <a href="${rootURL}/${runner.target.url}">${runner.target.displayName}</a>
+ </td>
+ <td>
+ <a href="${rootURL}/${runner.target.url}scmPollLog/">${runner.target.displayName} Polling Log</a>
+ </td>
+ <td>
+ ${runner.duration}
+ </td>
+ <td>
+ <a href="interrupt?job=${runner.target.name}">${%Interrupt}</a>
+ </td>
+ </tr>
+ </j:forEach>
+ </table>
+ </l:main-panel>
+ </l:layout>
+</j:jelly>
\ No newline at end of file
diff --git a/src/main/resources/name/wydler/hudson/plugin/HelloWorldBuilder/config.jelly b/src/main/resources/name/wydler/hudson/plugin/HelloWorldBuilder/config.jelly
deleted file mode 100644
index 491280c..0000000
--- a/src/main/resources/name/wydler/hudson/plugin/HelloWorldBuilder/config.jelly
+++ /dev/null
@@ -1,15 +0,0 @@
-<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define" xmlns:l="/lib/layout" xmlns:t="/lib/hudson" xmlns:f="/lib/form">
- <!--
- This jelly script is used for per-project configuration.
-
- See global.jelly for a general discussion about jelly script.
- -->
-
- <!--
- Creates a text field that shows the value of the "name" property.
- When submitted, it will be passed to the corresponding constructor parameter.
- -->
- <f:entry title="Name" field="name">
- <f:textbox />
- </f:entry>
-</j:jelly>
diff --git a/src/main/resources/name/wydler/hudson/plugin/HelloWorldBuilder/global.jelly b/src/main/resources/name/wydler/hudson/plugin/HelloWorldBuilder/global.jelly
deleted file mode 100644
index 2a0ec08..0000000
--- a/src/main/resources/name/wydler/hudson/plugin/HelloWorldBuilder/global.jelly
+++ /dev/null
@@ -1,32 +0,0 @@
-<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define" xmlns:l="/lib/layout" xmlns:t="/lib/hudson" xmlns:f="/lib/form">
- <!--
- This Jelly script is used to produce the global configuration option.
-
- Hudson uses a set of tag libraries to provide uniformity in forms.
- To determine where this tag is defined, first check the namespace URI,
- and then look under $HUDSON/views/. For example, <f:section> is defined
- in $HUDSON/views/lib/form/section.jelly.
-
- It's also often useful to just check other similar scripts to see what
- tags they use. Views are always organized according to its owner class,
- so it should be straightforward to find them.
- -->
- <f:section title="Hello World Builder">
- <!--
- optional @help points to the help document HTML. /plugin/hanging-scm-poller-plugin
- is mapped to our webapp/ directory, so this is a convenient way to serve
- static resources.
- -->
- <f:entry title="French"
- description="Check if we should say hello in French"
- help="/plugin/hanging-scm-poller-plugin/help-globalConfig.html">
- <!--
- we'll have on input field. In HTML, single "namespace" is shared between
- all form components in one <form>, so we need to choose a name that doesn't
- collide with other plugins. The 'descriptor' variable represents our descriptor
- object, so we use that to determine the initial value for this form.
- -->
- <f:checkbox name="hello_world.useFrench" checked="${descriptor.useFrench()}" />
- </f:entry>
- </f:section>
-</j:jelly>
diff --git a/src/main/resources/name/wydler/hudson/plugin/HelloWorldBuilder/help-name.html b/src/main/resources/name/wydler/hudson/plugin/HelloWorldBuilder/help-name.html
deleted file mode 100644
index 3fe2997..0000000
--- a/src/main/resources/name/wydler/hudson/plugin/HelloWorldBuilder/help-name.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<div>
- Help file for fields are discovered through a file name convention. This file is an line help for
- the "name" field. You can have <i>arbitrary</i> HTML here. You can write this file as a Jelly script
- if you need a dynamic content (but if you do so, change the extension to .jelly)
-</div>
\ No newline at end of file
diff --git a/src/main/webapp/help-globalConfig.html b/src/main/webapp/help-globalConfig.html
deleted file mode 100644
index a86fb74..0000000
--- a/src/main/webapp/help-globalConfig.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<div>
- <p>
- This HTML fragment will be injected into the configuration screen
- when the user clicks the 'help' icon. See global.jelly for how the
- form decides which page to load.
- You can have any HTML fragment here.
- </p>
-</div>
|
ehabkost/passerd
|
514b499f19de826818474f1f055fc5c899bdc99e
|
use user_id on friend_ids() call
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index a1793a9..2842b88 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -321,1026 +321,1027 @@ class CachedTwitterIrcUser(TwitterIrcUser):
return d
def has_data(self):
"""Checks if the Twitter user info is known"""
return (self.__get_data() is not None)
data = property(_get_data)
nick = property(lambda self: str(self.data.twitter_screen_name))
username = property(lambda self: str(self.data.twitter_screen_name))
real_name = property(lambda self: self.data.twitter_name.encode('utf-8'))
hostname = property(lambda self: 'twitter.com')
class UnknownTwitterUser(TwitterIrcUser):
"""An IrcUser object for an user we don't know anything about, but may be a valid Twitter user"""
def __init__(self, proto, nickname):
self.proto = proto
self.nick = nickname
self.username = nickname
real_name = 'Unknown User'
hostname = 'twitter.com'
def _target_params(self):
return {'screen_name':self.nick}
class TwitterIrcUserCache:
"""Cache of CachedTwitterIrcUser objects
A TwitterIrcUserCache is client-specific (not server-global), and takes
care of creating CachedTwitterIrcUser objects for some queries.
"""
def __init__(self, proto, cache):
self.proto = proto
self.cache = cache
self.cache.addCallback(self._user_changed)
self._watched_ids = {}
def _user_changed(self, id, old_info, new_info):
dbg("user_changed: %r, %r, %r" % (id, old_info, new_info))
if id in self._watched_ids:
dbg("user_changed (%s): is being watched." % (id))
u = self._get_user(id).data_changed(old_info, new_info)
def _get_user(self, id):
u = CachedTwitterIrcUser(self.proto, self.cache, id)
return u
def watch_user_id(self, id):
"""Start watching user ID for changes"""
self._watched_ids[id] = True
def watch_user_ids(self, ids):
for id in ids:
self.watch_user_id(id)
def watch_user(self, u):
self.watch_user_id(u._twitter_id)
def get_user(self, id):
return self._get_user(id)
def fetch_individual_user_info(self, unknown_users):
#TODO: implement me
pass
def fetch_all_friend_info(self, user, unknown_users):
#TODO: unify this paging code with the one on FriendlistMixIn
reqs = []
def request_cursor(cursor):
self.proto.dbg("requesting a page from the friend list: %s" % (str(cursor)))
reqs.append(cursor)
self.proto.api.list_friends(got_user, user=user, params={'cursor':cursor},
page_delegate=end_page).addCallbacks(done, error)
def got_user(u):
self.proto.global_twuser_cache.got_api_user_info(u)
def end_page(next, prev):
unk = [u for u in unknown_users if not u.has_data()]
num = len(unk)
if num == 0:
self.proto.notice("I know all friends of %s, now!" % (user))
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addEntryCallback(self.got_entry)
f.addErrback(self.refresh_error)
f.addRawErrback(self.raw_refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
dbg("nickname %s not found", nick)
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
dbg("no posts by uid %s", uid)
return None
if substring:
matches = []
i = 1
while i <= len(recent):
r = recent[-i]
text = full_entity_decode(r.text)
#TODO: make it more flexible, ignoring punctuation and spaces
if substring.lower() in text.lower():
matches.append(r)
i += 1
if not matches:
return None
if len(matches) > 1:
raise Exception("Multiple matches for [%s] on posts by %s" % (substring, nick))
# yay, single match:
r = matches[0]
else:
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent, I don't know if it's the one you want. Use words from the text to identify it" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
dbg("%s got_entry. id: %s", self.name, e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("%s refresh error: %r", self.name, e)
if isinstance(e, twisted.web.error.Error):
if str(e.status) == '503':
return self.bot_notice("Look! A flying whale! -- %s" % (e))
if isinstance(e, ThrottlerMessage):
# throttler messages are shown directly
return self.bot_notice(str(e))
self.bot_notice("error refreshing feed: %s" % (e))
def raw_refresh_error(self, e):
dbg("%s raw refresh error: %r", self.name, e)
if isinstance(e, twisted.web.error.Error):
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.status == '400' and remaining == 0:
self.wait_rate_limit()
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You can still try to fetch new tweets using `!`. Also, '
'you can check the rate limit using `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallbacks(done, error)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
def error(e):
self.bot_msg('error refreshing: %s' % (e.value))
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
- return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
- params=params, page_delegate=page_delegate)
+ params = params.copy()
+ params['user_id'] = self.proto.authenticated_user.id
+ return self.proto.api.friends_ids(delegate, params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
return [self.proto.passerd_bot, self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class DebugCommands(CommandDialog):
"""Some misc debug commands"""
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
class PasserdCommands(CommandHelpMixin, CommandDialog):
# subcommands:
importance_debug = dialogs.CMD_IMP_DEBUGGING
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_subdialog('debug', DebugCommands(proto, chan, parent=self), 'Debugging commands')
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
if substring:
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
else:
self.message(u"no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
shorthelp_re = "Reply to a post"
importance_re = dialogs.CMD_IMP_COMMON
def help_re(self, args):
self.cmd_syntax('re', '<nick> <part of the post> <message>')
self.message('Will send a reply to a post that matches the supplied text.')
def command_re(self, args):
if not self.chan:
self.message("The RE command only works in a channel")
return
#TODO maybe use shlex.split() to allow using quotes?
nick,rest = self.split_args(args)
substring,msg = self.split_args(rest)
if substring:
substring = try_unicode(substring, IRC_ENCODING)
if not msg:
self.message(u"you need to provide a message")
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message(u"error: %s" % (e))
return
if not r:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
return
msg = "@" + nick + " " + msg
args = {'in_reply_to_status_id': str(r.id)}
dbg("re-msg: %r. args: %r", msg, args)
def done(*args):
self.message("Replied: %s" % (msg))
def error(e):
self.message("Error while replying: %s" % (e.value))
self.proto.send_twitter_post(msg, args).addCallback(done).addErrback(error)
shorthelp_spam = "Report spam"
importance_spam = dialogs.CMD_IMP_INTERESTING
def help_spam(self, args):
self.cmd_syntax('spam', '<nickname>')
self.message('Will report an user for spam')
def command_spam(self, args):
if not args:
self.message('Nickname required')
return
nick = args
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
self.message("nickname %s not found", nick)
return
uid = u.twitter_id
ok = []
def got_user(u):
ok.append(u)
self.message('Reported user [%s] (uid %s) for spam' % (u.screen_name, u.id))
def done(*args):
if not ok:
self.message("Weird. Spam report API call didn't return user info...")
def error(e):
self.message("Error while reporting spam: %s" % (e.value))
self.proto.api.report_spam(uid, got_user).addCallback(done).addErrback(error)
shorthelp_thread = "Show thread for a post"
importance_thread = dialogs.CMD_IMP_INTERESTING
def help_thread(self, args):
self.cmd_syntax('thread', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> will be used.')
self.message('If text is specified, the post containing the supplied text is used')
def command_thread(self, args):
if not self.chan:
self.message("The 'thread' command only works in a channel")
return
nick,substring = self.split_args(args)
if substring:
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
else:
self.message(u"no posts from %s" % (nick))
return
def get_thread(p, back_count):
dbg("getThread: %r, %d", p, back_count)
d = defer.Deferred()
if back_count <= 0 or not p.in_reply_to_status_id:
d.callback([p])
return d
diff --git a/third-party/twitty-twister b/third-party/twitty-twister
index dddc39f..c58d29c 160000
--- a/third-party/twitty-twister
+++ b/third-party/twitty-twister
@@ -1 +1 @@
-Subproject commit dddc39f1c738dbc7b7ccb9e7f91e0564ae059566
+Subproject commit c58d29cd31e63db4ce2c418711149a5d12e7cde9
|
ehabkost/passerd
|
edc7d0870196acaa4d079592c796c9b179901b07
|
fix !thread get_thread() recursion call
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 9248b31..a1793a9 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -851,1037 +851,1037 @@ class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
return [self.proto.passerd_bot, self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class DebugCommands(CommandDialog):
"""Some misc debug commands"""
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
class PasserdCommands(CommandHelpMixin, CommandDialog):
# subcommands:
importance_debug = dialogs.CMD_IMP_DEBUGGING
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_subdialog('debug', DebugCommands(proto, chan, parent=self), 'Debugging commands')
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
if substring:
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
else:
self.message(u"no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
shorthelp_re = "Reply to a post"
importance_re = dialogs.CMD_IMP_COMMON
def help_re(self, args):
self.cmd_syntax('re', '<nick> <part of the post> <message>')
self.message('Will send a reply to a post that matches the supplied text.')
def command_re(self, args):
if not self.chan:
self.message("The RE command only works in a channel")
return
#TODO maybe use shlex.split() to allow using quotes?
nick,rest = self.split_args(args)
substring,msg = self.split_args(rest)
if substring:
substring = try_unicode(substring, IRC_ENCODING)
if not msg:
self.message(u"you need to provide a message")
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message(u"error: %s" % (e))
return
if not r:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
return
msg = "@" + nick + " " + msg
args = {'in_reply_to_status_id': str(r.id)}
dbg("re-msg: %r. args: %r", msg, args)
def done(*args):
self.message("Replied: %s" % (msg))
def error(e):
self.message("Error while replying: %s" % (e.value))
self.proto.send_twitter_post(msg, args).addCallback(done).addErrback(error)
shorthelp_spam = "Report spam"
importance_spam = dialogs.CMD_IMP_INTERESTING
def help_spam(self, args):
self.cmd_syntax('spam', '<nickname>')
self.message('Will report an user for spam')
def command_spam(self, args):
if not args:
self.message('Nickname required')
return
nick = args
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
self.message("nickname %s not found", nick)
return
uid = u.twitter_id
ok = []
def got_user(u):
ok.append(u)
self.message('Reported user [%s] (uid %s) for spam' % (u.screen_name, u.id))
def done(*args):
if not ok:
self.message("Weird. Spam report API call didn't return user info...")
def error(e):
self.message("Error while reporting spam: %s" % (e.value))
self.proto.api.report_spam(uid, got_user).addCallback(done).addErrback(error)
shorthelp_thread = "Show thread for a post"
importance_thread = dialogs.CMD_IMP_INTERESTING
def help_thread(self, args):
self.cmd_syntax('thread', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> will be used.')
self.message('If text is specified, the post containing the supplied text is used')
def command_thread(self, args):
if not self.chan:
self.message("The 'thread' command only works in a channel")
return
nick,substring = self.split_args(args)
if substring:
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
else:
self.message(u"no posts from %s" % (nick))
return
def get_thread(p, back_count):
dbg("getThread: %r, %d", p, back_count)
d = defer.Deferred()
if back_count <= 0 or not p.in_reply_to_status_id:
d.callback([p])
return d
def error(e):
d.errback(e)
statuses = []
def got_it(s):
dbg("got_it: %r", s)
statuses.append(s)
def got_back(l):
dbg("got_back: %r", l)
d.callback(l+[p])
def done(*args):
if not statuses:
got_back([])
return
get_thread(statuses[0], back_count-1).addCallback(got_back).addErrback(error)
- self.proto.api.status_get(str(r.in_reply_to_status_id), got_it).addCallback(done).addErrback(error)
+ self.proto.api.status_get(str(p.in_reply_to_status_id), got_it).addCallback(done).addErrback(error)
return d
def got_thread(l):
dbg('got_thread: %r', l)
self.message('reply thread:')
for e in l:
self.chan.printEntry(e)
self.message('(end of reply thread)')
def error(e):
self.message("Error getting thread: %s" % (e.value))
- self.message('fetching reply thread for message ID %s' % (r.id))
+ self.message('fetching reply thread for message ID %s...' % (r.id))
get_thread(r, 5).addCallback(got_thread).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
bm("this is not supposed to happen, sorry :(")
if e.check(twisted.web.error.Error) and str(e.value.status) == '401':
bm("some possible causes for this error are:")
bm("- incorrect PIN")
bm("- misadjusted system clock")
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (local/twitter)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addEntryCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def aborted(self):
return self._aborted
def abort(self):
"""Makes all @check_aborted functions stop doing anything
"""
dbg("abort")
#FIXME: we need to keep track of current requests/connections and
# abort all of them, instead of letting them continue running,
# but just ignoring the replies. The scheduler may be a good place
# to keep track of all pending requests
self._aborted = True
self._stop_scheduler()
@check_aborted
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
@check_aborted
def send_motd(self):
self.send_reply(irc.RPL_MOTDSTART, ":- %s Message of the day - " % (self.myhost))
self.send_reply(irc.RPL_MOTD, ":- Welcome to Passerd")
self.send_reply(irc.RPL_MOTD, ":- For additional information and help, see %s" % (version.URL))
self.send_reply(irc.RPL_ENDOFMOTD, ":End of MOTD command")
@check_aborted
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
@check_aborted
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _stop_scheduler(self):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
@check_aborted
def _set_scheduler(self, scheduler):
self._stop_scheduler()
self.scheduler = scheduler
def _userQuit(self, reason):
dbg("_userQuit: %r", reason)
self.dm_feed.stop_refreshing()
dbg("joined channels: %r", self.joined_channels)
# list will change under our feet, so copy it:
joined = self.joined_channels[:]
for ch in joined:
dbg("ch: %r", ch)
self.leave_channel(ch, reason)
# stop everything we are doing
self.abort()
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
dbg("dmError: %r", e)
self.notice("Error pulling Direct Messages: %s" % (e))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
@check_aborted
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
@check_aborted
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_channel(self, chan, reason):
dbg("leaving channel %r", chan)
if chan in self.joined_channels:
dbg("chan %r is joined", chan)
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_AWAY(self, prefix, args):
if args:
self.send_reply(irc.RPL_NOWAWAY, ':You have been marked as being away')
else:
self.send_reply(irc.RPL_UNAWAY, ':You are no longer marked as being away')
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
|
ehabkost/passerd
|
21f05491b020af79d4f8bc5cc0e92274b422e580
|
add !THREAD command to see reply thread
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index d7f7499..9248b31 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -799,1024 +799,1091 @@ class FriendlistMixIn:
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
return [self.proto.passerd_bot, self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class DebugCommands(CommandDialog):
"""Some misc debug commands"""
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
class PasserdCommands(CommandHelpMixin, CommandDialog):
# subcommands:
importance_debug = dialogs.CMD_IMP_DEBUGGING
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_subdialog('debug', DebugCommands(proto, chan, parent=self), 'Debugging commands')
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
if substring:
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
else:
self.message(u"no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
shorthelp_re = "Reply to a post"
importance_re = dialogs.CMD_IMP_COMMON
def help_re(self, args):
self.cmd_syntax('re', '<nick> <part of the post> <message>')
self.message('Will send a reply to a post that matches the supplied text.')
def command_re(self, args):
if not self.chan:
self.message("The RE command only works in a channel")
return
#TODO maybe use shlex.split() to allow using quotes?
nick,rest = self.split_args(args)
substring,msg = self.split_args(rest)
if substring:
substring = try_unicode(substring, IRC_ENCODING)
if not msg:
self.message(u"you need to provide a message")
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message(u"error: %s" % (e))
return
if not r:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
return
msg = "@" + nick + " " + msg
args = {'in_reply_to_status_id': str(r.id)}
dbg("re-msg: %r. args: %r", msg, args)
def done(*args):
self.message("Replied: %s" % (msg))
def error(e):
self.message("Error while replying: %s" % (e.value))
self.proto.send_twitter_post(msg, args).addCallback(done).addErrback(error)
shorthelp_spam = "Report spam"
importance_spam = dialogs.CMD_IMP_INTERESTING
def help_spam(self, args):
self.cmd_syntax('spam', '<nickname>')
self.message('Will report an user for spam')
def command_spam(self, args):
if not args:
self.message('Nickname required')
return
nick = args
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
self.message("nickname %s not found", nick)
return
uid = u.twitter_id
ok = []
def got_user(u):
ok.append(u)
self.message('Reported user [%s] (uid %s) for spam' % (u.screen_name, u.id))
def done(*args):
if not ok:
self.message("Weird. Spam report API call didn't return user info...")
def error(e):
self.message("Error while reporting spam: %s" % (e.value))
self.proto.api.report_spam(uid, got_user).addCallback(done).addErrback(error)
+ shorthelp_thread = "Show thread for a post"
+ importance_thread = dialogs.CMD_IMP_INTERESTING
+ def help_thread(self, args):
+ self.cmd_syntax('thread', 'nick [part of post text]')
+ self.message('If no text is specified, the latest post from <nick> will be used.')
+ self.message('If text is specified, the post containing the supplied text is used')
+ def command_thread(self, args):
+ if not self.chan:
+ self.message("The 'thread' command only works in a channel")
+ return
+
+ nick,substring = self.split_args(args)
+
+ if substring:
+ # substring parameter must be unicode, not byte str
+ substring = try_unicode(substring, IRC_ENCODING)
+
+ try:
+ r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
+ except Exception,e:
+ self.message("error: %s" % (e))
+ return
+
+ if not r:
+ if substring:
+ self.message(u"no match for [%s] on posts by %s" % (substring, nick))
+ else:
+ self.message(u"no posts from %s" % (nick))
+ return
+
+ def get_thread(p, back_count):
+ dbg("getThread: %r, %d", p, back_count)
+ d = defer.Deferred()
+ if back_count <= 0 or not p.in_reply_to_status_id:
+ d.callback([p])
+ return d
+
+ def error(e):
+ d.errback(e)
+
+ statuses = []
+ def got_it(s):
+ dbg("got_it: %r", s)
+ statuses.append(s)
+ def got_back(l):
+ dbg("got_back: %r", l)
+ d.callback(l+[p])
+ def done(*args):
+ if not statuses:
+ got_back([])
+ return
+ get_thread(statuses[0], back_count-1).addCallback(got_back).addErrback(error)
+ self.proto.api.status_get(str(r.in_reply_to_status_id), got_it).addCallback(done).addErrback(error)
+ return d
+
+ def got_thread(l):
+ dbg('got_thread: %r', l)
+ self.message('reply thread:')
+ for e in l:
+ self.chan.printEntry(e)
+ self.message('(end of reply thread)')
+ def error(e):
+ self.message("Error getting thread: %s" % (e.value))
+
+ self.message('fetching reply thread for message ID %s' % (r.id))
+ get_thread(r, 5).addCallback(got_thread).addErrback(error)
+
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
bm("this is not supposed to happen, sorry :(")
if e.check(twisted.web.error.Error) and str(e.value.status) == '401':
bm("some possible causes for this error are:")
bm("- incorrect PIN")
bm("- misadjusted system clock")
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (local/twitter)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addEntryCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def aborted(self):
return self._aborted
def abort(self):
"""Makes all @check_aborted functions stop doing anything
"""
dbg("abort")
#FIXME: we need to keep track of current requests/connections and
# abort all of them, instead of letting them continue running,
# but just ignoring the replies. The scheduler may be a good place
# to keep track of all pending requests
self._aborted = True
self._stop_scheduler()
@check_aborted
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
@check_aborted
def send_motd(self):
self.send_reply(irc.RPL_MOTDSTART, ":- %s Message of the day - " % (self.myhost))
self.send_reply(irc.RPL_MOTD, ":- Welcome to Passerd")
self.send_reply(irc.RPL_MOTD, ":- For additional information and help, see %s" % (version.URL))
self.send_reply(irc.RPL_ENDOFMOTD, ":End of MOTD command")
@check_aborted
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
@check_aborted
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _stop_scheduler(self):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
@check_aborted
def _set_scheduler(self, scheduler):
self._stop_scheduler()
self.scheduler = scheduler
def _userQuit(self, reason):
dbg("_userQuit: %r", reason)
self.dm_feed.stop_refreshing()
dbg("joined channels: %r", self.joined_channels)
# list will change under our feet, so copy it:
joined = self.joined_channels[:]
for ch in joined:
dbg("ch: %r", ch)
self.leave_channel(ch, reason)
# stop everything we are doing
self.abort()
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
dbg("dmError: %r", e)
self.notice("Error pulling Direct Messages: %s" % (e))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
@check_aborted
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
@check_aborted
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_channel(self, chan, reason):
dbg("leaving channel %r", chan)
if chan in self.joined_channels:
dbg("chan %r is joined", chan)
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_AWAY(self, prefix, args):
if args:
self.send_reply(irc.RPL_NOWAWAY, ':You have been marked as being away')
else:
self.send_reply(irc.RPL_UNAWAY, ':You are no longer marked as being away')
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
diff --git a/third-party/twitty-twister b/third-party/twitty-twister
index 7051f8d..dddc39f 160000
--- a/third-party/twitty-twister
+++ b/third-party/twitty-twister
@@ -1 +1 @@
-Subproject commit 7051f8dc9f7771039171086c1fa5284df377a9fc
+Subproject commit dddc39f1c738dbc7b7ccb9e7f91e0564ae059566
|
ehabkost/passerd
|
795889619f519afd26d2788a82608efadd396756
|
add !spam command
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index f925784..d7f7499 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -770,1024 +770,1052 @@ class FriendlistMixIn:
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
return [self.proto.passerd_bot, self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class DebugCommands(CommandDialog):
"""Some misc debug commands"""
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
class PasserdCommands(CommandHelpMixin, CommandDialog):
# subcommands:
importance_debug = dialogs.CMD_IMP_DEBUGGING
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_subdialog('debug', DebugCommands(proto, chan, parent=self), 'Debugging commands')
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
if substring:
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
else:
self.message(u"no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
shorthelp_re = "Reply to a post"
importance_re = dialogs.CMD_IMP_COMMON
def help_re(self, args):
self.cmd_syntax('re', '<nick> <part of the post> <message>')
self.message('Will send a reply to a post that matches the supplied text.')
def command_re(self, args):
if not self.chan:
self.message("The RE command only works in a channel")
return
#TODO maybe use shlex.split() to allow using quotes?
nick,rest = self.split_args(args)
substring,msg = self.split_args(rest)
if substring:
substring = try_unicode(substring, IRC_ENCODING)
if not msg:
self.message(u"you need to provide a message")
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message(u"error: %s" % (e))
return
if not r:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
return
msg = "@" + nick + " " + msg
args = {'in_reply_to_status_id': str(r.id)}
dbg("re-msg: %r. args: %r", msg, args)
def done(*args):
self.message("Replied: %s" % (msg))
def error(e):
self.message("Error while replying: %s" % (e.value))
self.proto.send_twitter_post(msg, args).addCallback(done).addErrback(error)
+ shorthelp_spam = "Report spam"
+ importance_spam = dialogs.CMD_IMP_INTERESTING
+ def help_spam(self, args):
+ self.cmd_syntax('spam', '<nickname>')
+ self.message('Will report an user for spam')
+
+ def command_spam(self, args):
+ if not args:
+ self.message('Nickname required')
+ return
+
+ nick = args
+ u = self.proto.global_twuser_cache.lookup_screen_name(nick)
+ if u is None:
+ self.message("nickname %s not found", nick)
+ return
+ uid = u.twitter_id
+
+ ok = []
+ def got_user(u):
+ ok.append(u)
+ self.message('Reported user [%s] (uid %s) for spam' % (u.screen_name, u.id))
+ def done(*args):
+ if not ok:
+ self.message("Weird. Spam report API call didn't return user info...")
+ def error(e):
+ self.message("Error while reporting spam: %s" % (e.value))
+ self.proto.api.report_spam(uid, got_user).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
bm("this is not supposed to happen, sorry :(")
if e.check(twisted.web.error.Error) and str(e.value.status) == '401':
bm("some possible causes for this error are:")
bm("- incorrect PIN")
bm("- misadjusted system clock")
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (local/twitter)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addEntryCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def aborted(self):
return self._aborted
def abort(self):
"""Makes all @check_aborted functions stop doing anything
"""
dbg("abort")
#FIXME: we need to keep track of current requests/connections and
# abort all of them, instead of letting them continue running,
# but just ignoring the replies. The scheduler may be a good place
# to keep track of all pending requests
self._aborted = True
self._stop_scheduler()
@check_aborted
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
@check_aborted
def send_motd(self):
self.send_reply(irc.RPL_MOTDSTART, ":- %s Message of the day - " % (self.myhost))
self.send_reply(irc.RPL_MOTD, ":- Welcome to Passerd")
self.send_reply(irc.RPL_MOTD, ":- For additional information and help, see %s" % (version.URL))
self.send_reply(irc.RPL_ENDOFMOTD, ":End of MOTD command")
@check_aborted
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
@check_aborted
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _stop_scheduler(self):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
@check_aborted
def _set_scheduler(self, scheduler):
self._stop_scheduler()
self.scheduler = scheduler
def _userQuit(self, reason):
dbg("_userQuit: %r", reason)
self.dm_feed.stop_refreshing()
dbg("joined channels: %r", self.joined_channels)
# list will change under our feet, so copy it:
joined = self.joined_channels[:]
for ch in joined:
dbg("ch: %r", ch)
self.leave_channel(ch, reason)
# stop everything we are doing
self.abort()
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
dbg("dmError: %r", e)
self.notice("Error pulling Direct Messages: %s" % (e))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
@check_aborted
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
@check_aborted
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_channel(self, chan, reason):
dbg("leaving channel %r", chan)
if chan in self.joined_channels:
dbg("chan %r is joined", chan)
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_AWAY(self, prefix, args):
if args:
self.send_reply(irc.RPL_NOWAWAY, ':You have been marked as being away')
else:
self.send_reply(irc.RPL_UNAWAY, ':You are no longer marked as being away')
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
diff --git a/third-party/twitty-twister b/third-party/twitty-twister
index 24d6d8c..7051f8d 160000
--- a/third-party/twitty-twister
+++ b/third-party/twitty-twister
@@ -1 +1 @@
-Subproject commit 24d6d8cd5e0c6fa791bc5a7670286a1cebf41141
+Subproject commit 7051f8dc9f7771039171086c1fa5284df377a9fc
|
ehabkost/passerd
|
d085b6edbd3e2b931ac50995042789db78b6fdcb
|
Added command !re to allow replying a post
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 07c7122..f925784 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -728,1024 +728,1066 @@ class TwitterChannel(IrcChannel):
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
return [self.proto.passerd_bot, self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class DebugCommands(CommandDialog):
"""Some misc debug commands"""
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
class PasserdCommands(CommandHelpMixin, CommandDialog):
# subcommands:
importance_debug = dialogs.CMD_IMP_DEBUGGING
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_subdialog('debug', DebugCommands(proto, chan, parent=self), 'Debugging commands')
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
if substring:
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
else:
self.message(u"no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
+ shorthelp_re = "Reply to a post"
+ importance_re = dialogs.CMD_IMP_COMMON
+ def help_re(self, args):
+ self.cmd_syntax('re', '<nick> <part of the post> <message>')
+ self.message('Will send a reply to a post that matches the supplied text.')
+
+ def command_re(self, args):
+ if not self.chan:
+ self.message("The RE command only works in a channel")
+ return
+
+ #TODO maybe use shlex.split() to allow using quotes?
+ nick,rest = self.split_args(args)
+ substring,msg = self.split_args(rest)
+ if substring:
+ substring = try_unicode(substring, IRC_ENCODING)
+ if not msg:
+ self.message(u"you need to provide a message")
+
+ try:
+ r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
+ except Exception,e:
+ self.message(u"error: %s" % (e))
+ return
+
+ if not r:
+ self.message(u"no match for [%s] on posts by %s" % (substring, nick))
+ return
+
+ msg = "@" + nick + " " + msg
+
+ args = {'in_reply_to_status_id': str(r.id)}
+ dbg("re-msg: %r. args: %r", msg, args)
+
+ def done(*args):
+ self.message("Replied: %s" % (msg))
+
+ def error(e):
+ self.message("Error while replying: %s" % (e.value))
+
+ self.proto.send_twitter_post(msg, args).addCallback(done).addErrback(error)
+
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
bm("this is not supposed to happen, sorry :(")
if e.check(twisted.web.error.Error) and str(e.value.status) == '401':
bm("some possible causes for this error are:")
bm("- incorrect PIN")
bm("- misadjusted system clock")
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (local/twitter)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addEntryCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def aborted(self):
return self._aborted
def abort(self):
"""Makes all @check_aborted functions stop doing anything
"""
dbg("abort")
#FIXME: we need to keep track of current requests/connections and
# abort all of them, instead of letting them continue running,
# but just ignoring the replies. The scheduler may be a good place
# to keep track of all pending requests
self._aborted = True
self._stop_scheduler()
@check_aborted
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
@check_aborted
def send_motd(self):
self.send_reply(irc.RPL_MOTDSTART, ":- %s Message of the day - " % (self.myhost))
self.send_reply(irc.RPL_MOTD, ":- Welcome to Passerd")
self.send_reply(irc.RPL_MOTD, ":- For additional information and help, see %s" % (version.URL))
self.send_reply(irc.RPL_ENDOFMOTD, ":End of MOTD command")
@check_aborted
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
@check_aborted
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _stop_scheduler(self):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
@check_aborted
def _set_scheduler(self, scheduler):
self._stop_scheduler()
self.scheduler = scheduler
def _userQuit(self, reason):
dbg("_userQuit: %r", reason)
self.dm_feed.stop_refreshing()
dbg("joined channels: %r", self.joined_channels)
# list will change under our feet, so copy it:
joined = self.joined_channels[:]
for ch in joined:
dbg("ch: %r", ch)
self.leave_channel(ch, reason)
# stop everything we are doing
self.abort()
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
dbg("dmError: %r", e)
self.notice("Error pulling Direct Messages: %s" % (e))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
@check_aborted
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
@check_aborted
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_channel(self, chan, reason):
dbg("leaving channel %r", chan)
if chan in self.joined_channels:
dbg("chan %r is joined", chan)
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_AWAY(self, prefix, args):
if args:
self.send_reply(irc.RPL_NOWAWAY, ':You have been marked as being away')
else:
self.send_reply(irc.RPL_UNAWAY, ':You are no longer marked as being away')
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
|
ehabkost/passerd
|
2d4b3b502c94d940bf63da0e30f877e9ab3e418e
|
add some diagnostics for 401 errors when getting oauth tokens
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 1b7cb3b..07c7122 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -771,1024 +771,1029 @@ class FriendlistMixIn:
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
return [self.proto.passerd_bot, self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class DebugCommands(CommandDialog):
"""Some misc debug commands"""
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
class PasserdCommands(CommandHelpMixin, CommandDialog):
# subcommands:
importance_debug = dialogs.CMD_IMP_DEBUGGING
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_subdialog('debug', DebugCommands(proto, chan, parent=self), 'Debugging commands')
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
if substring:
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
else:
self.message(u"no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
+ bm("this is not supposed to happen, sorry :(")
+ if e.check(twisted.web.error.Error) and str(e.value.status) == '401':
+ bm("some possible causes for this error are:")
+ bm("- incorrect PIN")
+ bm("- misadjusted system clock")
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (local/twitter)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addEntryCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def aborted(self):
return self._aborted
def abort(self):
"""Makes all @check_aborted functions stop doing anything
"""
dbg("abort")
#FIXME: we need to keep track of current requests/connections and
# abort all of them, instead of letting them continue running,
# but just ignoring the replies. The scheduler may be a good place
# to keep track of all pending requests
self._aborted = True
self._stop_scheduler()
@check_aborted
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
@check_aborted
def send_motd(self):
self.send_reply(irc.RPL_MOTDSTART, ":- %s Message of the day - " % (self.myhost))
self.send_reply(irc.RPL_MOTD, ":- Welcome to Passerd")
self.send_reply(irc.RPL_MOTD, ":- For additional information and help, see %s" % (version.URL))
self.send_reply(irc.RPL_ENDOFMOTD, ":End of MOTD command")
@check_aborted
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
@check_aborted
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _stop_scheduler(self):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
@check_aborted
def _set_scheduler(self, scheduler):
self._stop_scheduler()
self.scheduler = scheduler
def _userQuit(self, reason):
dbg("_userQuit: %r", reason)
self.dm_feed.stop_refreshing()
dbg("joined channels: %r", self.joined_channels)
# list will change under our feet, so copy it:
joined = self.joined_channels[:]
for ch in joined:
dbg("ch: %r", ch)
self.leave_channel(ch, reason)
# stop everything we are doing
self.abort()
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
dbg("dmError: %r", e)
self.notice("Error pulling Direct Messages: %s" % (e))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
@check_aborted
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
@check_aborted
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_channel(self, chan, reason):
dbg("leaving channel %r", chan)
if chan in self.joined_channels:
dbg("chan %r is joined", chan)
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_AWAY(self, prefix, args):
if args:
self.send_reply(irc.RPL_NOWAWAY, ':You have been marked as being away')
else:
self.send_reply(irc.RPL_UNAWAY, ':You are no longer marked as being away')
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
def irc_MOTD(self, p, args):
self.send_motd()
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
|
ehabkost/passerd
|
5ed977b3033f484f16a1ab77a04dac0c6784c12e
|
add debian packaging files
|
diff --git a/debian/changelog b/debian/changelog
new file mode 100644
index 0000000..b89ad87
--- /dev/null
+++ b/debian/changelog
@@ -0,0 +1,5 @@
+passerd (0.1.1-1) unstable; urgency=low
+
+ * Initial release
+
+ -- Olavo Junior <skyegg@gmail.com> Fri, 09 Apr 2010 16:17:50 -0300
diff --git a/debian/compat b/debian/compat
new file mode 100644
index 0000000..7f8f011
--- /dev/null
+++ b/debian/compat
@@ -0,0 +1 @@
+7
diff --git a/debian/control b/debian/control
new file mode 100644
index 0000000..5968225
--- /dev/null
+++ b/debian/control
@@ -0,0 +1,16 @@
+Source: passerd
+Section: net
+Priority: extra
+Maintainer: Olavo Junior <skyegg@gmail.com>
+Build-Depends: cdbs, debhelper (>= 7), python-dev, python-support, python-setuptools
+XS-Python-Version: all
+Standards-Version: 3.8.3
+Homepage: http://passerd.raisama.net
+
+Package: passerd
+Architecture: any
+Depends: ${misc:Depends}, ${python:Depends}, python-twisted, python-sqlite, python-sqlalchemy, python-oauth, python-daemon, python-twittytwister
+Description: Twitter client that runs an IRC server
+ Passerd is a Twitter client that runs an IRC server. Just run it
+ and point an IRC client to it, and you'll see your Twitter friends
+ as IRC contacts, and tweets appearing as messages on an IRC channel.
diff --git a/debian/copyright b/debian/copyright
new file mode 100644
index 0000000..427df38
--- /dev/null
+++ b/debian/copyright
@@ -0,0 +1,69 @@
+This work was packaged for Debian by:
+
+ Olavo Junior <skyegg@gmail.com> on Fri, 09 Apr 2010 16:17:50 -0300
+
+It was downloaded from http://github.com/ehabkost/passerd.git
+
+Upstream Author:
+
+ Eduardo Pereira Habkost <ehabkost@raisama.net>
+
+Copyright:
+
+ Eduardo Pereira Habkost <ehabkost@raisama.net>
+
+License:
+
+The MIT License
+
+Copyright (c) 2010 Eduardo Pereira Habkost <ehabkost@raisama.net>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+The Debian packaging is:
+
+ Copyright (C) 2010 Olavo Junior <skyegg@gmail.com>
+
+and is licensed under the MIT License.
+
+========================
+
+PBKDF2 module copyright and license:
+
+Copyright (C) 2007, 2008 Dwayne C. Litzenberger <dlitz@dlitz.net>
+All rights reserved.
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+provided that the above copyright notice appear in all copies and that
+both that copyright notice and this permission notice appear in
+supporting documentation.
+
+THE AUTHOR PROVIDES THIS SOFTWARE ``AS IS'' AND ANY EXPRESSED OR·
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES·
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.··
+IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,·
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,·
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY·
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT·
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE·
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+Country of origin: Canada
diff --git a/debian/dirs b/debian/dirs
new file mode 100644
index 0000000..decc7e9
--- /dev/null
+++ b/debian/dirs
@@ -0,0 +1 @@
+/var/lib/passerd
diff --git a/debian/docs b/debian/docs
new file mode 100644
index 0000000..2719474
--- /dev/null
+++ b/debian/docs
@@ -0,0 +1,6 @@
+COPYING
+CREDITS.markdown
+INSTALL.markdown
+NEWS.markdown
+README.markdown
+USERGUIDE.markdown
diff --git a/debian/passerd.init b/debian/passerd.init
new file mode 100644
index 0000000..52cbf4e
--- /dev/null
+++ b/debian/passerd.init
@@ -0,0 +1,69 @@
+#!/bin/sh
+### BEGIN INIT INFO
+# Provides: passerd
+# Required-Start: $remote_fs $syslog
+# Required-Stop: $remote_fs $syslog
+# Default-Start: 2 3 4 5
+# Default-Stop: 0 1 6
+### END INIT INFO
+
+PATH=/sbin:/bin:/usr/sbin:/usr/bin
+DESC="Twitter client that runs an IRC server"
+NAME=passerd
+DAEMON=/usr/bin/$NAME
+PIDFILE=/var/run/$NAME.pid
+SCRIPTNAME=/etc/init.d/$NAME
+
+PASSERD_PORT="localhost:6667"
+PASSERD_OPTS="-d --log-file=/var/log/passerd.log /var/lib/passerd/data.sqlite"
+
+# include passerd defaults if available.
+test -f /etc/default/$NAME && . /etc/default/$NAME
+
+# gracefully exit if the package has been removed.
+test -x $DAEMON || exit 0
+
+. /lib/lsb/init-functions
+
+d_start() {
+ touch $PIDFILE
+ start-stop-daemon --start --quiet --pidfile $PIDFILE \
+ --exec $DAEMON -- passerd -l $PASSERD_PORT $PASSERD_OPTS
+}
+
+d_status() {
+ ps ax | grep -q $DAEMON && echo "$NAME is running" || echo "$NAME is not running"
+}
+
+d_stop() {
+ start-stop-daemon --stop --quiet --pidfile $PIDFILE \
+ --name $NAME
+}
+
+case "$1" in
+ start)
+ echo -n "Starting $DESC: $NAME"
+ d_start
+ echo "."
+ ;;
+
+ stop)
+ echo -n "Stopping $DESC: $NAME"
+ d_stop
+ echo "."
+ ;;
+ status)
+ d_status
+ RETVAL=$?
+ ;;
+ restart|reload)
+ $0 stop
+ $0 start
+ ;;
+ *)
+ echo -n "Usage: %s {start|stop|status|restart}\n" "$0"
+ RETVAL=1
+ ;;
+esac
+
+exit $RETVAL
diff --git a/debian/pycompat b/debian/pycompat
new file mode 100644
index 0000000..0cfbf08
--- /dev/null
+++ b/debian/pycompat
@@ -0,0 +1 @@
+2
diff --git a/debian/rules b/debian/rules
new file mode 100644
index 0000000..33bf3ce
--- /dev/null
+++ b/debian/rules
@@ -0,0 +1,7 @@
+#!/usr/bin/make -f
+
+DEB_PYTHON_SYSTEM = pysupport
+DEB_DH_INSTALLINIT_ARGS := --no-start
+
+include /usr/share/cdbs/1/rules/debhelper.mk
+include /usr/share/cdbs/1/class/python-distutils.mk
|
ehabkost/passerd
|
ed048c9613989f8b06a11b46f14cb05976bda805
|
fix upper-case matching on !rt substring matching
|
diff --git a/NEWS.markdown b/NEWS.markdown
index 27868c8..3dbe815 100644
--- a/NEWS.markdown
+++ b/NEWS.markdown
@@ -1,87 +1,94 @@
+### Current development version
+
+
+* Bugs fixed:
+ * Issue #91: !RT upper-case matching
+
+
### Passerd 0.1.1 - 18 Mar 2010
* Support for Python 2.4
* Send MOTD when welcoming user, as some clients and scripts expect MOTD to be
always present
* Handle AWAY messages from clients (simply ignoring the away message)
* Bugs fixed:
* issue #76: handle windows-1252 chars
* issue #83: support Python 2.4
* issue #82: unicode handling on `!rt`
* issue #84: feeds still running after disconnect
* issue #30: don't show every friend from a user on #@user channel
* issue #55: send MOTD when user connects
* issue #71: don't flood the user with error messages
### Passerd 0.1.0 - 24 Jan 2010
* Add a simple scheduling algorithm that will make sure Passerd don't kill the
Twitter API rate-limit if the user joins too many Passerd channels.
* Fix auto-`@` of nickname replies when nicknames have digits on it
* Set timeout on API calls to avoid getting stuck if HTTP requests take too
long to reply
* Retweets are shown as messages from the original poster, with a note
by passerd-bot
(configurable by `!be concise` option)
* Multi-line tweets aren't shown as multiple lines anymore
(configurable by `!be verbose` option)
* Lower-level `!config` command to set specific configuration variables
* Support for running Passerd in _daemon_ mode
* Retweet support using `!rt` command
### Passerd 0.0.5 - 6 Jan 2010
* Don't continue refreshing feeds if rate-limit is hit. This is a temporary
solution until a true rate-limit-adjusting scheduler is written
* Unify `passerd-bot` commands and implementation of `!command` on `#twitter`
* Including a help system
* Add a `!post` command (aliases: `!tw`, `!twit`, `!update`)
* Paranoid mode: if you are afraid of posting by mistake when typing on
your IRC client, you can enable a "paranoid" mode using the `!be paranoid`
command.
When in this mode, you can only post to twitter using `!post` (or the aliases
above)
### Passerd 0.0.4.2 - 28 Dec 2009
* Updated twitty-twister version. On 0.0.4, I forgot to update the
twitty-twister git commit reference, and broke twitter posting.
### Passerd 0.0.4.1 - 28 Dec 2009
* Fix a problem on the OAuth access token request method. A POST
request with no Content-Length may case a 411 Length Required
error (probably on some proxy servers).
* Thanks to Bogdano Arendartchuk for the fix.
### Passerd 0.0.4 - 27 Dec 2009
* Ability to follow lists using `#@username/list` channels
* Ability to get updates from a single user using `#@username` channels
* Implement #mentions channel, for mentions of `@username`
* OAuth support! Now you don't need to give your Twitter password to
Passerd (and you'll get a nice "from Passerd" note on your Twits. :)
* Optional nickserv-style authentication support
* Better error messages (using a `passerd-bot` IRC user)
* Now with a real (but still a bit ugly) web page at [passerd.raisama.net](http://passerd.raisama.net/)
### Passerd 0.0.3 - 18 Dec 2009
* Ability to send updates to Twitter
* Fetch detailed user info from Twitter on-demand, only if necessary
* Basic command-line option support
* Implement Twitter follow/unfollow as IRCK KICK/INVITE
### Passerd 0.0.2 - 15 Dec 2009
* List Twitter friends as IRC contacts
### Passerd 0.0.1 - 14 Dec 2009
* Basic Twitter reading ability
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 03716da..1b7cb3b 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -35,1025 +35,1025 @@ from twisted.words.protocols.irc import IRC
from twisted.internet.protocol import Factory
from twisted.internet import reactor, defer
import twisted.web.error
from twittytwister.twitter import Twitter, TwitterClientInfo
from passerd.data import DataStore, TwitterUserData
from passerd.callbacks import CallbackList
from passerd.utils import full_entity_decode
from passerd.feeds import HomeTimelineFeed, ListTimelineFeed, UserTimelineFeed, MentionsFeed, DirectMessagesFeed, ThrottlerMessage
from passerd.scheduler import ApiScheduler
from passerd import dialogs
from passerd.dialogs import Dialog, CommandDialog, CommandHelpMixin, attach_dialog_to_channel, attach_dialog_to_bot
from passerd.util import try_unicode, to_str
from passerd.irc import IrcUser, IrcChannel, IrcServer
from passerd.poauth import OAuthClient, oauth_consumer
from passerd import version
import oauth.oauth as oauth
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from sqlalchemy.sql.expression import func
# client/user-agent info:
####
#FIXME: use a real hostname?
MYHOST = 'passerd.server'
CLIENT_INFO = TwitterClientInfo(version.NAME, version.VERSION, version.URL)
# IRC protocol stuff:
####
# the only mode supported, right now:
SUPPORTED_CHAN_MODES = 'b'
# No user mode is supported, by now:
SUPPORTED_USER_MODES = '0'
IRC_ENCODING = 'utf-8'
# Twitter protocol stuff:
####
BASE_URL = 'https://twitter.com'
TWITTER_ENCODING = 'utf-8'
LENGTH_LIMIT = 140
# Some limits:
####
# keep latest 100 post on each channel, to create in_reply_to field.
REPLY_HISTORY_SIZE = 100
# if more than MAX_USER_INFO_FETCH users are unknown, use /statuses/friends to fetch user info.
# otherwise, just fetch individual user info
MAX_USER_INFO_FETCH = 0 # individual fetch is not implemented yet...
# the maximum number of sequential friend list page requests:
MAX_FRIEND_PAGE_REQS = 10
# minimum post age (in seconds) to allow it to be used for RTs.
# useful to avoid surprises when using the !RT command
#TODO: make this configurable
MIN_LATEST_POST_AGE = 2
# IRC protocol constants:
####
# Other error codes we may use:
ERR_NEEDREGGEDNICK = '477'
# logging helpers:
####
logger = logging.getLogger("passerd")
dbg = logger.debug
pinfo = logger.info
perror = logger.error
class ErrorReply(Exception):
"""Special exception class used to generate IRC numeric replies"""
def __init__(self, command, *args):
self.command = command
self.args = args
class MissingOAuthRegistration(Exception):
pass
class MessageTooLong(Exception):
def __init__(self, text, length):
self.text = text
self.length = length
Exception.__init__(self, 'message too long (%d characters)' % (length))
class TwitterUserInfo:
"""Just carries simple data for a Twitter user
"""
def from_data(self, d):
self.screen_name = d.twitter_screen_name
self.name = d.twitter_name
return self
def to_data(self, d):
d.twitter_screen_name = self.screen_name
d.twitter_name = self.name
return self
def __repr__(self):
return 'TwitterUserInfo(%r, %r)' % (self.screen_name, self.name)
class TwitterUserCache:
"""Caches information about Twitter users
This is server-global, and is just an interface to the twitter_users database
table.
"""
def __init__(self, proto):
self.proto = proto
self.callbacks = CallbackList()
def addCallback(self, cb, *args, **kwargs):
"""Add a new callback function
Callback function is called with arguments: (twitter_user, old_info, new_info)
old_info may be None, if it's a new user
"""
self.callbacks.addCallback(cb, *args, **kwargs)
def _change_data(self, d, old_info, new_info):
# callbacks must becalled _before_ updating the data:
self.callbacks.callback(d.twitter_id, old_info, new_info)
new_info.to_data(d)
def _new_user(self, id, info):
d = TwitterUserData(twitter_id=id)
self._change_data(d, None, info)
#FIXME: encapsulate the following session operations, somehow:
self.proto.data.session.add(d)
self.proto.data.session.commit()
return d
def _update_user_info(self, id, new_info):
d = self.lookup_id(id)
if d is None:
return self._new_user(id, new_info)
old_info = TwitterUserInfo().from_data(d)
self._change_data(d, old_info, new_info)
#FIXME: encapsulate the following session operation, somehow:
self.proto.data.session.commit()
return d
def update_user_info(self, id, screen_name, name):
id = int(id)
i = TwitterUserInfo()
i.screen_name = screen_name
i.name = name
return self._update_user_info(id, i)
def got_api_user_info(self, u):
self.update_user_info(u.id, u.screen_name, u.name)
def lookup_id(self, id):
id = int(id)
#FIXME: encapsulate the following session operations, somehow:
d = self.proto.data.query(TwitterUserData).get(id)
if d is None:
return None
return d
def lookup_screen_name(self, name):
# not
try:
u = self.proto.data.query(TwitterUserData).filter(func.lower(TwitterUserData.twitter_screen_name)==name.lower()).one()
except MultipleResultsFound:
# multiple matches are possible if screen_names are reused.
# if that happens, be on the safe side: don't return anything
u = None
except NoResultFound:
u = None
return u
class TwitterIrcUser(IrcUser):
"""Common class for multiple methods of contacting IRC users"""
def _target_params(self, params):
"""Must return a dictionary containing user_id or screen_name, depending on
how much information we already have about the user.
"""
raise NotImplementedError("_target_params not implemented")
def send_direct_message(self, text):
d = defer.Deferred()
ok = []
def got_msg(msg):
ok.append(msg)
d.callback(msg)
def done(*args):
if not ok:
self.proto.notice("ERROR: Didn't get direct message info back when sending DM")
self.proto.api.send_direct_message(text, delegate=got_msg, params=self._target_params()).addCallbacks(done, d.errback)
return d
def messageReceived(self, sender, msg):
assert (sender is self.proto.the_user)
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
#TODO: maybe there's a better error code for this?
raise ErrorReply(irc.RPL_AWAY, self.nick, ':message too long (%d characters), not sent.' % (len(msg)))
def doit():
self.send_direct_message(msg).addCallbacks(done, error)
def done(msg):
self.proto.notice("Direct Message to %s sent. ID: %s" % (self.nick, msg.id))
def error(e):
self.proto.send_reply(irc.RPL_AWAY, self.nick, ":Error sending Direct Message: %s" % (e.value))
doit()
class UnavailableTwitterData:
"""Fake TwitterUserData object for unavailable info"""
def __init__(self, id):
self.twitter_id = id
twitter_screen_name = property(lambda self: 'user-id-%s' % (self.twitter_id))
twitter_name = property(lambda self: 'Twitter User (info not fetched yet)')
class CachedTwitterIrcUser(TwitterIrcUser):
"""An IrcUser object for cached Twitter user info
Objects of this class may be short-lived, just to return info of a random
Twitter user for which we don't have much data.
"""
def __init__(self, proto, cache, id):
IrcUser.__init__(self, proto)
self._twitter_id = id
self.cache = cache
self._data = None
def _target_params(self):
return {'user_id':self._twitter_id}
def data_changed(self, old_info, new_info):
dbg("CachedTwitterIrcUser.data_changed! %r %r" % (old_info, new_info))
if (old_info is None) or (old_info.screen_name != new_info.screen_name):
self.notifyNickChange(str(new_info.screen_name))
def __get_data(self):
if self._data is None:
self._data = self.cache.lookup_id(self._twitter_id)
return self._data
def _get_data(self):
d = self.__get_data()
if d is None:
return UnavailableTwitterData(self._twitter_id)
return d
def has_data(self):
"""Checks if the Twitter user info is known"""
return (self.__get_data() is not None)
data = property(_get_data)
nick = property(lambda self: str(self.data.twitter_screen_name))
username = property(lambda self: str(self.data.twitter_screen_name))
real_name = property(lambda self: self.data.twitter_name.encode('utf-8'))
hostname = property(lambda self: 'twitter.com')
class UnknownTwitterUser(TwitterIrcUser):
"""An IrcUser object for an user we don't know anything about, but may be a valid Twitter user"""
def __init__(self, proto, nickname):
self.proto = proto
self.nick = nickname
self.username = nickname
real_name = 'Unknown User'
hostname = 'twitter.com'
def _target_params(self):
return {'screen_name':self.nick}
class TwitterIrcUserCache:
"""Cache of CachedTwitterIrcUser objects
A TwitterIrcUserCache is client-specific (not server-global), and takes
care of creating CachedTwitterIrcUser objects for some queries.
"""
def __init__(self, proto, cache):
self.proto = proto
self.cache = cache
self.cache.addCallback(self._user_changed)
self._watched_ids = {}
def _user_changed(self, id, old_info, new_info):
dbg("user_changed: %r, %r, %r" % (id, old_info, new_info))
if id in self._watched_ids:
dbg("user_changed (%s): is being watched." % (id))
u = self._get_user(id).data_changed(old_info, new_info)
def _get_user(self, id):
u = CachedTwitterIrcUser(self.proto, self.cache, id)
return u
def watch_user_id(self, id):
"""Start watching user ID for changes"""
self._watched_ids[id] = True
def watch_user_ids(self, ids):
for id in ids:
self.watch_user_id(id)
def watch_user(self, u):
self.watch_user_id(u._twitter_id)
def get_user(self, id):
return self._get_user(id)
def fetch_individual_user_info(self, unknown_users):
#TODO: implement me
pass
def fetch_all_friend_info(self, user, unknown_users):
#TODO: unify this paging code with the one on FriendlistMixIn
reqs = []
def request_cursor(cursor):
self.proto.dbg("requesting a page from the friend list: %s" % (str(cursor)))
reqs.append(cursor)
self.proto.api.list_friends(got_user, user=user, params={'cursor':cursor},
page_delegate=end_page).addCallbacks(done, error)
def got_user(u):
self.proto.global_twuser_cache.got_api_user_info(u)
def end_page(next, prev):
unk = [u for u in unknown_users if not u.has_data()]
num = len(unk)
if num == 0:
self.proto.notice("I know all friends of %s, now!" % (user))
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addEntryCallback(self.got_entry)
f.addErrback(self.refresh_error)
f.addRawErrback(self.raw_refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
dbg("nickname %s not found", nick)
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
dbg("no posts by uid %s", uid)
return None
if substring:
matches = []
i = 1
while i <= len(recent):
r = recent[-i]
text = full_entity_decode(r.text)
#TODO: make it more flexible, ignoring punctuation and spaces
- if substring.lower() in text:
+ if substring.lower() in text.lower():
matches.append(r)
i += 1
if not matches:
return None
if len(matches) > 1:
raise Exception("Multiple matches for [%s] on posts by %s" % (substring, nick))
# yay, single match:
r = matches[0]
else:
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent, I don't know if it's the one you want. Use words from the text to identify it" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
dbg("%s got_entry. id: %s", self.name, e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("%s refresh error: %r", self.name, e)
if isinstance(e, twisted.web.error.Error):
if str(e.status) == '503':
return self.bot_notice("Look! A flying whale! -- %s" % (e))
if isinstance(e, ThrottlerMessage):
# throttler messages are shown directly
return self.bot_notice(str(e))
self.bot_notice("error refreshing feed: %s" % (e))
def raw_refresh_error(self, e):
dbg("%s raw refresh error: %r", self.name, e)
if isinstance(e, twisted.web.error.Error):
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.status == '400' and remaining == 0:
self.wait_rate_limit()
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You can still try to fetch new tweets using `!`. Also, '
'you can check the rate limit using `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallbacks(done, error)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
def error(e):
self.bot_msg('error refreshing: %s' % (e.value))
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
return [self.proto.passerd_bot, self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
|
ehabkost/passerd
|
ddb8fd393da34dcaa703eb16e6aae9ca362e1f1f
|
handle AWAY command
|
diff --git a/NEWS.markdown b/NEWS.markdown
index 54f610f..c748592 100644
--- a/NEWS.markdown
+++ b/NEWS.markdown
@@ -1,86 +1,87 @@
### Current development version:
* Support for Python 2.4
* Send MOTD when welcoming user, as some clients and scripts expect MOTD to be
always present
+* Handle AWAY messages from clients (simply ignoring the away message)
* Bugs fixed:
* issue #76: handle windows-1252 chars
* issue #83: support Python 2.4
* issue #82: unicode handling on `!rt`
* issue #84: feeds still running after disconnect
* issue #30: don't show every friend from a user on #@user channel
* issue #55: send MOTD when user connects
* issue #71: don't flood the user with error messages
### Passerd 0.1.0 - 24 Jan 2010
* Add a simple scheduling algorithm that will make sure Passerd don't kill the
Twitter API rate-limit if the user joins too many Passerd channels.
* Fix auto-`@` of nickname replies when nicknames have digits on it
* Set timeout on API calls to avoid getting stuck if HTTP requests take too
long to reply
* Retweets are shown as messages from the original poster, with a note
by passerd-bot
(configurable by `!be concise` option)
* Multi-line tweets aren't shown as multiple lines anymore
(configurable by `!be verbose` option)
* Lower-level `!config` command to set specific configuration variables
* Support for running Passerd in _daemon_ mode
* Retweet support using `!rt` command
### Passerd 0.0.5 - 6 Jan 2010
* Don't continue refreshing feeds if rate-limit is hit. This is a temporary
solution until a true rate-limit-adjusting scheduler is written
* Unify `passerd-bot` commands and implementation of `!command` on `#twitter`
* Including a help system
* Add a `!post` command (aliases: `!tw`, `!twit`, `!update`)
* Paranoid mode: if you are afraid of posting by mistake when typing on
your IRC client, you can enable a "paranoid" mode using the `!be paranoid`
command.
When in this mode, you can only post to twitter using `!post` (or the aliases
above)
### Passerd 0.0.4.2 - 28 Dec 2009
* Updated twitty-twister version. On 0.0.4, I forgot to update the
twitty-twister git commit reference, and broke twitter posting.
### Passerd 0.0.4.1 - 28 Dec 2009
* Fix a problem on the OAuth access token request method. A POST
request with no Content-Length may case a 411 Length Required
error (probably on some proxy servers).
* Thanks to Bogdano Arendartchuk for the fix.
### Passerd 0.0.4 - 27 Dec 2009
* Ability to follow lists using `#@username/list` channels
* Ability to get updates from a single user using `#@username` channels
* Implement #mentions channel, for mentions of `@username`
* OAuth support! Now you don't need to give your Twitter password to
Passerd (and you'll get a nice "from Passerd" note on your Twits. :)
* Optional nickserv-style authentication support
* Better error messages (using a `passerd-bot` IRC user)
* Now with a real (but still a bit ugly) web page at [passerd.raisama.net](http://passerd.raisama.net/)
### Passerd 0.0.3 - 18 Dec 2009
* Ability to send updates to Twitter
* Fetch detailed user info from Twitter on-demand, only if necessary
* Basic command-line option support
* Implement Twitter follow/unfollow as IRCK KICK/INVITE
### Passerd 0.0.2 - 15 Dec 2009
* List Twitter friends as IRC contacts
### Passerd 0.0.1 - 14 Dec 2009
* Basic Twitter reading ability
diff --git a/passerd/ircd.py b/passerd/ircd.py
index c367ecb..03716da 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -1217,1024 +1217,1030 @@ class PasserdCommands(CommandHelpMixin, CommandDialog):
if not r:
if substring:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
else:
self.message(u"no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (local/twitter)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addEntryCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def aborted(self):
return self._aborted
def abort(self):
"""Makes all @check_aborted functions stop doing anything
"""
dbg("abort")
#FIXME: we need to keep track of current requests/connections and
# abort all of them, instead of letting them continue running,
# but just ignoring the replies. The scheduler may be a good place
# to keep track of all pending requests
self._aborted = True
self._stop_scheduler()
@check_aborted
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
@check_aborted
def send_motd(self):
self.send_reply(irc.RPL_MOTDSTART, ":- %s Message of the day - " % (self.myhost))
self.send_reply(irc.RPL_MOTD, ":- Welcome to Passerd")
self.send_reply(irc.RPL_MOTD, ":- For additional information and help, see %s" % (version.URL))
self.send_reply(irc.RPL_ENDOFMOTD, ":End of MOTD command")
@check_aborted
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
@check_aborted
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _stop_scheduler(self):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
@check_aborted
def _set_scheduler(self, scheduler):
self._stop_scheduler()
self.scheduler = scheduler
def _userQuit(self, reason):
dbg("_userQuit: %r", reason)
self.dm_feed.stop_refreshing()
dbg("joined channels: %r", self.joined_channels)
# list will change under our feet, so copy it:
joined = self.joined_channels[:]
for ch in joined:
dbg("ch: %r", ch)
self.leave_channel(ch, reason)
# stop everything we are doing
self.abort()
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
dbg("dmError: %r", e)
self.notice("Error pulling Direct Messages: %s" % (e))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
@check_aborted
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
@check_aborted
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_channel(self, chan, reason):
dbg("leaving channel %r", chan)
if chan in self.joined_channels:
dbg("chan %r is joined", chan)
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
+ def irc_AWAY(self, prefix, args):
+ if args:
+ self.send_reply(irc.RPL_NOWAWAY, ':You have been marked as being away')
+ else:
+ self.send_reply(irc.RPL_UNAWAY, ':You are no longer marked as being away')
+
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
def irc_MOTD(self, p, args):
self.send_motd()
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
@check_aborted
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, version.VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, version.VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
self.send_motd()
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(timeout=self.factory.opts.api_timeout, *args, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = version.USER_AGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
channel = ListChannel(self, user, list_name)
if channel:
self.channels[name] = channel
return channel
def get_channel(self, name):
return self.channels.get(name)
def get_target(self, name):
if name.startswith('#'):
return self.get_channel(name)
else:
return self.get_user(name)
def mask_matches(self, mask):
#FIXME: match wildcards?
u = self.get_user(mask)
if u:
yield u
def who_matches(self, mask):
#TODO: make WHO list channel users
for u in self.mask_matches(mask):
#XXX: WTF do "H" and "G" mean?
yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
def whois_twitter_user(self, u, tu):
self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
#FIXME: find a better way to send user information, instead of RPL_AWAY
# - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
def oneline(s):
#FIXME: create a escape_post() function
return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
def whois_mask(self, mask):
def doit():
self.dbg("fetching user info for %s" % (mask))
self.api.show_user(mask).addCallback(got_user).addErrback(error)
def got_user(tu):
self.dbg("got user info!")
self.global_twuser_cache.got_api_user_info(tu)
u = self.get_twitter_user(tu.id)
self.whois_twitter_user(u, tu)
def error(e):
self.send_reply(irc.ERR_NOSUCHNICK, mask, ':Error fetching user info - %s' % (e.value))
doit()
class PasserdFactory(Factory):
protocol = PasserdProtocol
def __init__(self, opts):
url = 'sqlite:///%s' % (opts.database)
self.opts = opts
self.data = DataStore(url)
self.data.create_tables()
self.global_twuser_cache = TwitterUserCache(self)
class PasserdGlobalOptions:
def __init__(self):
# set the defaults:
self.listen = ('0.0.0.0', 6667)
#logging:
self.logstream = sys.stderr
# list of (logger_name, level) pairs
# - sqlalchemy is too verbose on the INFO loglevel
# - enable oauth debugging, by now
self.loglevels = [(None, logging.INFO),
('sqlalchemy', logging.ERROR),
('passerd.oauth',logging.DEBUG),
('passerd.feeds',logging.DEBUG),
('passerd.scheduler',logging.DEBUG)]
self.logformat = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
self.api_timeout = 60
self.daemon_mode = False
self.pidfile = None
def parse_cmdline(args, opts):
def parse_hostport(option, optstr, value, parser):
try:
host, rawport = value.rsplit(":", 1)
port = int(rawport)
except ValueError:
parser.error("invalid listen address, expected HOST:PORT")
opts.listen = (host, port)
def set_loglevels(levels):
opts.loglevels = levels
def open_logfile(option, optstr, value, parser):
opts.logstream = open(value, 'a')
parser = optparse.OptionParser("%prog [options] <database path>")
parser.add_option("-l", "--listen", type="string",
action="callback", callback=parse_hostport,
metavar="HOST:PORT", help="listen address")
parser.add_option("-D", "--debug",
action="callback", callback=lambda *args: set_loglevels([(None,logging.DEBUG)]),
help="Enable debug logging")
parser.add_option("--logformat",
metavar="FORMAT", type="string", default=None,
help="Set the logging format")
parser.add_option("-d", "--daemon",
action="store_true", dest="daemon_mode")
parser.add_option("-L", "--log-file",
metavar="FILENAME", type="string",
action="callback", callback=open_logfile)
parser.add_option("-p", "--pid-file",
metavar="FILENAME", type="string",
dest="pidfile")
_, args = parser.parse_args(args, opts)
if not args:
parser.error("the database path is needed!")
opts.database = args[0]
return opts
def setup_logging(opts):
# root logger:
r = logging.getLogger()
if opts.logstream:
handler = logging.StreamHandler(opts.logstream)
f = logging.Formatter(opts.logformat)
handler.setFormatter(f)
r.addHandler(handler)
|
ehabkost/passerd
|
02a71f783e789f9e1a28dbe19c3788a5c4791176
|
reword INSTALL section titles
|
diff --git a/INSTALL.markdown b/INSTALL.markdown
index 3926e1f..bf245bb 100644
--- a/INSTALL.markdown
+++ b/INSTALL.markdown
@@ -1,63 +1,63 @@
-What do I need, to use Passerd?
--------------------------------
+Requirements for Passerd
+------------------------
_Passerd_ is written in Python. You need Python (of course!), and the following
Python modules:
* twisted (and its 'twisted.words' module)
* sqlite
* sqlalchemy (recommended version 0.5.4 or later)
* oauth
* A patched version of twitty-twister -- but don't worry: it is automatically fetched by `git submodule` and `./run.sh` (see run instructions below)
Optional dependencies:
* For running Passerd in _daemon_ mode:
* [python-daemon](http://pypi.python.org/pypi/python-daemon/)
* Python [lockfile](http://pypi.python.org/pypi/lockfile/) module
Below you'll find instructions to easily get the dependencies on some operating
systems:
### On Fedora
To install the dependencies on a Fedora machine, run:
yum install python-twisted python-twisted-words python-sqlalchemy python-oauth
For the optional packages:
yum install python-daemon python-lockfile
### On Mandriva
These dependencies currently match the 2010.0 release but should be ok for others:
urpmi python-twisted-words python-sqlite python-sqlalchemy python-oauth
-How do I run it?
-----------------
+How to run it
+-------------
Right now the recommended way to run Passerd is to check out the source
directly from the git repository.
### From the git repository:
* Check out the [git repository][gitrepo]
* `git clone git://github.com/ehabkost/passerd.git`
* `cd passerd`
* Run `git submodule init`
* Run `git submodule update`
* Run `./run.sh`
* Point your IRC client to server `localhost`, port `6667`
* Join the `#new-user-setup` channel on the server
* Follow the instructions from `passerd-bot`
* Have fun!
See the `USERGUIDE` file for more information.
[gitrepo]: http://github.com/ehabkost/passerd
|
ehabkost/passerd
|
fc1385ead238a1b61a2e20e78f0ab0ec919a0a61
|
error message "throttling"
|
diff --git a/passerd/feeds.py b/passerd/feeds.py
index e342ad8..fd6f369 100644
--- a/passerd/feeds.py
+++ b/passerd/feeds.py
@@ -1,206 +1,288 @@
#!/usr/bin/env python
#
# Passerd - An IRC server as a gateway to Twitter
#
# Code for continuously-updating feeds
#
# Author: Eduardo Habkost <ehabkost@raisama.net>
#
# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import time
import logging
from twisted.internet import reactor, defer
from passerd.callbacks import CallbackList
# 'count' paremeter for feed queries. It's a bit high, but this shouldn't be a
# problem as we always use the last_id parameter.
QUERY_COUNT = 100
logger = logging.getLogger('passerd.feeds')
dbg = logger.debug
+class ThrottlerMessage:
+ """Class useful to identify throttler messages on error callbacks"""
+ def __init__(self, msg):
+ self._msg = msg
+
+ def __str__(self):
+ return str(self._msg)
+
+class BackWorkingMessage(ThrottlerMessage):
+ pass
+
+class ThrottlerStopMessage(ThrottlerMessage):
+ pass
+
+class ErrorThrottler:
+ """Filter repeated error messages"""
+
+ # max number of times repeated error messages can be shown:
+ MAX_SAME_ERROR = 1
+
+ # max number of different error messages that can be shown:
+ MAX_DIFF_ERROR = 4
+
+ # informative messages:
+ SAME_ERROR_MSG = "I got the same error again. I will shut up and just tell you when things are back to normal"
+ LOTS_ERRORS_MSG = "I am getting too many errors. I will shut up and just tell you when things are back to normal"
+ BACK_WORKING = "Good! Things seem to be working again"
+
+ def __init__(self, real_error_fn):
+ self._real_fn = real_error_fn
+ self._last_err = None
+ self._same_err_count = 0
+ self._any_err_count = 0
+ self._stopped = False
+
+ def _stop(self, msg):
+ self._real_fn(ThrottlerStopMessage(msg))
+ self._stopped = True
+
+ def error(self, e):
+ self._any_err_count += 1
+ msg = str(e)
+ if msg == self._last_err:
+ self._same_err_count += 1
+ else:
+ self._same_err_count = 1
+ self._last_err = msg
+
+ if self._stopped:
+ return
+
+ if self._same_err_count > self.MAX_SAME_ERROR:
+ return self._stop(self.SAME_ERROR_MSG)
+
+ if self._any_err_count > self.MAX_DIFF_ERROR:
+ return self._stop(self.LOTS_ERRORS_MSG)
+
+ return self._real_fn(e)
+
+ def ok(self):
+ if self._stopped:
+ self._real_fn(BackWorkingMessage(self.BACK_WORKING))
+ self._same_err_count = 0
+ self._any_err_count = 0
+ self._stopped = False
+
+
class TwitterFeed:
def __init__(self, proto):
self.proto = proto
self.updater = None
- self.callbacks = CallbackList()
+ self.entry_cb = CallbackList()
self.errbacks = CallbackList()
+ self.raw_errbacks = CallbackList()
self.continue_refreshing = False
self.next_refresh = None
self.loading = False
self._last_id = None
+ self._error_handler = ErrorThrottler(self.report_error)
def _last_id_var(self):
return self.LAST_ID_VAR
def update_last_id(self, last_id):
self._last_id = last_id
self.proto.set_user_var(self._last_id_var(), last_id)
@property
def last_id(self):
if self._last_id is None:
self._last_id = self.proto.user_var(self._last_id_var())
return self._last_id
- def addCallback(self, *args, **kwargs):
+ def addEntryCallback(self, *args, **kwargs):
"""Add a callback for new entries"""
- self.callbacks.addCallback(*args, **kwargs)
+ self.entry_cb.addCallback(*args, **kwargs)
def addErrback(self, *args, **kwargs):
"""Add a callbck for loading errors"""
self.errbacks.addCallback(*args, **kwargs)
+ def addRawErrback(self, *args, **kwargs):
+ """Add a "raw" error callback, without error throttling"""
+ self.raw_errbacks.addCallback(*args, **kwargs)
+
@property
def api(self):
return self.proto.api
@property
def scheduler(self):
return self.proto.scheduler
def refresh_resched(self):
if self.updater is not None:
self.updater.resched()
def _refresh(self, last_id=None):
if last_id is None:
last_id = self.last_id
entries = []
d = defer.Deferred()
def doit():
args = {}
if last_id:
args['since_id'] = last_id
args['count'] = str(QUERY_COUNT)
- self._timeline(got_entry, args).addCallbacks(finished, error)
+ return self._timeline(got_entry, args).addCallbacks(finished, error)
dbg("_refresh returning")
- def error(*args):
- dbg("_refresh error %r" % (args,))
- d.errback(*args)
- self.errbacks.callback(*args)
+ def error(e):
+ dbg("_refresh error %r", e)
+ return e
# store the entries and then show them in chronological order:
def got_entry(e):
dbg("got an entry")
entries.insert(0, e)
def finished(*args):
dbg("finished loading %r" % (args,))
+
+ # tell the error throttler that things are ok, now:
+ self._error_handler.ok()
+
for e in entries:
- self.callbacks.callback(e)
+ self.entry_cb.callback(e)
if self.last_id is None or int(e.id) > int(self.last_id):
self.update_last_id(e.id)
- d.callback(len(entries))
+ return len(entries)
+
+ return doit()
- doit()
- return d
+ def report_error(self, e):
+ """Send an error message back to interested parties"""
+ self.errbacks.callback(e)
def refresh(self):
def doit():
if self.loading:
dbg("Won't refresh now. Still loading...")
return
self.loading = True
self._refresh().addCallbacks(done, error).addBoth(resched)
- def error(*args):
+ def error(e):
dbg("ERROR while refreshing")
+ self.raw_errbacks.callback(e)
+ self._error_handler.error(e.value)
+ return e
def done(num_entries):
dbg("got %d entries." % (num_entries))
def resched(*args):
self.loading = False
- dbg("rescheduling...")
+ dbg("rescheduling... [%r]", args)
self.refresh_resched()
return doit()
def stop_refreshing(self):
if self.updater is not None:
self.updater.destroy()
self.updater = None
def start_refreshing(self):
if self.updater is None:
self.updater = self.scheduler.new_updater(self.refresh)
# yes, this is cheating, but I don't want to make the user wait for
# too long
#FIXME: just add support for 'one-shot lower-latency' calls on
# the scheduler, instead of cheating
self.refresh()
class ListTimelineFeed(TwitterFeed):
def __init__(self, proto, list_user, list_name):
TwitterFeed.__init__(self, proto)
self.list_user = list_user
self.list_name = list_name
def _last_id_var(self):
return "last_status_id_@%s/%s" % (self.list_user, self.list_name)
def _timeline(self, delegate, args):
return self.api.list_timeline(delegate, self.list_user,
self.list_name, args)
class HomeTimelineFeed(TwitterFeed):
LAST_ID_VAR = 'home_last_status_id'
def _timeline(self, delegate, args):
dbg("will try to use the API:")
return self.api.home_timeline(delegate, args)
class UserTimelineFeed(TwitterFeed):
def __init__(self, proto, user):
TwitterFeed.__init__(self, proto)
self.user = user
def _last_id_var(self):
return "last_status_id_@%s" % (self.user)
def _timeline(self, delegate, args):
return self.api.user_timeline(delegate, self.user, args)
class MentionsFeed(TwitterFeed):
LAST_ID_VAR = 'mentions_last_status_id'
def _timeline(self, delegate, args):
return self.api.mentions(delegate, args)
class DirectMessagesFeed(TwitterFeed):
LAST_ID_VAR = 'direct_messages_last_id'
def _timeline(self, delegate, args):
return self.api.direct_messages(delegate, args)
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 8603f6f..c367ecb 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -1,2054 +1,2066 @@
#!/usr/bin/env python
#
# Passerd - An IRC server as a gateway to Twitter
#
# Author: Eduardo Habkost <ehabkost@raisama.net>
#
# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys, os, logging, time, re, random
import fcntl, signal
import gc
import optparse
import rfc822 # for date/time parsing
from twisted.words.protocols import irc
from twisted.words.protocols.irc import IRC
from twisted.internet.protocol import Factory
from twisted.internet import reactor, defer
import twisted.web.error
from twittytwister.twitter import Twitter, TwitterClientInfo
from passerd.data import DataStore, TwitterUserData
from passerd.callbacks import CallbackList
from passerd.utils import full_entity_decode
-from passerd.feeds import HomeTimelineFeed, ListTimelineFeed, UserTimelineFeed, MentionsFeed, DirectMessagesFeed
+from passerd.feeds import HomeTimelineFeed, ListTimelineFeed, UserTimelineFeed, MentionsFeed, DirectMessagesFeed, ThrottlerMessage
from passerd.scheduler import ApiScheduler
from passerd import dialogs
from passerd.dialogs import Dialog, CommandDialog, CommandHelpMixin, attach_dialog_to_channel, attach_dialog_to_bot
from passerd.util import try_unicode, to_str
from passerd.irc import IrcUser, IrcChannel, IrcServer
from passerd.poauth import OAuthClient, oauth_consumer
from passerd import version
import oauth.oauth as oauth
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from sqlalchemy.sql.expression import func
# client/user-agent info:
####
#FIXME: use a real hostname?
MYHOST = 'passerd.server'
CLIENT_INFO = TwitterClientInfo(version.NAME, version.VERSION, version.URL)
# IRC protocol stuff:
####
# the only mode supported, right now:
SUPPORTED_CHAN_MODES = 'b'
# No user mode is supported, by now:
SUPPORTED_USER_MODES = '0'
IRC_ENCODING = 'utf-8'
# Twitter protocol stuff:
####
BASE_URL = 'https://twitter.com'
TWITTER_ENCODING = 'utf-8'
LENGTH_LIMIT = 140
# Some limits:
####
# keep latest 100 post on each channel, to create in_reply_to field.
REPLY_HISTORY_SIZE = 100
# if more than MAX_USER_INFO_FETCH users are unknown, use /statuses/friends to fetch user info.
# otherwise, just fetch individual user info
MAX_USER_INFO_FETCH = 0 # individual fetch is not implemented yet...
# the maximum number of sequential friend list page requests:
MAX_FRIEND_PAGE_REQS = 10
# minimum post age (in seconds) to allow it to be used for RTs.
# useful to avoid surprises when using the !RT command
#TODO: make this configurable
MIN_LATEST_POST_AGE = 2
# IRC protocol constants:
####
# Other error codes we may use:
ERR_NEEDREGGEDNICK = '477'
# logging helpers:
####
logger = logging.getLogger("passerd")
dbg = logger.debug
pinfo = logger.info
perror = logger.error
class ErrorReply(Exception):
"""Special exception class used to generate IRC numeric replies"""
def __init__(self, command, *args):
self.command = command
self.args = args
class MissingOAuthRegistration(Exception):
pass
class MessageTooLong(Exception):
def __init__(self, text, length):
self.text = text
self.length = length
Exception.__init__(self, 'message too long (%d characters)' % (length))
class TwitterUserInfo:
"""Just carries simple data for a Twitter user
"""
def from_data(self, d):
self.screen_name = d.twitter_screen_name
self.name = d.twitter_name
return self
def to_data(self, d):
d.twitter_screen_name = self.screen_name
d.twitter_name = self.name
return self
def __repr__(self):
return 'TwitterUserInfo(%r, %r)' % (self.screen_name, self.name)
class TwitterUserCache:
"""Caches information about Twitter users
This is server-global, and is just an interface to the twitter_users database
table.
"""
def __init__(self, proto):
self.proto = proto
self.callbacks = CallbackList()
def addCallback(self, cb, *args, **kwargs):
"""Add a new callback function
Callback function is called with arguments: (twitter_user, old_info, new_info)
old_info may be None, if it's a new user
"""
self.callbacks.addCallback(cb, *args, **kwargs)
def _change_data(self, d, old_info, new_info):
# callbacks must becalled _before_ updating the data:
self.callbacks.callback(d.twitter_id, old_info, new_info)
new_info.to_data(d)
def _new_user(self, id, info):
d = TwitterUserData(twitter_id=id)
self._change_data(d, None, info)
#FIXME: encapsulate the following session operations, somehow:
self.proto.data.session.add(d)
self.proto.data.session.commit()
return d
def _update_user_info(self, id, new_info):
d = self.lookup_id(id)
if d is None:
return self._new_user(id, new_info)
old_info = TwitterUserInfo().from_data(d)
self._change_data(d, old_info, new_info)
#FIXME: encapsulate the following session operation, somehow:
self.proto.data.session.commit()
return d
def update_user_info(self, id, screen_name, name):
id = int(id)
i = TwitterUserInfo()
i.screen_name = screen_name
i.name = name
return self._update_user_info(id, i)
def got_api_user_info(self, u):
self.update_user_info(u.id, u.screen_name, u.name)
def lookup_id(self, id):
id = int(id)
#FIXME: encapsulate the following session operations, somehow:
d = self.proto.data.query(TwitterUserData).get(id)
if d is None:
return None
return d
def lookup_screen_name(self, name):
# not
try:
u = self.proto.data.query(TwitterUserData).filter(func.lower(TwitterUserData.twitter_screen_name)==name.lower()).one()
except MultipleResultsFound:
# multiple matches are possible if screen_names are reused.
# if that happens, be on the safe side: don't return anything
u = None
except NoResultFound:
u = None
return u
class TwitterIrcUser(IrcUser):
"""Common class for multiple methods of contacting IRC users"""
def _target_params(self, params):
"""Must return a dictionary containing user_id or screen_name, depending on
how much information we already have about the user.
"""
raise NotImplementedError("_target_params not implemented")
def send_direct_message(self, text):
d = defer.Deferred()
ok = []
def got_msg(msg):
ok.append(msg)
d.callback(msg)
def done(*args):
if not ok:
self.proto.notice("ERROR: Didn't get direct message info back when sending DM")
self.proto.api.send_direct_message(text, delegate=got_msg, params=self._target_params()).addCallbacks(done, d.errback)
return d
def messageReceived(self, sender, msg):
assert (sender is self.proto.the_user)
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
#TODO: maybe there's a better error code for this?
raise ErrorReply(irc.RPL_AWAY, self.nick, ':message too long (%d characters), not sent.' % (len(msg)))
def doit():
self.send_direct_message(msg).addCallbacks(done, error)
def done(msg):
self.proto.notice("Direct Message to %s sent. ID: %s" % (self.nick, msg.id))
def error(e):
self.proto.send_reply(irc.RPL_AWAY, self.nick, ":Error sending Direct Message: %s" % (e.value))
doit()
class UnavailableTwitterData:
"""Fake TwitterUserData object for unavailable info"""
def __init__(self, id):
self.twitter_id = id
twitter_screen_name = property(lambda self: 'user-id-%s' % (self.twitter_id))
twitter_name = property(lambda self: 'Twitter User (info not fetched yet)')
class CachedTwitterIrcUser(TwitterIrcUser):
"""An IrcUser object for cached Twitter user info
Objects of this class may be short-lived, just to return info of a random
Twitter user for which we don't have much data.
"""
def __init__(self, proto, cache, id):
IrcUser.__init__(self, proto)
self._twitter_id = id
self.cache = cache
self._data = None
def _target_params(self):
return {'user_id':self._twitter_id}
def data_changed(self, old_info, new_info):
dbg("CachedTwitterIrcUser.data_changed! %r %r" % (old_info, new_info))
if (old_info is None) or (old_info.screen_name != new_info.screen_name):
self.notifyNickChange(str(new_info.screen_name))
def __get_data(self):
if self._data is None:
self._data = self.cache.lookup_id(self._twitter_id)
return self._data
def _get_data(self):
d = self.__get_data()
if d is None:
return UnavailableTwitterData(self._twitter_id)
return d
def has_data(self):
"""Checks if the Twitter user info is known"""
return (self.__get_data() is not None)
data = property(_get_data)
nick = property(lambda self: str(self.data.twitter_screen_name))
username = property(lambda self: str(self.data.twitter_screen_name))
real_name = property(lambda self: self.data.twitter_name.encode('utf-8'))
hostname = property(lambda self: 'twitter.com')
class UnknownTwitterUser(TwitterIrcUser):
"""An IrcUser object for an user we don't know anything about, but may be a valid Twitter user"""
def __init__(self, proto, nickname):
self.proto = proto
self.nick = nickname
self.username = nickname
real_name = 'Unknown User'
hostname = 'twitter.com'
def _target_params(self):
return {'screen_name':self.nick}
class TwitterIrcUserCache:
"""Cache of CachedTwitterIrcUser objects
A TwitterIrcUserCache is client-specific (not server-global), and takes
care of creating CachedTwitterIrcUser objects for some queries.
"""
def __init__(self, proto, cache):
self.proto = proto
self.cache = cache
self.cache.addCallback(self._user_changed)
self._watched_ids = {}
def _user_changed(self, id, old_info, new_info):
dbg("user_changed: %r, %r, %r" % (id, old_info, new_info))
if id in self._watched_ids:
dbg("user_changed (%s): is being watched." % (id))
u = self._get_user(id).data_changed(old_info, new_info)
def _get_user(self, id):
u = CachedTwitterIrcUser(self.proto, self.cache, id)
return u
def watch_user_id(self, id):
"""Start watching user ID for changes"""
self._watched_ids[id] = True
def watch_user_ids(self, ids):
for id in ids:
self.watch_user_id(id)
def watch_user(self, u):
self.watch_user_id(u._twitter_id)
def get_user(self, id):
return self._get_user(id)
def fetch_individual_user_info(self, unknown_users):
#TODO: implement me
pass
def fetch_all_friend_info(self, user, unknown_users):
#TODO: unify this paging code with the one on FriendlistMixIn
reqs = []
def request_cursor(cursor):
self.proto.dbg("requesting a page from the friend list: %s" % (str(cursor)))
reqs.append(cursor)
self.proto.api.list_friends(got_user, user=user, params={'cursor':cursor},
page_delegate=end_page).addCallbacks(done, error)
def got_user(u):
self.proto.global_twuser_cache.got_api_user_info(u)
def end_page(next, prev):
unk = [u for u in unknown_users if not u.has_data()]
num = len(unk)
if num == 0:
self.proto.notice("I know all friends of %s, now!" % (user))
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
- f.addCallback(self.got_entry)
+ f.addEntryCallback(self.got_entry)
f.addErrback(self.refresh_error)
+ f.addRawErrback(self.raw_refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
dbg("nickname %s not found", nick)
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
dbg("no posts by uid %s", uid)
return None
if substring:
matches = []
i = 1
while i <= len(recent):
r = recent[-i]
text = full_entity_decode(r.text)
#TODO: make it more flexible, ignoring punctuation and spaces
if substring.lower() in text:
matches.append(r)
i += 1
if not matches:
return None
if len(matches) > 1:
raise Exception("Multiple matches for [%s] on posts by %s" % (substring, nick))
# yay, single match:
r = matches[0]
else:
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent, I don't know if it's the one you want. Use words from the text to identify it" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
- dbg("#twitter got_entry. id: %s", e.id)
+ dbg("%s got_entry. id: %s", self.name, e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
+
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
- dbg("#twitter refresh error")
- #FIXME: stop showing repeated errors and just let the user know when service is back
- if e.check(twisted.web.error.Error):
- if str(e.value.status) == '503':
- self.bot_notice("Look! A flying whale! -- %s" % (e.value))
- return
+ dbg("%s refresh error: %r", self.name, e)
+ if isinstance(e, twisted.web.error.Error):
+ if str(e.status) == '503':
+ return self.bot_notice("Look! A flying whale! -- %s" % (e))
+
+ if isinstance(e, ThrottlerMessage):
+ # throttler messages are shown directly
+ return self.bot_notice(str(e))
+
+ self.bot_notice("error refreshing feed: %s" % (e))
+
+ def raw_refresh_error(self, e):
+ dbg("%s raw refresh error: %r", self.name, e)
+ if isinstance(e, twisted.web.error.Error):
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
- if e.value.status == '400' and remaining == 0:
+ if e.status == '400' and remaining == 0:
self.wait_rate_limit()
- self.bot_notice("error refreshing feed: %s" % (e.value))
-
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You can still try to fetch new tweets using `!`. Also, '
'you can check the rate limit using `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
- f._refresh(last_id=last).addCallback(done)
+ f._refresh(last_id=last).addCallbacks(done, error)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
+ def error(e):
+ self.bot_msg('error refreshing: %s' % (e.value))
+
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
return [self.proto.passerd_bot, self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class DebugCommands(CommandDialog):
"""Some misc debug commands"""
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
class PasserdCommands(CommandHelpMixin, CommandDialog):
# subcommands:
importance_debug = dialogs.CMD_IMP_DEBUGGING
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_subdialog('debug', DebugCommands(proto, chan, parent=self), 'Debugging commands')
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
if substring:
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
else:
self.message(u"no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (local/twitter)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
- self.dm_feed.addCallback(self.gotDirectMessage)
+ self.dm_feed.addEntryCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def aborted(self):
return self._aborted
def abort(self):
"""Makes all @check_aborted functions stop doing anything
"""
dbg("abort")
#FIXME: we need to keep track of current requests/connections and
# abort all of them, instead of letting them continue running,
# but just ignoring the replies. The scheduler may be a good place
# to keep track of all pending requests
self._aborted = True
self._stop_scheduler()
@check_aborted
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
@check_aborted
def send_motd(self):
self.send_reply(irc.RPL_MOTDSTART, ":- %s Message of the day - " % (self.myhost))
self.send_reply(irc.RPL_MOTD, ":- Welcome to Passerd")
self.send_reply(irc.RPL_MOTD, ":- For additional information and help, see %s" % (version.URL))
self.send_reply(irc.RPL_ENDOFMOTD, ":End of MOTD command")
@check_aborted
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
@check_aborted
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _stop_scheduler(self):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
@check_aborted
def _set_scheduler(self, scheduler):
self._stop_scheduler()
self.scheduler = scheduler
def _userQuit(self, reason):
dbg("_userQuit: %r", reason)
self.dm_feed.stop_refreshing()
dbg("joined channels: %r", self.joined_channels)
# list will change under our feet, so copy it:
joined = self.joined_channels[:]
for ch in joined:
dbg("ch: %r", ch)
self.leave_channel(ch, reason)
# stop everything we are doing
self.abort()
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
- self.notice("Error pulling Direct Messages: %s" % (e.value))
+ dbg("dmError: %r", e)
+ self.notice("Error pulling Direct Messages: %s" % (e))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
@check_aborted
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
@check_aborted
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_channel(self, chan, reason):
dbg("leaving channel %r", chan)
if chan in self.joined_channels:
dbg("chan %r is joined", chan)
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
def irc_MOTD(self, p, args):
self.send_motd()
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
@check_aborted
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, version.VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, version.VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
self.send_motd()
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(timeout=self.factory.opts.api_timeout, *args, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = version.USER_AGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
diff --git a/passerd/tests/__init__.py b/passerd/tests/__init__.py
index ccdf244..5ab7922 100644
--- a/passerd/tests/__init__.py
+++ b/passerd/tests/__init__.py
@@ -1,22 +1,22 @@
import unittest, doctest
-modules = 'dialogs formatting encoding'.split()
+modules = 'dialogs formatting encoding errors'.split()
docmodules = []
def suite():
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for n in modules:
passerd = __import__('passerd.tests.%s' % (n))
module = getattr(passerd.tests, n)
tests = loader.loadTestsFromModule(module)
suite.addTests(tests)
for dm in docmodules:
suite.addTest(doctest.DocTestSuite(dm))
return suite
if __name__ == '__main__':
unittest.TextTestRunner().run(suite())
diff --git a/passerd/tests/errors.py b/passerd/tests/errors.py
new file mode 100644
index 0000000..12120a9
--- /dev/null
+++ b/passerd/tests/errors.py
@@ -0,0 +1,147 @@
+from passerd.feeds import ErrorThrottler
+import unittest
+
+class TestErrorThrottle(unittest.TestCase):
+ def setUp(self):
+ self.log = []
+ self.t = ErrorThrottler(lambda m: self.log.append(m))
+
+ def assertLog(self, *l):
+ self.assertEquals(self.log, list(l))
+
+ def testSimpleMsg(self):
+ self.t.error("ouch")
+ self.assertLog("ouch")
+
+ def testErrorOne(self):
+ self.t.MAX_SAME_ERROR = 1
+ self.t.error("d'oh")
+ self.t.error("d'oh")
+ self.t.error("d'oh")
+ self.assertLog("d'oh", self.t.SAME_ERROR_MSG)
+
+ def testErrorMany(self):
+ self.t.MAX_SAME_ERROR = 2
+ self.t.error("d'oh")
+ self.t.error("d'oh")
+ self.t.error("d'oh")
+ self.t.error("d'oh")
+ self.t.error("d'oh")
+ self.t.error("d'oh")
+ self.t.error("d'oh")
+ self.t.error("d'oh")
+ self.assertLog("d'oh", "d'oh", self.t.SAME_ERROR_MSG)
+
+ def testErrorBackError(self):
+ self.t.MAX_SAME_ERROR = 2
+ self.t.error("ouch")
+ self.t.error("ouch")
+ self.t.error("ouch")
+ self.t.error("ouch")
+ self.t.error("ouch")
+ self.t.ok()
+ self.t.error("ouch")
+ self.t.ok()
+ self.t.error("ouch")
+ self.t.error("ouch")
+ self.t.error("ouch")
+ self.t.error("ouch")
+ self.t.ok()
+ self.t.ok()
+ self.t.error("ouch")
+ self.t.ok()
+ self.t.ok()
+ self.t.error("ouch")
+ self.t.ok()
+ self.t.error("ouch")
+ self.t.error("ouch")
+ self.t.ok()
+ self.t.error("ouch")
+ self.t.ok()
+
+ self.assertLog('ouch', 'ouch',
+ self.t.SAME_ERROR_MSG,
+ self.t.BACK_WORKING,
+ 'ouch',
+ 'ouch', 'ouch',
+ self.t.SAME_ERROR_MSG,
+ self.t.BACK_WORKING,
+ 'ouch',
+ 'ouch',
+ 'ouch', 'ouch',
+ 'ouch')
+
+ def testFewDiffErrors(self):
+ self.t.MAX_SAME_ERROR = 2
+ self.t.MAX_DIFF_ERROR = 6
+ self.t.error("ouch")
+ self.t.error("ouch")
+ self.t.error("d'oh")
+ self.t.error("ouch")
+ self.t.error("d'oh")
+ self.t.error("d'oh")
+ self.t.ok()
+ self.t.error("argh")
+
+ self.assertLog("ouch",
+ "ouch",
+ "d'oh",
+ "ouch",
+ "d'oh",
+ "d'oh",
+ "argh")
+
+ def testManyDifferrors(self):
+ self.t.MAX_SAME_ERROR = 2
+ self.t.MAX_DIFF_ERROR = 6
+ self.t.error("ouch")
+ self.t.error("ouch")
+ self.t.error("d'oh")
+ self.t.error("ouch")
+ self.t.error("d'oh")
+ self.t.error("d'oh")
+ self.t.error("argh")
+ for i in range(100):
+ self.t.error("error %d" % (i))
+ self.t.ok()
+ self.t.error("another error")
+ self.t.error("another error")
+ self.t.error("another error")
+ self.t.error("another error")
+ self.t.error("another error")
+ self.t.error("another error")
+ self.t.ok()
+ self.t.ok()
+ self.t.error("ouch")
+ self.t.error("ouch")
+ self.t.error("d'oh")
+ self.t.error("ouch")
+ self.t.error("d'oh")
+ self.t.error("d'oh")
+
+ self.assertLog("ouch",
+ "ouch",
+ "d'oh",
+ "ouch",
+ "d'oh",
+ "d'oh",
+ self.t.LOTS_ERRORS_MSG,
+ self.t.BACK_WORKING,
+ "another error", "another error",
+ self.t.SAME_ERROR_MSG,
+ self.t.BACK_WORKING,
+ "ouch",
+ "ouch",
+ "d'oh",
+ "ouch",
+ "d'oh",
+ "d'oh")
+
+ def testNonStringError(self):
+ self.t.MAX_SAME_ERROR = 2
+ self.t.error("ouch")
+ self.t.error("123")
+ self.t.error(123)
+ self.t.error(u"123")
+
+ self.assertLog("ouch", '123', 123, self.t.SAME_ERROR_MSG)
|
ehabkost/passerd
|
20381b7a66b4b460fee49b4fee4f2ca7eadea12e
|
add more python-distutils files to .gitignore
|
diff --git a/.gitignore b/.gitignore
index 6477d4f..bf7168f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,7 @@
*.pyc
tags
docs/html/*.html
.*.swp
build/
+MANIFEST
+dist/
|
ehabkost/passerd
|
6d8846c739b218d54b33380f0ad395c2146f7e0f
|
Add !debug command to isolate debugging stuf
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 4e0a971..8603f6f 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -557,1129 +557,1137 @@ class TwitterChannel(IrcChannel):
r = matches[0]
else:
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent, I don't know if it's the one you want. Use words from the text to identify it" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
dbg("#twitter got_entry. id: %s", e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("#twitter refresh error")
#FIXME: stop showing repeated errors and just let the user know when service is back
if e.check(twisted.web.error.Error):
if str(e.value.status) == '503':
self.bot_notice("Look! A flying whale! -- %s" % (e.value))
return
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.value.status == '400' and remaining == 0:
self.wait_rate_limit()
self.bot_notice("error refreshing feed: %s" % (e.value))
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You can still try to fetch new tweets using `!`. Also, '
'you can check the rate limit using `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallback(done)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
return [self.proto.passerd_bot, self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
+class DebugCommands(CommandDialog):
+ """Some misc debug commands"""
+ def dialog_init(self, proto, chan=None, *args, **kwargs):
+ self.proto = proto
+ self.chan = chan
+
+ shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
+ def command_gc(self, args):
+ self.message("Object counts: %r" % (gc.get_count(),))
+ r = gc.collect()
+ self.message("Garbage collection run. %d objects freed" % (r))
+ self.message("New object counts: %r" % (gc.get_count(),))
+
+ #TODO: add 'needs_chan' decorator
+ shorthelp_recent = "Debug the recent-post matching code"
+ def command_recent(self, args):
+ nick,substring = self.split_args(args)
+ substring = try_unicode(substring, IRC_ENCODING)
+ try:
+ r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
+ except Exception,e:
+ self.message("error: %s" % (e))
+ return
+
+ if r:
+ self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
+ else:
+ self.message("no match...")
+
+
class PasserdCommands(CommandHelpMixin, CommandDialog):
+ # subcommands:
+ importance_debug = dialogs.CMD_IMP_DEBUGGING
+
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
+ self.add_subdialog('debug', DebugCommands(proto, chan, parent=self), 'Debugging commands')
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
- shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
- importance_gc = dialogs.CMD_IMP_DEBUGGING
- def command_gc(self, args):
- self.message("Object counts: %r" % (gc.get_count(),))
- r = gc.collect()
- self.message("Garbage collection run. %d objects freed" % (r))
- self.message("New object counts: %r" % (gc.get_count(),))
-
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
- #TODO: add 'needs_chan' decorator
-
- shorthelp_recent = "Debug the recent-post matching code"
- importance_recent = dialogs.CMD_IMP_DEBUGGING
- def command_recent(self, args):
- nick,substring = self.split_args(args)
- substring = try_unicode(substring, IRC_ENCODING)
- try:
- r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
- except Exception,e:
- self.message("error: %s" % (e))
- return
-
- if r:
- self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
- else:
- self.message("no match...")
-
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
if substring:
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
else:
self.message(u"no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (local/twitter)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def aborted(self):
return self._aborted
def abort(self):
"""Makes all @check_aborted functions stop doing anything
"""
dbg("abort")
#FIXME: we need to keep track of current requests/connections and
# abort all of them, instead of letting them continue running,
# but just ignoring the replies. The scheduler may be a good place
# to keep track of all pending requests
self._aborted = True
self._stop_scheduler()
@check_aborted
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
@check_aborted
def send_motd(self):
self.send_reply(irc.RPL_MOTDSTART, ":- %s Message of the day - " % (self.myhost))
self.send_reply(irc.RPL_MOTD, ":- Welcome to Passerd")
self.send_reply(irc.RPL_MOTD, ":- For additional information and help, see %s" % (version.URL))
self.send_reply(irc.RPL_ENDOFMOTD, ":End of MOTD command")
@check_aborted
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
@check_aborted
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _stop_scheduler(self):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
@check_aborted
def _set_scheduler(self, scheduler):
self._stop_scheduler()
self.scheduler = scheduler
def _userQuit(self, reason):
dbg("_userQuit: %r", reason)
self.dm_feed.stop_refreshing()
dbg("joined channels: %r", self.joined_channels)
# list will change under our feet, so copy it:
joined = self.joined_channels[:]
for ch in joined:
dbg("ch: %r", ch)
self.leave_channel(ch, reason)
# stop everything we are doing
self.abort()
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
@check_aborted
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
@check_aborted
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_channel(self, chan, reason):
|
ehabkost/passerd
|
1fccb85bbbc7defa53542a07b3263e794d44358f
|
use commas to separate "Other commands:" listing
|
diff --git a/passerd/dialogs.py b/passerd/dialogs.py
index 5c93dfa..8c26130 100644
--- a/passerd/dialogs.py
+++ b/passerd/dialogs.py
@@ -1,323 +1,323 @@
# Passerd - An IRC server as a gateway to Twitter
#
# classes for text-based "dialogs"
#
# Author: Eduardo Habkost <ehabkost@raisama.net>
#
# Copyright (c) 2009,2010 Eduardo Pereira Habkost <ehabkost@raisama.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import re
import logging
logger = logging.getLogger("passerd")
class Dialog:
"""An abstract interface to "user dialogs"
"""
def __init__(self, *args, **kwargs):
self.patterns = []
self.message_func = None
self.parent = kwargs.get('parent', None)
self.dialog_init(*args, **kwargs)
def set_message_func(self, fn):
self.message_func = fn
def dialog_init(self, *args, **kwargs):
"""Initialize the Dialog object"""
pass
def begin(self):
"""Start the dialog"""
pass
def wait_for(self, regexp, func, flags=re.I, strip=True):
if strip:
filter = (lambda s: s.strip())
else:
filter = (lambda s: s)
self.patterns.insert(0, (filter, re.compile(regexp, flags), func) )
def unknown_message(self, msg):
self.message("Sorry, I don't know what you mean")
def error_reply(self, msg, e):
self.message("An error has occurred. Sorry. -- %s" % (e))
def recv_message(self, msg):
for filter,expr,func in self.patterns:
s = filter(msg)
m = expr.search(s)
if m:
try:
return func(msg, m)
except Exception,e:
return self.error_reply(msg, e)
return self.unknown_message(msg)
def message(self, msg):
"""Send a message to the user"""
if self.message_func is None:
raise NotImplementedError("Dialog.message: not message_func set")
return self.message_func(msg)
# command "importance", to order help system
CMD_IMP_IMPORTANT = 0 # important commands
CMD_IMP_COMMON = 2 # commonly-used commands
CMD_IMP_INTERESTING = 5 # interesting-to-know commands
CMD_IMP_UNIMPORTANT = 6 # usual but not important commands
CMD_IMP_ADVANCED = 8 # advanced commands
CMD_IMP_DEBUGGING = 8 # debugging/development commands
CMD_IMP_ALIAS = 7
CMD_IMP_DEFAULT = CMD_IMP_INTERESTING
class CommandDialog(Dialog):
"""A dialog for simple 'command args' commands"""
def __init__(self, *args, **kwargs):
self.subdialogs = []
self.commands = {}
self.cmd_prefix = ''
Dialog.__init__(self, *args, **kwargs)
self.add_alias('?', 'help')
def _set_subdialog_prefix(self, cmd, dialog):
dialog.set_cmd_prefix('%s%s ' % (self.cmd_prefix, cmd.upper()))
def set_cmd_prefix(self, prefix):
"""Set prefix for command examples on help messages
Useful for the "!command" format or for subdialogs
"""
self.cmd_prefix = prefix
for cmd,sd in self.subdialogs:
self._set_subdialog_prefix(cmd, sd)
def unknown_command(self, cmd, args):
#TODO: show help
self.message("Sorry, I don't get it. Type '%sHELP' for available commands" % (self.cmd_prefix))
def add_command(self, cmd, fn):
self.commands[cmd.lower()] = fn
def add_alias(self, alias, cmd, imp=CMD_IMP_ALIAS):
self.add_command(alias, self._command_fn(cmd))
sh = self._short_help(cmd)
if sh:
setattr(self, 'shorthelp_%s' % (alias.lower()), 'Synonym to `%s`: %s' % (cmd, sh))
setattr(self, 'importance_%s' % (alias.lower()), imp)
def _command_fn(self, cmd):
fn = getattr(self, 'command_%s' % (cmd.lower()), None)
if fn is None:
fn = self.commands.get(cmd.lower())
return fn
def add_subdialog(self, cmd, dialog, short_help=None):
def show_help(args):
dialog.show_help('%s: ' % (cmd.upper()), args)
def handle_cmd(args):
if not args:
args = ''
dialog.recv_message(args)
self.subdialogs.append( (cmd, dialog) )
dialog.set_message_func(self.message)
self._set_subdialog_prefix(cmd, dialog)
self.add_command(cmd, handle_cmd)
setattr(self, 'help_%s' % (cmd.lower()), show_help)
if short_help is None:
short_help = dialog.get_help_header()
if short_help:
setattr(self, 'shorthelp_%s' % (cmd.lower()), short_help)
def split_args(self, s):
s = s.lstrip()
parts = s.split(' ',1)
cmd = parts[0]
if len(parts) > 1:
args = parts[1]
else:
args = None
return cmd,args
def _short_help(self, cmd):
return getattr(self, 'shorthelp_%s' % (cmd.lower()), None)
def short_help(self, cmd):
sh = self._short_help(cmd)
if sh is None:
return None
# command get a full prefix
if self._command_fn(cmd):
prefix = self.cmd_prefix
else:
prefix = ''
return '%s%s - %s' % (prefix, cmd.upper(), sh)
def _long_help(self, cmd, args):
fn = getattr(self, 'help_%s' % (cmd.lower()), None)
if fn:
return fn(args)
sh = self.short_help(cmd)
if sh:
self.message(sh)
return
self.message("Unknown help topic: %s" % (cmd))
def get_help_header(self):
return getattr(self, 'help_header', None)
def show_help_header(self, args):
h = self.get_help_header()
if h:
self.message(h)
def _topic_importance(self, t):
r = getattr(self, 'importance_%s' % (t.lower()), None)
if r is None:
return CMD_IMP_DEFAULT
else:
return r
def help_topics(self):
r = []
for a in dir(self):
if a.startswith('shorthelp_'):
_,t = a.split('_',1)
imp = self._topic_importance(t)
r.append( (imp, t) )
r.sort()
return r
def show_help(self, prefix, args):
if args:
cmd,rest = self.split_args(args)
return self._long_help(cmd, rest)
topics = []
commands = []
for imp,t in self.help_topics():
if self._command_fn(t):
commands.append( (imp,t) )
else:
topics.append( (imp,t) )
self.show_help_header(args)
if commands:
main = []
rest = []
for imp,c in commands:
if imp <= CMD_IMP_INTERESTING:
main.append(c)
else:
rest.append(c)
if main:
self.message('%sAvailable commands:' % (prefix))
for c in main:
self.message(self.short_help(c))
if rest:
if main: name='Other commands'
else: name='Available commands'
pref = self.cmd_prefix
- clist = ' '.join(['%s%s' % (pref,c.upper()) for c in rest])
+ clist = ', '.join(['%s%s' % (pref,c.upper()) for c in rest])
self.message("%s: %s" % (name, clist))
if topics:
self.message('Other help topics:' % (prefix))
for t in topics:
self.message(self.short_help(t))
self.show_help_footer(args)
def show_help_footer(self, args):
pass
def cmd_syntax_str(self, cmd, args):
if args: suffix = ' %s' % (args)
else: suffix = ''
return 'Usage: %s%s%s' % (self.cmd_prefix, cmd.upper(), suffix)
def cmd_syntax(self, cmd, args):
self.message(self.cmd_syntax_str(cmd, args))
def help_help(self, args):
self.cmd_syntax('help', 'command-or-topic')
def command_help(self, args):
self.show_help('', args)
def try_msg(self, msg, unknown_fn=None):
cmd,args = self.split_args(msg)
fn = self._command_fn(cmd)
if fn is None:
return False,(cmd,args)
return True,fn(args)
def recv_message(self, msg):
try:
worked,r = self.try_msg(msg)
if worked:
return r
else:
cmd,args = r
return self.unknown_command(cmd, args)
except Exception,e:
self.message("Ouch! An unexpected fatal error has occurred. I am very sorry. [%s]" % (e))
logger.error("Exception on dialog %r. msg: %r" % (self, msg))
logger.exception(e)
class CommandHelpMixin:
shorthelp_help = 'Show help'
importance_help = CMD_IMP_UNIMPORTANT
def attach_dialog_to_channel(dialog, chan, bot_user):
def doit():
chan.add_msg_notifier(got_chan_msg)
dialog.set_message_func(send_message)
def got_chan_msg(ch, sender, msg):
assert ch is chan
dialog.recv_message(msg)
def send_message(msg):
chan.send_message(bot_user, msg)
doit()
def attach_dialog_to_bot(dialog, proto, real_user, bot):
def doit():
bot.add_msg_notifier(got_msg)
dialog.set_message_func(send_message)
def got_msg(u, sender, msg):
assert u is bot
dialog.recv_message(msg)
def send_message(msg):
proto.send_notice(bot, real_user, msg)
doit()
|
ehabkost/passerd
|
78c93311e8aa3b2e04ba1721591ac8cb8f14be0a
|
CommandDialog: show exception info as dialog replies
|
diff --git a/passerd/dialogs.py b/passerd/dialogs.py
index 850f993..5c93dfa 100644
--- a/passerd/dialogs.py
+++ b/passerd/dialogs.py
@@ -1,314 +1,323 @@
# Passerd - An IRC server as a gateway to Twitter
#
# classes for text-based "dialogs"
#
# Author: Eduardo Habkost <ehabkost@raisama.net>
#
# Copyright (c) 2009,2010 Eduardo Pereira Habkost <ehabkost@raisama.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import re
+
+import logging
+logger = logging.getLogger("passerd")
+
class Dialog:
"""An abstract interface to "user dialogs"
"""
def __init__(self, *args, **kwargs):
self.patterns = []
self.message_func = None
self.parent = kwargs.get('parent', None)
self.dialog_init(*args, **kwargs)
def set_message_func(self, fn):
self.message_func = fn
def dialog_init(self, *args, **kwargs):
"""Initialize the Dialog object"""
pass
def begin(self):
"""Start the dialog"""
pass
def wait_for(self, regexp, func, flags=re.I, strip=True):
if strip:
filter = (lambda s: s.strip())
else:
filter = (lambda s: s)
self.patterns.insert(0, (filter, re.compile(regexp, flags), func) )
def unknown_message(self, msg):
self.message("Sorry, I don't know what you mean")
def error_reply(self, msg, e):
self.message("An error has occurred. Sorry. -- %s" % (e))
def recv_message(self, msg):
for filter,expr,func in self.patterns:
s = filter(msg)
m = expr.search(s)
if m:
try:
return func(msg, m)
except Exception,e:
return self.error_reply(msg, e)
return self.unknown_message(msg)
def message(self, msg):
"""Send a message to the user"""
if self.message_func is None:
raise NotImplementedError("Dialog.message: not message_func set")
return self.message_func(msg)
# command "importance", to order help system
CMD_IMP_IMPORTANT = 0 # important commands
CMD_IMP_COMMON = 2 # commonly-used commands
CMD_IMP_INTERESTING = 5 # interesting-to-know commands
CMD_IMP_UNIMPORTANT = 6 # usual but not important commands
CMD_IMP_ADVANCED = 8 # advanced commands
CMD_IMP_DEBUGGING = 8 # debugging/development commands
CMD_IMP_ALIAS = 7
CMD_IMP_DEFAULT = CMD_IMP_INTERESTING
class CommandDialog(Dialog):
"""A dialog for simple 'command args' commands"""
def __init__(self, *args, **kwargs):
self.subdialogs = []
self.commands = {}
self.cmd_prefix = ''
Dialog.__init__(self, *args, **kwargs)
self.add_alias('?', 'help')
def _set_subdialog_prefix(self, cmd, dialog):
dialog.set_cmd_prefix('%s%s ' % (self.cmd_prefix, cmd.upper()))
def set_cmd_prefix(self, prefix):
"""Set prefix for command examples on help messages
Useful for the "!command" format or for subdialogs
"""
self.cmd_prefix = prefix
for cmd,sd in self.subdialogs:
self._set_subdialog_prefix(cmd, sd)
def unknown_command(self, cmd, args):
#TODO: show help
self.message("Sorry, I don't get it. Type '%sHELP' for available commands" % (self.cmd_prefix))
def add_command(self, cmd, fn):
self.commands[cmd.lower()] = fn
def add_alias(self, alias, cmd, imp=CMD_IMP_ALIAS):
self.add_command(alias, self._command_fn(cmd))
sh = self._short_help(cmd)
if sh:
setattr(self, 'shorthelp_%s' % (alias.lower()), 'Synonym to `%s`: %s' % (cmd, sh))
setattr(self, 'importance_%s' % (alias.lower()), imp)
def _command_fn(self, cmd):
fn = getattr(self, 'command_%s' % (cmd.lower()), None)
if fn is None:
fn = self.commands.get(cmd.lower())
return fn
def add_subdialog(self, cmd, dialog, short_help=None):
def show_help(args):
dialog.show_help('%s: ' % (cmd.upper()), args)
def handle_cmd(args):
if not args:
args = ''
dialog.recv_message(args)
self.subdialogs.append( (cmd, dialog) )
dialog.set_message_func(self.message)
self._set_subdialog_prefix(cmd, dialog)
self.add_command(cmd, handle_cmd)
setattr(self, 'help_%s' % (cmd.lower()), show_help)
if short_help is None:
short_help = dialog.get_help_header()
if short_help:
setattr(self, 'shorthelp_%s' % (cmd.lower()), short_help)
def split_args(self, s):
s = s.lstrip()
parts = s.split(' ',1)
cmd = parts[0]
if len(parts) > 1:
args = parts[1]
else:
args = None
return cmd,args
def _short_help(self, cmd):
return getattr(self, 'shorthelp_%s' % (cmd.lower()), None)
def short_help(self, cmd):
sh = self._short_help(cmd)
if sh is None:
return None
# command get a full prefix
if self._command_fn(cmd):
prefix = self.cmd_prefix
else:
prefix = ''
return '%s%s - %s' % (prefix, cmd.upper(), sh)
def _long_help(self, cmd, args):
fn = getattr(self, 'help_%s' % (cmd.lower()), None)
if fn:
return fn(args)
sh = self.short_help(cmd)
if sh:
self.message(sh)
return
self.message("Unknown help topic: %s" % (cmd))
def get_help_header(self):
return getattr(self, 'help_header', None)
def show_help_header(self, args):
h = self.get_help_header()
if h:
self.message(h)
def _topic_importance(self, t):
r = getattr(self, 'importance_%s' % (t.lower()), None)
if r is None:
return CMD_IMP_DEFAULT
else:
return r
def help_topics(self):
r = []
for a in dir(self):
if a.startswith('shorthelp_'):
_,t = a.split('_',1)
imp = self._topic_importance(t)
r.append( (imp, t) )
r.sort()
return r
def show_help(self, prefix, args):
if args:
cmd,rest = self.split_args(args)
return self._long_help(cmd, rest)
topics = []
commands = []
for imp,t in self.help_topics():
if self._command_fn(t):
commands.append( (imp,t) )
else:
topics.append( (imp,t) )
self.show_help_header(args)
if commands:
main = []
rest = []
for imp,c in commands:
if imp <= CMD_IMP_INTERESTING:
main.append(c)
else:
rest.append(c)
if main:
self.message('%sAvailable commands:' % (prefix))
for c in main:
self.message(self.short_help(c))
if rest:
if main: name='Other commands'
else: name='Available commands'
pref = self.cmd_prefix
clist = ' '.join(['%s%s' % (pref,c.upper()) for c in rest])
self.message("%s: %s" % (name, clist))
if topics:
self.message('Other help topics:' % (prefix))
for t in topics:
self.message(self.short_help(t))
self.show_help_footer(args)
def show_help_footer(self, args):
pass
def cmd_syntax_str(self, cmd, args):
if args: suffix = ' %s' % (args)
else: suffix = ''
return 'Usage: %s%s%s' % (self.cmd_prefix, cmd.upper(), suffix)
def cmd_syntax(self, cmd, args):
self.message(self.cmd_syntax_str(cmd, args))
def help_help(self, args):
self.cmd_syntax('help', 'command-or-topic')
def command_help(self, args):
self.show_help('', args)
def try_msg(self, msg, unknown_fn=None):
cmd,args = self.split_args(msg)
fn = self._command_fn(cmd)
if fn is None:
return False,(cmd,args)
return True,fn(args)
def recv_message(self, msg):
- worked,r = self.try_msg(msg)
- if worked:
- return r
- else:
- cmd,args = r
- return self.unknown_command(cmd, args)
+ try:
+ worked,r = self.try_msg(msg)
+ if worked:
+ return r
+ else:
+ cmd,args = r
+ return self.unknown_command(cmd, args)
+ except Exception,e:
+ self.message("Ouch! An unexpected fatal error has occurred. I am very sorry. [%s]" % (e))
+ logger.error("Exception on dialog %r. msg: %r" % (self, msg))
+ logger.exception(e)
class CommandHelpMixin:
shorthelp_help = 'Show help'
importance_help = CMD_IMP_UNIMPORTANT
def attach_dialog_to_channel(dialog, chan, bot_user):
def doit():
chan.add_msg_notifier(got_chan_msg)
dialog.set_message_func(send_message)
def got_chan_msg(ch, sender, msg):
assert ch is chan
dialog.recv_message(msg)
def send_message(msg):
chan.send_message(bot_user, msg)
doit()
def attach_dialog_to_bot(dialog, proto, real_user, bot):
def doit():
bot.add_msg_notifier(got_msg)
dialog.set_message_func(send_message)
def got_msg(u, sender, msg):
assert u is bot
dialog.recv_message(msg)
def send_message(msg):
proto.send_notice(bot, real_user, msg)
doit()
|
ehabkost/passerd
|
b4b458c01b43fca8be96c6802cd70e29df4e1e50
|
dialogs.py: copyright info
|
diff --git a/passerd/dialogs.py b/passerd/dialogs.py
index 79fcafb..850f993 100644
--- a/passerd/dialogs.py
+++ b/passerd/dialogs.py
@@ -1,289 +1,314 @@
+# Passerd - An IRC server as a gateway to Twitter
+#
+# classes for text-based "dialogs"
+#
+# Author: Eduardo Habkost <ehabkost@raisama.net>
+#
+# Copyright (c) 2009,2010 Eduardo Pereira Habkost <ehabkost@raisama.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
import re
class Dialog:
"""An abstract interface to "user dialogs"
"""
def __init__(self, *args, **kwargs):
self.patterns = []
self.message_func = None
self.parent = kwargs.get('parent', None)
self.dialog_init(*args, **kwargs)
def set_message_func(self, fn):
self.message_func = fn
def dialog_init(self, *args, **kwargs):
"""Initialize the Dialog object"""
pass
def begin(self):
"""Start the dialog"""
pass
def wait_for(self, regexp, func, flags=re.I, strip=True):
if strip:
filter = (lambda s: s.strip())
else:
filter = (lambda s: s)
self.patterns.insert(0, (filter, re.compile(regexp, flags), func) )
def unknown_message(self, msg):
self.message("Sorry, I don't know what you mean")
def error_reply(self, msg, e):
self.message("An error has occurred. Sorry. -- %s" % (e))
def recv_message(self, msg):
for filter,expr,func in self.patterns:
s = filter(msg)
m = expr.search(s)
if m:
try:
return func(msg, m)
except Exception,e:
return self.error_reply(msg, e)
return self.unknown_message(msg)
def message(self, msg):
"""Send a message to the user"""
if self.message_func is None:
raise NotImplementedError("Dialog.message: not message_func set")
return self.message_func(msg)
# command "importance", to order help system
CMD_IMP_IMPORTANT = 0 # important commands
CMD_IMP_COMMON = 2 # commonly-used commands
CMD_IMP_INTERESTING = 5 # interesting-to-know commands
CMD_IMP_UNIMPORTANT = 6 # usual but not important commands
CMD_IMP_ADVANCED = 8 # advanced commands
CMD_IMP_DEBUGGING = 8 # debugging/development commands
CMD_IMP_ALIAS = 7
CMD_IMP_DEFAULT = CMD_IMP_INTERESTING
class CommandDialog(Dialog):
"""A dialog for simple 'command args' commands"""
def __init__(self, *args, **kwargs):
self.subdialogs = []
self.commands = {}
self.cmd_prefix = ''
Dialog.__init__(self, *args, **kwargs)
self.add_alias('?', 'help')
def _set_subdialog_prefix(self, cmd, dialog):
dialog.set_cmd_prefix('%s%s ' % (self.cmd_prefix, cmd.upper()))
def set_cmd_prefix(self, prefix):
"""Set prefix for command examples on help messages
Useful for the "!command" format or for subdialogs
"""
self.cmd_prefix = prefix
for cmd,sd in self.subdialogs:
self._set_subdialog_prefix(cmd, sd)
def unknown_command(self, cmd, args):
#TODO: show help
self.message("Sorry, I don't get it. Type '%sHELP' for available commands" % (self.cmd_prefix))
def add_command(self, cmd, fn):
self.commands[cmd.lower()] = fn
def add_alias(self, alias, cmd, imp=CMD_IMP_ALIAS):
self.add_command(alias, self._command_fn(cmd))
sh = self._short_help(cmd)
if sh:
setattr(self, 'shorthelp_%s' % (alias.lower()), 'Synonym to `%s`: %s' % (cmd, sh))
setattr(self, 'importance_%s' % (alias.lower()), imp)
def _command_fn(self, cmd):
fn = getattr(self, 'command_%s' % (cmd.lower()), None)
if fn is None:
fn = self.commands.get(cmd.lower())
return fn
def add_subdialog(self, cmd, dialog, short_help=None):
def show_help(args):
dialog.show_help('%s: ' % (cmd.upper()), args)
def handle_cmd(args):
if not args:
args = ''
dialog.recv_message(args)
self.subdialogs.append( (cmd, dialog) )
dialog.set_message_func(self.message)
self._set_subdialog_prefix(cmd, dialog)
self.add_command(cmd, handle_cmd)
setattr(self, 'help_%s' % (cmd.lower()), show_help)
if short_help is None:
short_help = dialog.get_help_header()
if short_help:
setattr(self, 'shorthelp_%s' % (cmd.lower()), short_help)
def split_args(self, s):
s = s.lstrip()
parts = s.split(' ',1)
cmd = parts[0]
if len(parts) > 1:
args = parts[1]
else:
args = None
return cmd,args
def _short_help(self, cmd):
return getattr(self, 'shorthelp_%s' % (cmd.lower()), None)
def short_help(self, cmd):
sh = self._short_help(cmd)
if sh is None:
return None
# command get a full prefix
if self._command_fn(cmd):
prefix = self.cmd_prefix
else:
prefix = ''
return '%s%s - %s' % (prefix, cmd.upper(), sh)
def _long_help(self, cmd, args):
fn = getattr(self, 'help_%s' % (cmd.lower()), None)
if fn:
return fn(args)
sh = self.short_help(cmd)
if sh:
self.message(sh)
return
self.message("Unknown help topic: %s" % (cmd))
def get_help_header(self):
return getattr(self, 'help_header', None)
def show_help_header(self, args):
h = self.get_help_header()
if h:
self.message(h)
def _topic_importance(self, t):
r = getattr(self, 'importance_%s' % (t.lower()), None)
if r is None:
return CMD_IMP_DEFAULT
else:
return r
def help_topics(self):
r = []
for a in dir(self):
if a.startswith('shorthelp_'):
_,t = a.split('_',1)
imp = self._topic_importance(t)
r.append( (imp, t) )
r.sort()
return r
def show_help(self, prefix, args):
if args:
cmd,rest = self.split_args(args)
return self._long_help(cmd, rest)
topics = []
commands = []
for imp,t in self.help_topics():
if self._command_fn(t):
commands.append( (imp,t) )
else:
topics.append( (imp,t) )
self.show_help_header(args)
if commands:
main = []
rest = []
for imp,c in commands:
if imp <= CMD_IMP_INTERESTING:
main.append(c)
else:
rest.append(c)
if main:
self.message('%sAvailable commands:' % (prefix))
for c in main:
self.message(self.short_help(c))
if rest:
if main: name='Other commands'
else: name='Available commands'
pref = self.cmd_prefix
clist = ' '.join(['%s%s' % (pref,c.upper()) for c in rest])
self.message("%s: %s" % (name, clist))
if topics:
self.message('Other help topics:' % (prefix))
for t in topics:
self.message(self.short_help(t))
self.show_help_footer(args)
def show_help_footer(self, args):
pass
def cmd_syntax_str(self, cmd, args):
if args: suffix = ' %s' % (args)
else: suffix = ''
return 'Usage: %s%s%s' % (self.cmd_prefix, cmd.upper(), suffix)
def cmd_syntax(self, cmd, args):
self.message(self.cmd_syntax_str(cmd, args))
def help_help(self, args):
self.cmd_syntax('help', 'command-or-topic')
def command_help(self, args):
self.show_help('', args)
def try_msg(self, msg, unknown_fn=None):
cmd,args = self.split_args(msg)
fn = self._command_fn(cmd)
if fn is None:
return False,(cmd,args)
return True,fn(args)
def recv_message(self, msg):
worked,r = self.try_msg(msg)
if worked:
return r
else:
cmd,args = r
return self.unknown_command(cmd, args)
class CommandHelpMixin:
shorthelp_help = 'Show help'
importance_help = CMD_IMP_UNIMPORTANT
def attach_dialog_to_channel(dialog, chan, bot_user):
def doit():
chan.add_msg_notifier(got_chan_msg)
dialog.set_message_func(send_message)
def got_chan_msg(ch, sender, msg):
assert ch is chan
dialog.recv_message(msg)
def send_message(msg):
chan.send_message(bot_user, msg)
doit()
def attach_dialog_to_bot(dialog, proto, real_user, bot):
def doit():
bot.add_msg_notifier(got_msg)
dialog.set_message_func(send_message)
def got_msg(u, sender, msg):
assert u is bot
dialog.recv_message(msg)
def send_message(msg):
proto.send_notice(bot, real_user, msg)
doit()
|
ehabkost/passerd
|
cd749b12eb2e8a51e43bf72e3b5125f033f1122f
|
Include passerd-bot on #@user channels too
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 80e33fc..4e0a971 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -419,1025 +419,1025 @@ class TwitterIrcUserCache:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addCallback(self.got_entry)
f.addErrback(self.refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
dbg("nickname %s not found", nick)
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
dbg("no posts by uid %s", uid)
return None
if substring:
matches = []
i = 1
while i <= len(recent):
r = recent[-i]
text = full_entity_decode(r.text)
#TODO: make it more flexible, ignoring punctuation and spaces
if substring.lower() in text:
matches.append(r)
i += 1
if not matches:
return None
if len(matches) > 1:
raise Exception("Multiple matches for [%s] on posts by %s" % (substring, nick))
# yay, single match:
r = matches[0]
else:
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent, I don't know if it's the one you want. Use words from the text to identify it" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
dbg("#twitter got_entry. id: %s", e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("#twitter refresh error")
#FIXME: stop showing repeated errors and just let the user know when service is back
if e.check(twisted.web.error.Error):
if str(e.value.status) == '503':
self.bot_notice("Look! A flying whale! -- %s" % (e.value))
return
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.value.status == '400' and remaining == 0:
self.wait_rate_limit()
self.bot_notice("error refreshing feed: %s" % (e.value))
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You can still try to fetch new tweets using `!`. Also, '
'you can check the rate limit using `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallback(done)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
- return [self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
+ return [self.proto.passerd_bot, self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
importance_recent = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
if substring:
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message(u"no match for [%s] on posts by %s" % (substring, nick))
else:
self.message(u"no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (local/twitter)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
|
ehabkost/passerd
|
732f0a4f7991e97bb3f08b1109936efacb837b9b
|
use unicode strings on RT error messages
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 8eeed9b..80e33fc 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -688,1027 +688,1027 @@ class TwitterChannel(IrcChannel):
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
return [self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
importance_recent = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
if substring:
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
- self.message("no match for [%s] on posts by %s" % (substring, nick))
+ self.message(u"no match for [%s] on posts by %s" % (substring, nick))
else:
- self.message("no posts from %s" % (nick))
+ self.message(u"no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (local/twitter)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def aborted(self):
return self._aborted
def abort(self):
"""Makes all @check_aborted functions stop doing anything
"""
dbg("abort")
#FIXME: we need to keep track of current requests/connections and
# abort all of them, instead of letting them continue running,
# but just ignoring the replies. The scheduler may be a good place
# to keep track of all pending requests
self._aborted = True
self._stop_scheduler()
@check_aborted
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
@check_aborted
def send_motd(self):
self.send_reply(irc.RPL_MOTDSTART, ":- %s Message of the day - " % (self.myhost))
self.send_reply(irc.RPL_MOTD, ":- Welcome to Passerd")
self.send_reply(irc.RPL_MOTD, ":- For additional information and help, see %s" % (version.URL))
self.send_reply(irc.RPL_ENDOFMOTD, ":End of MOTD command")
@check_aborted
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
@check_aborted
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _stop_scheduler(self):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
@check_aborted
def _set_scheduler(self, scheduler):
self._stop_scheduler()
self.scheduler = scheduler
def _userQuit(self, reason):
dbg("_userQuit: %r", reason)
self.dm_feed.stop_refreshing()
dbg("joined channels: %r", self.joined_channels)
# list will change under our feet, so copy it:
joined = self.joined_channels[:]
for ch in joined:
dbg("ch: %r", ch)
self.leave_channel(ch, reason)
# stop everything we are doing
self.abort()
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
@check_aborted
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
@check_aborted
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_channel(self, chan, reason):
dbg("leaving channel %r", chan)
if chan in self.joined_channels:
dbg("chan %r is joined", chan)
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
|
ehabkost/passerd
|
d5560c91672edec9f73dbb1e7f176da326836aa5
|
fix handling of RT command with no substring arg
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 56b6db0..8eeed9b 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -676,1026 +676,1028 @@ class TwitterChannel(IrcChannel):
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
return [self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
importance_recent = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
- # substring parameter must be unicode, not byte str
- substring = try_unicode(substring, IRC_ENCODING)
+ if substring:
+ # substring parameter must be unicode, not byte str
+ substring = try_unicode(substring, IRC_ENCODING)
+
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message("no match for [%s] on posts by %s" % (substring, nick))
else:
self.message("no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (local/twitter)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def aborted(self):
return self._aborted
def abort(self):
"""Makes all @check_aborted functions stop doing anything
"""
dbg("abort")
#FIXME: we need to keep track of current requests/connections and
# abort all of them, instead of letting them continue running,
# but just ignoring the replies. The scheduler may be a good place
# to keep track of all pending requests
self._aborted = True
self._stop_scheduler()
@check_aborted
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
@check_aborted
def send_motd(self):
self.send_reply(irc.RPL_MOTDSTART, ":- %s Message of the day - " % (self.myhost))
self.send_reply(irc.RPL_MOTD, ":- Welcome to Passerd")
self.send_reply(irc.RPL_MOTD, ":- For additional information and help, see %s" % (version.URL))
self.send_reply(irc.RPL_ENDOFMOTD, ":End of MOTD command")
@check_aborted
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
@check_aborted
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _stop_scheduler(self):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
@check_aborted
def _set_scheduler(self, scheduler):
self._stop_scheduler()
self.scheduler = scheduler
def _userQuit(self, reason):
dbg("_userQuit: %r", reason)
self.dm_feed.stop_refreshing()
dbg("joined channels: %r", self.joined_channels)
# list will change under our feet, so copy it:
joined = self.joined_channels[:]
for ch in joined:
dbg("ch: %r", ch)
self.leave_channel(ch, reason)
# stop everything we are doing
self.abort()
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
@check_aborted
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
@check_aborted
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_channel(self, chan, reason):
dbg("leaving channel %r", chan)
if chan in self.joined_channels:
dbg("chan %r is joined", chan)
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
|
ehabkost/passerd
|
d6712e50c8d067d60d46c860853a977a1058a1d2
|
MOTD support
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 962cf9d..56b6db0 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -968,1311 +968,1321 @@ class ConfigInfo:
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
importance_recent = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message("no match for [%s] on posts by %s" % (substring, nick))
else:
self.message("no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (local/twitter)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def aborted(self):
return self._aborted
def abort(self):
"""Makes all @check_aborted functions stop doing anything
"""
dbg("abort")
#FIXME: we need to keep track of current requests/connections and
# abort all of them, instead of letting them continue running,
# but just ignoring the replies. The scheduler may be a good place
# to keep track of all pending requests
self._aborted = True
self._stop_scheduler()
@check_aborted
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
+ @check_aborted
+ def send_motd(self):
+ self.send_reply(irc.RPL_MOTDSTART, ":- %s Message of the day - " % (self.myhost))
+ self.send_reply(irc.RPL_MOTD, ":- Welcome to Passerd")
+ self.send_reply(irc.RPL_MOTD, ":- For additional information and help, see %s" % (version.URL))
+ self.send_reply(irc.RPL_ENDOFMOTD, ":End of MOTD command")
+
@check_aborted
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
@check_aborted
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _stop_scheduler(self):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
@check_aborted
def _set_scheduler(self, scheduler):
self._stop_scheduler()
self.scheduler = scheduler
def _userQuit(self, reason):
dbg("_userQuit: %r", reason)
self.dm_feed.stop_refreshing()
dbg("joined channels: %r", self.joined_channels)
# list will change under our feet, so copy it:
joined = self.joined_channels[:]
for ch in joined:
dbg("ch: %r", ch)
self.leave_channel(ch, reason)
# stop everything we are doing
self.abort()
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
@check_aborted
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
@check_aborted
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_channel(self, chan, reason):
dbg("leaving channel %r", chan)
if chan in self.joined_channels:
dbg("chan %r is joined", chan)
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
+ def irc_MOTD(self, p, args):
+ self.send_motd()
+
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
@check_aborted
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, version.VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, version.VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
- #TODO: send a MOTD with useful information
+ self.send_motd()
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(timeout=self.factory.opts.api_timeout, *args, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = version.USER_AGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
channel = ListChannel(self, user, list_name)
if channel:
self.channels[name] = channel
return channel
def get_channel(self, name):
return self.channels.get(name)
def get_target(self, name):
if name.startswith('#'):
return self.get_channel(name)
else:
return self.get_user(name)
def mask_matches(self, mask):
#FIXME: match wildcards?
u = self.get_user(mask)
if u:
yield u
def who_matches(self, mask):
#TODO: make WHO list channel users
for u in self.mask_matches(mask):
#XXX: WTF do "H" and "G" mean?
yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
def whois_twitter_user(self, u, tu):
self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
#FIXME: find a better way to send user information, instead of RPL_AWAY
# - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
def oneline(s):
#FIXME: create a escape_post() function
return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
def whois_mask(self, mask):
def doit():
self.dbg("fetching user info for %s" % (mask))
self.api.show_user(mask).addCallback(got_user).addErrback(error)
def got_user(tu):
self.dbg("got user info!")
self.global_twuser_cache.got_api_user_info(tu)
u = self.get_twitter_user(tu.id)
self.whois_twitter_user(u, tu)
def error(e):
self.send_reply(irc.ERR_NOSUCHNICK, mask, ':Error fetching user info - %s' % (e.value))
doit()
class PasserdFactory(Factory):
protocol = PasserdProtocol
def __init__(self, opts):
url = 'sqlite:///%s' % (opts.database)
self.opts = opts
self.data = DataStore(url)
self.data.create_tables()
self.global_twuser_cache = TwitterUserCache(self)
class PasserdGlobalOptions:
def __init__(self):
# set the defaults:
self.listen = ('0.0.0.0', 6667)
#logging:
self.logstream = sys.stderr
# list of (logger_name, level) pairs
# - sqlalchemy is too verbose on the INFO loglevel
# - enable oauth debugging, by now
self.loglevels = [(None, logging.INFO),
('sqlalchemy', logging.ERROR),
('passerd.oauth',logging.DEBUG),
('passerd.feeds',logging.DEBUG),
('passerd.scheduler',logging.DEBUG)]
self.logformat = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
self.api_timeout = 60
self.daemon_mode = False
self.pidfile = None
def parse_cmdline(args, opts):
def parse_hostport(option, optstr, value, parser):
try:
host, rawport = value.rsplit(":", 1)
port = int(rawport)
except ValueError:
parser.error("invalid listen address, expected HOST:PORT")
opts.listen = (host, port)
def set_loglevels(levels):
opts.loglevels = levels
def open_logfile(option, optstr, value, parser):
opts.logstream = open(value, 'a')
parser = optparse.OptionParser("%prog [options] <database path>")
parser.add_option("-l", "--listen", type="string",
action="callback", callback=parse_hostport,
metavar="HOST:PORT", help="listen address")
parser.add_option("-D", "--debug",
action="callback", callback=lambda *args: set_loglevels([(None,logging.DEBUG)]),
help="Enable debug logging")
parser.add_option("--logformat",
metavar="FORMAT", type="string", default=None,
help="Set the logging format")
parser.add_option("-d", "--daemon",
action="store_true", dest="daemon_mode")
parser.add_option("-L", "--log-file",
metavar="FILENAME", type="string",
action="callback", callback=open_logfile)
parser.add_option("-p", "--pid-file",
metavar="FILENAME", type="string",
dest="pidfile")
_, args = parser.parse_args(args, opts)
if not args:
parser.error("the database path is needed!")
opts.database = args[0]
return opts
def setup_logging(opts):
# root logger:
r = logging.getLogger()
if opts.logstream:
handler = logging.StreamHandler(opts.logstream)
f = logging.Formatter(opts.logformat)
handler.setFormatter(f)
r.addHandler(handler)
for name,level in opts.loglevels:
logging.getLogger(name).setLevel(level)
def _run(opts):
pinfo("Starting Passerd. Will listen on address %s:%d" % opts.listen)
reactor.listenTCP(interface=opts.listen[0], port=opts.listen[1],
factory=PasserdFactory(opts))
pinfo("Starting Twisted reactor loop")
try:
reactor.run()
finally:
pinfo("Terminating")
class PidFile:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
dbg("locking pidfile %s", self.filename)
self.file = open(self.filename, 'w')
fcntl.lockf(self.file, fcntl.LOCK_EX|fcntl.LOCK_NB)
self.file.write('%d\n' % (os.getpid()))
self.file.flush()
def __exit__(self):
dbg("unlocking pidfile %s", self.filename)
os.unlink(self.filename)
fcntl.lockf(self.file, fcntl.LOCK_UN)
self.file.close()
def run_as_daemon(opts):
try:
import daemon
except ImportError:
raise Exception("You need the python-daemon module, to run Passerd on daemon mode")
pidfile = None
if opts.pidfile:
pidfile = PidFile(opts.pidfile)
# I don't want python-daemon to mess with any open file. The files we open
# on initialization will be kept, because they are our log files and sockets.
# stdin/stdout/stderr will be redirected to /dev/null, so they may be kept open,
# too.
preserve = range(MAXFD)
dc = daemon.DaemonContext(files_preserve=preserve, pidfile=pidfile)
dc.open()
try:
_run(opts)
except Exception,e:
logger.exception(e)
dc.close()
MAXFD = 2048
def run():
# be careful: avoid opening files before the _run() call. the
# daemon module will close it if you don't include it on files_preserve.
opts = PasserdGlobalOptions()
parse_cmdline(sys.argv[1:], opts)
setup_logging(opts)
if opts.daemon_mode:
run_as_daemon(opts)
else:
_run(opts)
__all__ = ['run']
|
ehabkost/passerd
|
d6a44b2c76aa35fd1a1c98d2c293a1f6d23f5d81
|
use a single exclamation mark on message
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 52231f6..962cf9d 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -178,1025 +178,1025 @@ class TwitterUserCache:
self.callbacks.addCallback(cb, *args, **kwargs)
def _change_data(self, d, old_info, new_info):
# callbacks must becalled _before_ updating the data:
self.callbacks.callback(d.twitter_id, old_info, new_info)
new_info.to_data(d)
def _new_user(self, id, info):
d = TwitterUserData(twitter_id=id)
self._change_data(d, None, info)
#FIXME: encapsulate the following session operations, somehow:
self.proto.data.session.add(d)
self.proto.data.session.commit()
return d
def _update_user_info(self, id, new_info):
d = self.lookup_id(id)
if d is None:
return self._new_user(id, new_info)
old_info = TwitterUserInfo().from_data(d)
self._change_data(d, old_info, new_info)
#FIXME: encapsulate the following session operation, somehow:
self.proto.data.session.commit()
return d
def update_user_info(self, id, screen_name, name):
id = int(id)
i = TwitterUserInfo()
i.screen_name = screen_name
i.name = name
return self._update_user_info(id, i)
def got_api_user_info(self, u):
self.update_user_info(u.id, u.screen_name, u.name)
def lookup_id(self, id):
id = int(id)
#FIXME: encapsulate the following session operations, somehow:
d = self.proto.data.query(TwitterUserData).get(id)
if d is None:
return None
return d
def lookup_screen_name(self, name):
# not
try:
u = self.proto.data.query(TwitterUserData).filter(func.lower(TwitterUserData.twitter_screen_name)==name.lower()).one()
except MultipleResultsFound:
# multiple matches are possible if screen_names are reused.
# if that happens, be on the safe side: don't return anything
u = None
except NoResultFound:
u = None
return u
class TwitterIrcUser(IrcUser):
"""Common class for multiple methods of contacting IRC users"""
def _target_params(self, params):
"""Must return a dictionary containing user_id or screen_name, depending on
how much information we already have about the user.
"""
raise NotImplementedError("_target_params not implemented")
def send_direct_message(self, text):
d = defer.Deferred()
ok = []
def got_msg(msg):
ok.append(msg)
d.callback(msg)
def done(*args):
if not ok:
self.proto.notice("ERROR: Didn't get direct message info back when sending DM")
self.proto.api.send_direct_message(text, delegate=got_msg, params=self._target_params()).addCallbacks(done, d.errback)
return d
def messageReceived(self, sender, msg):
assert (sender is self.proto.the_user)
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
#TODO: maybe there's a better error code for this?
raise ErrorReply(irc.RPL_AWAY, self.nick, ':message too long (%d characters), not sent.' % (len(msg)))
def doit():
self.send_direct_message(msg).addCallbacks(done, error)
def done(msg):
self.proto.notice("Direct Message to %s sent. ID: %s" % (self.nick, msg.id))
def error(e):
self.proto.send_reply(irc.RPL_AWAY, self.nick, ":Error sending Direct Message: %s" % (e.value))
doit()
class UnavailableTwitterData:
"""Fake TwitterUserData object for unavailable info"""
def __init__(self, id):
self.twitter_id = id
twitter_screen_name = property(lambda self: 'user-id-%s' % (self.twitter_id))
twitter_name = property(lambda self: 'Twitter User (info not fetched yet)')
class CachedTwitterIrcUser(TwitterIrcUser):
"""An IrcUser object for cached Twitter user info
Objects of this class may be short-lived, just to return info of a random
Twitter user for which we don't have much data.
"""
def __init__(self, proto, cache, id):
IrcUser.__init__(self, proto)
self._twitter_id = id
self.cache = cache
self._data = None
def _target_params(self):
return {'user_id':self._twitter_id}
def data_changed(self, old_info, new_info):
dbg("CachedTwitterIrcUser.data_changed! %r %r" % (old_info, new_info))
if (old_info is None) or (old_info.screen_name != new_info.screen_name):
self.notifyNickChange(str(new_info.screen_name))
def __get_data(self):
if self._data is None:
self._data = self.cache.lookup_id(self._twitter_id)
return self._data
def _get_data(self):
d = self.__get_data()
if d is None:
return UnavailableTwitterData(self._twitter_id)
return d
def has_data(self):
"""Checks if the Twitter user info is known"""
return (self.__get_data() is not None)
data = property(_get_data)
nick = property(lambda self: str(self.data.twitter_screen_name))
username = property(lambda self: str(self.data.twitter_screen_name))
real_name = property(lambda self: self.data.twitter_name.encode('utf-8'))
hostname = property(lambda self: 'twitter.com')
class UnknownTwitterUser(TwitterIrcUser):
"""An IrcUser object for an user we don't know anything about, but may be a valid Twitter user"""
def __init__(self, proto, nickname):
self.proto = proto
self.nick = nickname
self.username = nickname
real_name = 'Unknown User'
hostname = 'twitter.com'
def _target_params(self):
return {'screen_name':self.nick}
class TwitterIrcUserCache:
"""Cache of CachedTwitterIrcUser objects
A TwitterIrcUserCache is client-specific (not server-global), and takes
care of creating CachedTwitterIrcUser objects for some queries.
"""
def __init__(self, proto, cache):
self.proto = proto
self.cache = cache
self.cache.addCallback(self._user_changed)
self._watched_ids = {}
def _user_changed(self, id, old_info, new_info):
dbg("user_changed: %r, %r, %r" % (id, old_info, new_info))
if id in self._watched_ids:
dbg("user_changed (%s): is being watched." % (id))
u = self._get_user(id).data_changed(old_info, new_info)
def _get_user(self, id):
u = CachedTwitterIrcUser(self.proto, self.cache, id)
return u
def watch_user_id(self, id):
"""Start watching user ID for changes"""
self._watched_ids[id] = True
def watch_user_ids(self, ids):
for id in ids:
self.watch_user_id(id)
def watch_user(self, u):
self.watch_user_id(u._twitter_id)
def get_user(self, id):
return self._get_user(id)
def fetch_individual_user_info(self, unknown_users):
#TODO: implement me
pass
def fetch_all_friend_info(self, user, unknown_users):
#TODO: unify this paging code with the one on FriendlistMixIn
reqs = []
def request_cursor(cursor):
self.proto.dbg("requesting a page from the friend list: %s" % (str(cursor)))
reqs.append(cursor)
self.proto.api.list_friends(got_user, user=user, params={'cursor':cursor},
page_delegate=end_page).addCallbacks(done, error)
def got_user(u):
self.proto.global_twuser_cache.got_api_user_info(u)
def end_page(next, prev):
unk = [u for u in unknown_users if not u.has_data()]
num = len(unk)
if num == 0:
self.proto.notice("I know all friends of %s, now!" % (user))
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addCallback(self.got_entry)
f.addErrback(self.refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
dbg("nickname %s not found", nick)
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
dbg("no posts by uid %s", uid)
return None
if substring:
matches = []
i = 1
while i <= len(recent):
r = recent[-i]
text = full_entity_decode(r.text)
#TODO: make it more flexible, ignoring punctuation and spaces
if substring.lower() in text:
matches.append(r)
i += 1
if not matches:
return None
if len(matches) > 1:
raise Exception("Multiple matches for [%s] on posts by %s" % (substring, nick))
# yay, single match:
r = matches[0]
else:
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent, I don't know if it's the one you want. Use words from the text to identify it" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
dbg("#twitter got_entry. id: %s", e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("#twitter refresh error")
#FIXME: stop showing repeated errors and just let the user know when service is back
if e.check(twisted.web.error.Error):
if str(e.value.status) == '503':
self.bot_notice("Look! A flying whale! -- %s" % (e.value))
return
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.value.status == '400' and remaining == 0:
self.wait_rate_limit()
self.bot_notice("error refreshing feed: %s" % (e.value))
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You can still try to fetch new tweets using `!`. Also, '
'you can check the rate limit using `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallback(done)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
- self.bot_notice("Twitter update posted!!")
+ self.bot_notice("Twitter update posted!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
return [self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
importance_recent = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message("no match for [%s] on posts by %s" % (substring, nick))
else:
self.message("no posts from %s" % (nick))
return
|
ehabkost/passerd
|
9bb1627d6a2dae8def2b3291785746de41591714
|
new-user-setup: use a consistent order when asking about password option
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 025419c..52231f6 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -797,1025 +797,1025 @@ class FriendlistMixIn:
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def list_members(self):
#FIXME: only include the_user if the user really joined the channel
#FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
# and return it if info is available (see similar FIXME note on proto.get_user())
return [self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
#TODO: this was enabled in the past, but it just polluted the channel,
# as we don't see any messages from the people that follow the user.
# This can be enabled again if made configurable/optional
#def _friendList(self, delegate, params={}, page_delegate=None):
# #TODO: include the user on the list of channel members, too
# # (the user whose timeline is being followed, not the Passerd
# # authenticated user)
# return self.proto.api.friends_ids(delegate, self.user, params=params,
# page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
importance_recent = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message("no match for [%s] on posts by %s" % (substring, nick))
else:
self.message("no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
- bm("Which option do you want to use? (twitter/local)")
+ bm("Which option do you want to use? (local/twitter)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def aborted(self):
return self._aborted
def abort(self):
"""Makes all @check_aborted functions stop doing anything
"""
dbg("abort")
#FIXME: we need to keep track of current requests/connections and
# abort all of them, instead of letting them continue running,
# but just ignoring the replies. The scheduler may be a good place
# to keep track of all pending requests
self._aborted = True
self._stop_scheduler()
@check_aborted
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
@check_aborted
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
@check_aborted
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _stop_scheduler(self):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
@check_aborted
def _set_scheduler(self, scheduler):
self._stop_scheduler()
self.scheduler = scheduler
def _userQuit(self, reason):
dbg("_userQuit: %r", reason)
self.dm_feed.stop_refreshing()
dbg("joined channels: %r", self.joined_channels)
# list will change under our feet, so copy it:
joined = self.joined_channels[:]
for ch in joined:
dbg("ch: %r", ch)
self.leave_channel(ch, reason)
# stop everything we are doing
self.abort()
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
@check_aborted
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
@check_aborted
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_channel(self, chan, reason):
dbg("leaving channel %r", chan)
if chan in self.joined_channels:
dbg("chan %r is joined", chan)
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
dbg("joined channels now: %r", self.joined_channels)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
|
ehabkost/passerd
|
081e99e4f4981ada8a4f113d0b5b2b8ad70495fa
|
don't show every friend from a user on #@user channel
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index cc07f0a..025419c 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -399,1045 +399,1055 @@ class TwitterIrcUserCache:
def got_user(u):
self.proto.global_twuser_cache.got_api_user_info(u)
def end_page(next, prev):
unk = [u for u in unknown_users if not u.has_data()]
num = len(unk)
if num == 0:
self.proto.notice("I know all friends of %s, now!" % (user))
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addCallback(self.got_entry)
f.addErrback(self.refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
dbg("nickname %s not found", nick)
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
dbg("no posts by uid %s", uid)
return None
if substring:
matches = []
i = 1
while i <= len(recent):
r = recent[-i]
text = full_entity_decode(r.text)
#TODO: make it more flexible, ignoring punctuation and spaces
if substring.lower() in text:
matches.append(r)
i += 1
if not matches:
return None
if len(matches) > 1:
raise Exception("Multiple matches for [%s] on posts by %s" % (substring, nick))
# yay, single match:
r = matches[0]
else:
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent, I don't know if it's the one you want. Use words from the text to identify it" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
dbg("#twitter got_entry. id: %s", e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("#twitter refresh error")
#FIXME: stop showing repeated errors and just let the user know when service is back
if e.check(twisted.web.error.Error):
if str(e.value.status) == '503':
self.bot_notice("Look! A flying whale! -- %s" % (e.value))
return
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.value.status == '400' and remaining == 0:
self.wait_rate_limit()
self.bot_notice("error refreshing feed: %s" % (e.value))
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You can still try to fetch new tweets using `!`. Also, '
'you can check the rate limit using `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallback(done)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
-class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
+class UserChannel(TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
- def _friendList(self, delegate, params={}, page_delegate=None):
- #TODO: include the user on the list of channel members, too
- # (the user whose timeline is being followed, not the Passerd
- # authenticated user)
- return self.proto.api.friends_ids(delegate, self.user, params=params,
- page_delegate=page_delegate)
+ def list_members(self):
+ #FIXME: only include the_user if the user really joined the channel
+
+ #FIXME: use a self.proto.get_user()-like function that uses lookup_screen_name
+ # and return it if info is available (see similar FIXME note on proto.get_user())
+ return [self.proto.the_user, UnknownTwitterUser(self.proto, self.user)]
+
+ #TODO: this was enabled in the past, but it just polluted the channel,
+ # as we don't see any messages from the people that follow the user.
+ # This can be enabled again if made configurable/optional
+ #def _friendList(self, delegate, params={}, page_delegate=None):
+ # #TODO: include the user on the list of channel members, too
+ # # (the user whose timeline is being followed, not the Passerd
+ # # authenticated user)
+ # return self.proto.api.friends_ids(delegate, self.user, params=params,
+ # page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
importance_recent = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message("no match for [%s] on posts by %s" % (substring, nick))
else:
self.message("no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
def check_aborted(fn):
"""A decorator to make a function not do anything if the object is "aborted"
"""
def wrapper(self, *args, **kwargs):
dbg("aborted wrapper for %r called", fn)
if self.aborted():
dbg("it's aborted")
return
dbg("calling %r", fn)
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
|
ehabkost/passerd
|
17e7d062ef3bdc9164c8c308f0e1b4f67f466af4
|
simplistic mechanism to make server stop everything on disconnect
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index e4e8f19..cc07f0a 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -869,1360 +869,1400 @@ class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def _friendList(self, delegate, params={}, page_delegate=None):
#TODO: include the user on the list of channel members, too
# (the user whose timeline is being followed, not the Passerd
# authenticated user)
return self.proto.api.friends_ids(delegate, self.user, params=params,
page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
importance_recent = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message("no match for [%s] on posts by %s" % (substring, nick))
else:
self.message("no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
+def check_aborted(fn):
+ """A decorator to make a function not do anything if the object is "aborted"
+ """
+ def wrapper(self, *args, **kwargs):
+ dbg("aborted wrapper for %r called", fn)
+ if self.aborted():
+ dbg("it's aborted")
+ return
+ dbg("calling %r", fn)
+ return fn(self, *args, **kwargs)
+ return wrapper
+
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
+ self._aborted = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
-
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
+ def aborted(self):
+ return self._aborted
+
+ def abort(self):
+ """Makes all @check_aborted functions stop doing anything
+ """
+ dbg("abort")
+ #FIXME: we need to keep track of current requests/connections and
+ # abort all of them, instead of letting them continue running,
+ # but just ignoring the replies. The scheduler may be a good place
+ # to keep track of all pending requests
+ self._aborted = True
+ self._stop_scheduler()
+
+ @check_aborted
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
+ @check_aborted
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
-
+ @check_aborted
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
- def _set_scheduler(self, scheduler):
+ def _stop_scheduler(self):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
+
+ @check_aborted
+ def _set_scheduler(self, scheduler):
+ self._stop_scheduler()
self.scheduler = scheduler
def _userQuit(self, reason):
+ dbg("_userQuit: %r", reason)
self.dm_feed.stop_refreshing()
dbg("joined channels: %r", self.joined_channels)
# list will change under our feet, so copy it:
joined = self.joined_channels[:]
for ch in joined:
dbg("ch: %r", ch)
self.leave_channel(ch, reason)
- self._set_scheduler(None)
+ # stop everything we are doing
+ self.abort()
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
- self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
+ @check_aborted
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
+ @check_aborted
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
+ dbg("joined channels now: %r", self.joined_channels)
def leave_channel(self, chan, reason):
+ dbg("leaving channel %r", chan)
if chan in self.joined_channels:
+ dbg("chan %r is joined", chan)
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
+ dbg("joined channels now: %r", self.joined_channels)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
+ @check_aborted
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, version.VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, version.VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(timeout=self.factory.opts.api_timeout, *args, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = version.USER_AGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
channel = ListChannel(self, user, list_name)
if channel:
self.channels[name] = channel
return channel
def get_channel(self, name):
return self.channels.get(name)
def get_target(self, name):
if name.startswith('#'):
return self.get_channel(name)
else:
return self.get_user(name)
def mask_matches(self, mask):
#FIXME: match wildcards?
u = self.get_user(mask)
if u:
yield u
def who_matches(self, mask):
#TODO: make WHO list channel users
for u in self.mask_matches(mask):
#XXX: WTF do "H" and "G" mean?
yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
def whois_twitter_user(self, u, tu):
self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
#FIXME: find a better way to send user information, instead of RPL_AWAY
# - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
def oneline(s):
#FIXME: create a escape_post() function
return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
def whois_mask(self, mask):
def doit():
self.dbg("fetching user info for %s" % (mask))
self.api.show_user(mask).addCallback(got_user).addErrback(error)
def got_user(tu):
self.dbg("got user info!")
self.global_twuser_cache.got_api_user_info(tu)
u = self.get_twitter_user(tu.id)
self.whois_twitter_user(u, tu)
def error(e):
self.send_reply(irc.ERR_NOSUCHNICK, mask, ':Error fetching user info - %s' % (e.value))
doit()
class PasserdFactory(Factory):
protocol = PasserdProtocol
def __init__(self, opts):
url = 'sqlite:///%s' % (opts.database)
self.opts = opts
self.data = DataStore(url)
self.data.create_tables()
self.global_twuser_cache = TwitterUserCache(self)
class PasserdGlobalOptions:
def __init__(self):
# set the defaults:
self.listen = ('0.0.0.0', 6667)
#logging:
self.logstream = sys.stderr
# list of (logger_name, level) pairs
# - sqlalchemy is too verbose on the INFO loglevel
# - enable oauth debugging, by now
self.loglevels = [(None, logging.INFO),
('sqlalchemy', logging.ERROR),
('passerd.oauth',logging.DEBUG),
('passerd.feeds',logging.DEBUG),
('passerd.scheduler',logging.DEBUG)]
self.logformat = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
self.api_timeout = 60
self.daemon_mode = False
self.pidfile = None
def parse_cmdline(args, opts):
def parse_hostport(option, optstr, value, parser):
try:
host, rawport = value.rsplit(":", 1)
port = int(rawport)
except ValueError:
parser.error("invalid listen address, expected HOST:PORT")
opts.listen = (host, port)
def set_loglevels(levels):
opts.loglevels = levels
def open_logfile(option, optstr, value, parser):
opts.logstream = open(value, 'a')
parser = optparse.OptionParser("%prog [options] <database path>")
parser.add_option("-l", "--listen", type="string",
action="callback", callback=parse_hostport,
metavar="HOST:PORT", help="listen address")
parser.add_option("-D", "--debug",
action="callback", callback=lambda *args: set_loglevels([(None,logging.DEBUG)]),
help="Enable debug logging")
parser.add_option("--logformat",
metavar="FORMAT", type="string", default=None,
help="Set the logging format")
parser.add_option("-d", "--daemon",
action="store_true", dest="daemon_mode")
parser.add_option("-L", "--log-file",
metavar="FILENAME", type="string",
action="callback", callback=open_logfile)
parser.add_option("-p", "--pid-file",
metavar="FILENAME", type="string",
dest="pidfile")
_, args = parser.parse_args(args, opts)
if not args:
parser.error("the database path is needed!")
opts.database = args[0]
return opts
def setup_logging(opts):
# root logger:
r = logging.getLogger()
if opts.logstream:
handler = logging.StreamHandler(opts.logstream)
f = logging.Formatter(opts.logformat)
handler.setFormatter(f)
r.addHandler(handler)
for name,level in opts.loglevels:
logging.getLogger(name).setLevel(level)
def _run(opts):
pinfo("Starting Passerd. Will listen on address %s:%d" % opts.listen)
reactor.listenTCP(interface=opts.listen[0], port=opts.listen[1],
factory=PasserdFactory(opts))
pinfo("Starting Twisted reactor loop")
try:
reactor.run()
finally:
pinfo("Terminating")
class PidFile:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
dbg("locking pidfile %s", self.filename)
self.file = open(self.filename, 'w')
fcntl.lockf(self.file, fcntl.LOCK_EX|fcntl.LOCK_NB)
self.file.write('%d\n' % (os.getpid()))
self.file.flush()
def __exit__(self):
dbg("unlocking pidfile %s", self.filename)
os.unlink(self.filename)
fcntl.lockf(self.file, fcntl.LOCK_UN)
self.file.close()
def run_as_daemon(opts):
try:
import daemon
except ImportError:
raise Exception("You need the python-daemon module, to run Passerd on daemon mode")
pidfile = None
if opts.pidfile:
pidfile = PidFile(opts.pidfile)
# I don't want python-daemon to mess with any open file. The files we open
# on initialization will be kept, because they are our log files and sockets.
# stdin/stdout/stderr will be redirected to /dev/null, so they may be kept open,
# too.
preserve = range(MAXFD)
dc = daemon.DaemonContext(files_preserve=preserve, pidfile=pidfile)
dc.open()
try:
_run(opts)
except Exception,e:
logger.exception(e)
dc.close()
MAXFD = 2048
def run():
# be careful: avoid opening files before the _run() call. the
# daemon module will close it if you don't include it on files_preserve.
opts = PasserdGlobalOptions()
parse_cmdline(sys.argv[1:], opts)
setup_logging(opts)
if opts.daemon_mode:
run_as_daemon(opts)
else:
_run(opts)
__all__ = ['run']
diff --git a/passerd/scheduler.py b/passerd/scheduler.py
index 39aa60b..adf2fc9 100644
--- a/passerd/scheduler.py
+++ b/passerd/scheduler.py
@@ -1,154 +1,169 @@
#!/usr/bin/env python
#
# Passerd - An IRC server as a gateway to Twitter
#
# Rate-limiting scheduler code
#
# Author: Eduardo Habkost <ehabkost@raisama.net>
#
# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import logging, time
from twisted.internet import reactor, defer
logger = logging.getLogger('passerd.scheduler')
dbg = logger.debug
# refresh delay in seconds. This is multiplied by the number of feeds running,
# so we don't hit the rate-limit if the user is following too many feeds.
# Twitter default rate limit is 150 requests/hour. REFRESH_DELAY=45 should
# result on 80 requets per hour
MAX_REQS_PER_HOUR = 80
REFRESH_DELAY = int(3600/MAX_REQS_PER_HOUR)
class RefreshUpdater:
def __init__(self, scheduler, fn):
self.scheduler = scheduler
self.fn = fn
self.pending = False
def call(self):
dbg("calling: %r", self.fn)
self.pending = False
return self.fn()
def resched(self):
dbg("resched %r. pending: %r", self.fn, self.pending)
if self.pending:
return
self.pending = True
self.scheduler._resched_updater(self)
def unsched(self):
dbg("unsched %r. pending: %r", self.fn, self.pending)
if not self.pending:
return
self.pending = False
self.scheduler._unsched_updater(self)
def destroy(self):
dbg("destroy %r. pending: %r", self.fn, self.pending)
self.unsched()
self.scheduler._remove_updater(self)
class ApiScheduler:
def __init__(self, api):
self.api = api
self.updaters = {}
self.pending_queue = []
self.next_call = None
self.running = False
self.shots_available = 0
def new_updater(self, fn, active=True):
u = RefreshUpdater(self, fn)
self.updaters[id(u)] = u
if active:
u.resched()
return u
+ def _dbg_dump(self):
+ dbg("running: %r. current updater list: %r", self.running, self.updaters.values())
+
def _remove_updater(self, u):
del self.updaters[id(u)]
+ self._dbg_dump()
def _resched_updater(self, u):
self.pending_queue.append(u)
self._run_shots()
+ self._dbg_dump()
def _unsched_updater(self, u):
self.pending_queue.remove(u)
+ self._dbg_dump()
def _run_shots(self):
while self.shots_available > 0 and self.pending_queue:
self.shots_available -= 1
u = self.pending_queue.pop(0)
u.call()
def _run_next(self):
# we will run all pending refreshs at the same time to give a better
# user experience: all content will be fetched at the same time
# (DMs, home timeline, mentions, other feeds), avoiding
# bugging the user multiple times
dbg("_run_next called")
+ if not self.running:
+ dbg("not running")
+ return
+
updater_count = len(self.updaters)
self.shots_available = updater_count
self._run_shots()
if self.shots_available > 0:
dbg("still have %d shots available", self.shots_available)
delay = REFRESH_DELAY*updater_count
dbg("%d updaters are running. delay for the next update: %d seconds", updater_count, delay)
self._sched_next(delay)
def _sched_next(self, delay):
dbg("scheduling next call for %d seconds", delay)
+ if not self.running:
+ dbg("not scheduling: not running")
+ return
self.next_call = reactor.callLater(delay, self._run_next)
def _cancel_next(self):
dbg("cancelling next call")
if self.next_call is not None:
if self.next_call.active():
self.next_call.cancel()
self.next_call = None
def start(self):
+ dbg("starting scheduler")
if not self.running:
self.running = True
self._run_next()
def stop(self):
+ dbg("stopping scheduler")
self.running = False
self._cancel_next()
def wait_rate_limit(self):
delay = int(self.api.rate_limit_reset - time.time())
reset = time.ctime(self.api.rate_limit_reset)
if delay > REFRESH_DELAY:
dbg("Rescheduling the next feed refresh to %s (%s seconds),"
" as the rate limit was exhausted." % (reset, delay))
self._cancel_next()
self._sched_next(delay)
else:
dbg("No need to resched to wait for rate-limit, as the "
"delay is only %s seconds" % (delay))
|
ehabkost/passerd
|
655a1eecc28acac1f4277cb17dc64b9edb0dbadb
|
fix channel-leaving code on _userQuit()
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index e3fc78b..e4e8f19 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -950,1025 +950,1029 @@ class ConfigInfo:
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
importance_recent = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
# substring parameter must be unicode, not byte str
substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message("no match for [%s] on posts by %s" % (substring, nick))
else:
self.message("no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
- for ch in self.joined_channels:
+ dbg("joined channels: %r", self.joined_channels)
+ # list will change under our feet, so copy it:
+ joined = self.joined_channels[:]
+ for ch in joined:
+ dbg("ch: %r", ch)
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, version.VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, version.VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(timeout=self.factory.opts.api_timeout, *args, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = version.USER_AGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
|
ehabkost/passerd
|
aef1d4201087e0335ff6632d3af310c289b37dba
|
don't send PART messages when user leaves channel
|
diff --git a/passerd/irc.py b/passerd/irc.py
index 2209d8c..e08cf47 100644
--- a/passerd/irc.py
+++ b/passerd/irc.py
@@ -1,293 +1,294 @@
#!/usr/bin/env python
#
# Passerd - An IRC server as a gateway to Twitter
#
# Basic IRC protocol abstraction classes
#
# Author: Eduardo Habkost <ehabkost@raisama.net>
#
# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import logging
from twisted.words.protocols import irc
from twisted.internet import defer
from passerd.util import hooks
logger = logging.getLogger("passerd.irc")
dbg = logger.debug
pinfo = logger.info
perror = logger.error
class IrcTarget:
"""Common class for IRC channels and users
This may contain some common operations that work for both users and
channels.
"""
def __init__(self, proto):
self.proto = proto
self.msg_notifiers = []
def add_msg_notifier(self, func):
self.msg_notifiers.append(func)
def notify_message(self, sender, msg):
for func in self.msg_notifiers:
func(self, sender, msg)
def parseModeSetRequest(self, args):
"""Parse a mode-change request, generating (flags,params) tuples
Whoever invented the MODE command syntax is _really_ evil.
"""
i = 0
dbg("parsing mode request: %r" % (args))
while i < len(args):
flags = args[i]
i += 1
params = []
while i < len(args):
a = args[i]
if a[:1] in '+-':
# a new flag set/unset was requested
break
params.append(a)
i += 1
dbg("flags: %r, params: %r" % (flags, params))
yield flags,params
def modeFlagQuery(self, flag, params):
dbg("mode flag query: %r %r" % (flag, params))
# specific mode query/set request:
if not flag in self.supported_modes:
self.proto.send_reply(irc.ERR_UNKNOWNMODE, 'Mode %s is not known to me' % (flag))
return
fn = getattr(self, 'mode_query_%s' % (flag))
fn(params)
def flagChangeRequest(self, flag, value, params):
dbg("mode change request: %r %s %r" % (flag, value, params))
if not flag in self.supported_modes:
self.proto.send_reply(irc.ERR_UNKNOWNMODE, flag, ':Mode %s is not known to me' % (flag))
return
fn = getattr(self, 'mode_set_%s' % (flag))
fn(value, params)
def modeFlagRequest(self, sender, args):
for flags,params in self.parseModeSetRequest(args):
value = 0
for f in flags:
if f == '+': value = 1
elif f == '-': value = -1
else:
if value == 0:
# no "+" or "-" => simple query
self.modeFlagQuery(f, params)
else:
self.flagChangeRequest(f, value, params)
def modeRequest(self, sender, args):
if len(args) == 1:
# general mode query
self.sendModes()
else:
self.modeFlagRequest(self, args[1:])
def ctcp_unknown(self, tag, data):
dbg("Unsupported CTCP query: %r %r" % (tag, data))
def ctcpQueryReceived(self, sender, query):
for tag,data in query:
m = getattr(self, 'ctcp_%s' % (tag), None)
if m is not None:
m(data)
else:
self.ctcp_unknown(tag, data)
def messageReceived(self, sender, msg):
assert (sender is self.proto.the_user)
self.notify_message(sender, msg)
class IrcUser(IrcTarget):
supported_modes = ''
def __cmp__(self, o):
return cmp(self.nick, o.nick)
def target_name(self):
return self.nick
def is_away(self):
return False
def away_char(self):
if self.is_away(): return '-'
else: return '+'
def userhost(self):
return '%s@%s' % (self.username, self.hostname)
def full_id(self):
return '%s!%s@%s' % (self.nick, self.username, self.hostname)
def notifyNickChange(self, new_nick):
"""Must be called before self.nick value changes, so the sender ID is correct"""
self.proto.send_message(self, 'NICK', new_nick)
def force_nick(self, new_nick):
if self.nick != new_nick:
self.notifyNickChange(new_nick)
self.nick = new_nick
class IrcChannel(IrcTarget):
supported_modes = 'b'
def __init__(self, proto, name):
IrcTarget.__init__(self, proto)
self.name = name
def target_name(self):
return self.name
def ban_masks(self, params):
return []
def list_members(self):
#FIXME: include the_user only if the user already joined
return [self.proto.the_user]
def mode_query_b(self, params):
"""Query ban list"""
dbg("checking the ban list for %s" % (self.name))
for m in self.ban_masks(params):
self.proto.send_reply(irc.RPL_BANLIST, self.name, m)
self.proto.send_reply(irc.RPL_ENDOFBANLIST, self.name, ":End of channel ban list")
def mode_set_b(self, value, params):
dbg("ban mode set request: %r %r" % (value, params))
if len(params) == 0:
# no params means this is a mode query
return self.mode_query_b(params)
raise NotImplementedError("Ban setting is not implemented")
def send_message(self, sender, msg):
self.proto.send_privmsg(sender, self, msg)
def typeChar(self):
"""Return '@', '*', or '=', for RPL_NAMREPLY"""
return '=' # show channel as public by default
def userModeChar(self, user):
"""Retuern '', '@', or '+', depending on user mode"""
return ''
def fullModeSpec(self):
# return no modes, by default
return ''
def notifyJoin(self, who):
self.proto.send_message(who, 'JOIN', self.name)
def notifyKick(self, kicker, kicked):
self.proto.send_message(kicker, 'KICK', self.name, kicked.nick)
def notifyPart(self, who, reason):
if reason is not None:
self.proto.send_message(who, 'PART', self.name, reason)
else:
self.proto.send_message(who, 'PART', self.name)
def notifyTopic(self):
self.proto.send_reply(irc.RPL_TOPIC, self.name, ':%s' % (self.topic()))
def sendModes(self):
self.proto.send_reply(irc.RPL_CHANNELMODEIS, self.name, self.fullModeSpec())
def _sendNames(self, members):
namelist = []
def flush():
names = ' '.join(namelist)
self.proto.send_reply(irc.RPL_NAMREPLY, '=', self.name, ':%s' % (names))
namelist[:] = []
for m in members:
namelist.append('%s%s' % (self.userModeChar(m), m.nick))
if len(namelist) > 30:
flush()
flush()
self.proto.send_reply(irc.RPL_ENDOFNAMES, self.name, ':End of NAMES list')
def sendNames(self):
def doit():
d = defer.maybeDeferred(self.list_members)
d.addCallback(send_names).addErrback(error)
def send_names(members):
dbg("got member list: %d members" % (len(members)))
self._sendNames(members)
def error(e):
self.proto.notice("ERROR: failure getting member names for %s -- %s" % (self.name, e.value))
#FIXME: include the_user only if the user already joined
self._sendNames([self.proto.the_user])
doit()
@hooks
def userJoined(self, user):
self.notifyJoin(user)
self.notifyTopic()
self.sendNames()
@hooks
def userLeft(self, user, reason):
- self.notifyPart(user, reason)
+ """Called when the user just joined the channel"""
+ pass
@hooks
def userQuit(self, user, reason):
pass
def topic(self):
return "[no topic set]"
def kickUser(self, sender, nickname):
return NotImplementedError("Can't kick users from %s" % (self.name))
def inviteUser(self, nickname):
return NotImplementedError("Can't invite users to %s" % (self.name))
def kickUsers(self, sender, users):
for u in users:
self.kickUser(sender, u)
class IrcServer(IrcTarget):
"""An IrcTarget used for server messages"""
def __init__(self, proto, name):
IrcTarget.__init__(self, proto)
self.name = name
def full_id(self):
return self.name
|
ehabkost/passerd
|
b2ef8addfd98e0a7951bb4288d4013893e9248df
|
Fix unicode handling on recent_post()
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 7b87939..e3fc78b 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -32,1655 +32,1660 @@ import rfc822 # for date/time parsing
from twisted.words.protocols import irc
from twisted.words.protocols.irc import IRC
from twisted.internet.protocol import Factory
from twisted.internet import reactor, defer
import twisted.web.error
from twittytwister.twitter import Twitter, TwitterClientInfo
from passerd.data import DataStore, TwitterUserData
from passerd.callbacks import CallbackList
from passerd.utils import full_entity_decode
from passerd.feeds import HomeTimelineFeed, ListTimelineFeed, UserTimelineFeed, MentionsFeed, DirectMessagesFeed
from passerd.scheduler import ApiScheduler
from passerd import dialogs
from passerd.dialogs import Dialog, CommandDialog, CommandHelpMixin, attach_dialog_to_channel, attach_dialog_to_bot
from passerd.util import try_unicode, to_str
from passerd.irc import IrcUser, IrcChannel, IrcServer
from passerd.poauth import OAuthClient, oauth_consumer
from passerd import version
import oauth.oauth as oauth
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from sqlalchemy.sql.expression import func
# client/user-agent info:
####
#FIXME: use a real hostname?
MYHOST = 'passerd.server'
CLIENT_INFO = TwitterClientInfo(version.NAME, version.VERSION, version.URL)
# IRC protocol stuff:
####
# the only mode supported, right now:
SUPPORTED_CHAN_MODES = 'b'
# No user mode is supported, by now:
SUPPORTED_USER_MODES = '0'
IRC_ENCODING = 'utf-8'
# Twitter protocol stuff:
####
BASE_URL = 'https://twitter.com'
TWITTER_ENCODING = 'utf-8'
LENGTH_LIMIT = 140
# Some limits:
####
# keep latest 100 post on each channel, to create in_reply_to field.
REPLY_HISTORY_SIZE = 100
# if more than MAX_USER_INFO_FETCH users are unknown, use /statuses/friends to fetch user info.
# otherwise, just fetch individual user info
MAX_USER_INFO_FETCH = 0 # individual fetch is not implemented yet...
# the maximum number of sequential friend list page requests:
MAX_FRIEND_PAGE_REQS = 10
# minimum post age (in seconds) to allow it to be used for RTs.
# useful to avoid surprises when using the !RT command
#TODO: make this configurable
MIN_LATEST_POST_AGE = 2
# IRC protocol constants:
####
# Other error codes we may use:
ERR_NEEDREGGEDNICK = '477'
# logging helpers:
####
logger = logging.getLogger("passerd")
dbg = logger.debug
pinfo = logger.info
perror = logger.error
class ErrorReply(Exception):
"""Special exception class used to generate IRC numeric replies"""
def __init__(self, command, *args):
self.command = command
self.args = args
class MissingOAuthRegistration(Exception):
pass
class MessageTooLong(Exception):
def __init__(self, text, length):
self.text = text
self.length = length
Exception.__init__(self, 'message too long (%d characters)' % (length))
class TwitterUserInfo:
"""Just carries simple data for a Twitter user
"""
def from_data(self, d):
self.screen_name = d.twitter_screen_name
self.name = d.twitter_name
return self
def to_data(self, d):
d.twitter_screen_name = self.screen_name
d.twitter_name = self.name
return self
def __repr__(self):
return 'TwitterUserInfo(%r, %r)' % (self.screen_name, self.name)
class TwitterUserCache:
"""Caches information about Twitter users
This is server-global, and is just an interface to the twitter_users database
table.
"""
def __init__(self, proto):
self.proto = proto
self.callbacks = CallbackList()
def addCallback(self, cb, *args, **kwargs):
"""Add a new callback function
Callback function is called with arguments: (twitter_user, old_info, new_info)
old_info may be None, if it's a new user
"""
self.callbacks.addCallback(cb, *args, **kwargs)
def _change_data(self, d, old_info, new_info):
# callbacks must becalled _before_ updating the data:
self.callbacks.callback(d.twitter_id, old_info, new_info)
new_info.to_data(d)
def _new_user(self, id, info):
d = TwitterUserData(twitter_id=id)
self._change_data(d, None, info)
#FIXME: encapsulate the following session operations, somehow:
self.proto.data.session.add(d)
self.proto.data.session.commit()
return d
def _update_user_info(self, id, new_info):
d = self.lookup_id(id)
if d is None:
return self._new_user(id, new_info)
old_info = TwitterUserInfo().from_data(d)
self._change_data(d, old_info, new_info)
#FIXME: encapsulate the following session operation, somehow:
self.proto.data.session.commit()
return d
def update_user_info(self, id, screen_name, name):
id = int(id)
i = TwitterUserInfo()
i.screen_name = screen_name
i.name = name
return self._update_user_info(id, i)
def got_api_user_info(self, u):
self.update_user_info(u.id, u.screen_name, u.name)
def lookup_id(self, id):
id = int(id)
#FIXME: encapsulate the following session operations, somehow:
d = self.proto.data.query(TwitterUserData).get(id)
if d is None:
return None
return d
def lookup_screen_name(self, name):
# not
try:
u = self.proto.data.query(TwitterUserData).filter(func.lower(TwitterUserData.twitter_screen_name)==name.lower()).one()
except MultipleResultsFound:
# multiple matches are possible if screen_names are reused.
# if that happens, be on the safe side: don't return anything
u = None
except NoResultFound:
u = None
return u
class TwitterIrcUser(IrcUser):
"""Common class for multiple methods of contacting IRC users"""
def _target_params(self, params):
"""Must return a dictionary containing user_id or screen_name, depending on
how much information we already have about the user.
"""
raise NotImplementedError("_target_params not implemented")
def send_direct_message(self, text):
d = defer.Deferred()
ok = []
def got_msg(msg):
ok.append(msg)
d.callback(msg)
def done(*args):
if not ok:
self.proto.notice("ERROR: Didn't get direct message info back when sending DM")
self.proto.api.send_direct_message(text, delegate=got_msg, params=self._target_params()).addCallbacks(done, d.errback)
return d
def messageReceived(self, sender, msg):
assert (sender is self.proto.the_user)
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
#TODO: maybe there's a better error code for this?
raise ErrorReply(irc.RPL_AWAY, self.nick, ':message too long (%d characters), not sent.' % (len(msg)))
def doit():
self.send_direct_message(msg).addCallbacks(done, error)
def done(msg):
self.proto.notice("Direct Message to %s sent. ID: %s" % (self.nick, msg.id))
def error(e):
self.proto.send_reply(irc.RPL_AWAY, self.nick, ":Error sending Direct Message: %s" % (e.value))
doit()
class UnavailableTwitterData:
"""Fake TwitterUserData object for unavailable info"""
def __init__(self, id):
self.twitter_id = id
twitter_screen_name = property(lambda self: 'user-id-%s' % (self.twitter_id))
twitter_name = property(lambda self: 'Twitter User (info not fetched yet)')
class CachedTwitterIrcUser(TwitterIrcUser):
"""An IrcUser object for cached Twitter user info
Objects of this class may be short-lived, just to return info of a random
Twitter user for which we don't have much data.
"""
def __init__(self, proto, cache, id):
IrcUser.__init__(self, proto)
self._twitter_id = id
self.cache = cache
self._data = None
def _target_params(self):
return {'user_id':self._twitter_id}
def data_changed(self, old_info, new_info):
dbg("CachedTwitterIrcUser.data_changed! %r %r" % (old_info, new_info))
if (old_info is None) or (old_info.screen_name != new_info.screen_name):
self.notifyNickChange(str(new_info.screen_name))
def __get_data(self):
if self._data is None:
self._data = self.cache.lookup_id(self._twitter_id)
return self._data
def _get_data(self):
d = self.__get_data()
if d is None:
return UnavailableTwitterData(self._twitter_id)
return d
def has_data(self):
"""Checks if the Twitter user info is known"""
return (self.__get_data() is not None)
data = property(_get_data)
nick = property(lambda self: str(self.data.twitter_screen_name))
username = property(lambda self: str(self.data.twitter_screen_name))
real_name = property(lambda self: self.data.twitter_name.encode('utf-8'))
hostname = property(lambda self: 'twitter.com')
class UnknownTwitterUser(TwitterIrcUser):
"""An IrcUser object for an user we don't know anything about, but may be a valid Twitter user"""
def __init__(self, proto, nickname):
self.proto = proto
self.nick = nickname
self.username = nickname
real_name = 'Unknown User'
hostname = 'twitter.com'
def _target_params(self):
return {'screen_name':self.nick}
class TwitterIrcUserCache:
"""Cache of CachedTwitterIrcUser objects
A TwitterIrcUserCache is client-specific (not server-global), and takes
care of creating CachedTwitterIrcUser objects for some queries.
"""
def __init__(self, proto, cache):
self.proto = proto
self.cache = cache
self.cache.addCallback(self._user_changed)
self._watched_ids = {}
def _user_changed(self, id, old_info, new_info):
dbg("user_changed: %r, %r, %r" % (id, old_info, new_info))
if id in self._watched_ids:
dbg("user_changed (%s): is being watched." % (id))
u = self._get_user(id).data_changed(old_info, new_info)
def _get_user(self, id):
u = CachedTwitterIrcUser(self.proto, self.cache, id)
return u
def watch_user_id(self, id):
"""Start watching user ID for changes"""
self._watched_ids[id] = True
def watch_user_ids(self, ids):
for id in ids:
self.watch_user_id(id)
def watch_user(self, u):
self.watch_user_id(u._twitter_id)
def get_user(self, id):
return self._get_user(id)
def fetch_individual_user_info(self, unknown_users):
#TODO: implement me
pass
def fetch_all_friend_info(self, user, unknown_users):
#TODO: unify this paging code with the one on FriendlistMixIn
reqs = []
def request_cursor(cursor):
self.proto.dbg("requesting a page from the friend list: %s" % (str(cursor)))
reqs.append(cursor)
self.proto.api.list_friends(got_user, user=user, params={'cursor':cursor},
page_delegate=end_page).addCallbacks(done, error)
def got_user(u):
self.proto.global_twuser_cache.got_api_user_info(u)
def end_page(next, prev):
unk = [u for u in unknown_users if not u.has_data()]
num = len(unk)
if num == 0:
self.proto.notice("I know all friends of %s, now!" % (user))
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addCallback(self.got_entry)
f.addErrback(self.refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
dbg("nickname %s not found", nick)
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
dbg("no posts by uid %s", uid)
return None
if substring:
matches = []
i = 1
while i <= len(recent):
r = recent[-i]
+ text = full_entity_decode(r.text)
#TODO: make it more flexible, ignoring punctuation and spaces
- if substring.lower() in r.text.lower():
+ if substring.lower() in text:
matches.append(r)
i += 1
if not matches:
return None
if len(matches) > 1:
raise Exception("Multiple matches for [%s] on posts by %s" % (substring, nick))
# yay, single match:
r = matches[0]
else:
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent, I don't know if it's the one you want. Use words from the text to identify it" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
dbg("#twitter got_entry. id: %s", e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("#twitter refresh error")
#FIXME: stop showing repeated errors and just let the user know when service is back
if e.check(twisted.web.error.Error):
if str(e.value.status) == '503':
self.bot_notice("Look! A flying whale! -- %s" % (e.value))
return
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.value.status == '400' and remaining == 0:
self.wait_rate_limit()
self.bot_notice("error refreshing feed: %s" % (e.value))
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You can still try to fetch new tweets using `!`. Also, '
'you can check the rate limit using `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallback(done)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def _friendList(self, delegate, params={}, page_delegate=None):
#TODO: include the user on the list of channel members, too
# (the user whose timeline is being followed, not the Passerd
# authenticated user)
return self.proto.api.friends_ids(delegate, self.user, params=params,
page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
importance_recent = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
+ substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
- self.message("match: id: %r. text: %r" % (r.id, r.text))
+ self.message("match: id: %r. text: %r" % (r.id, full_entity_decode(r.text)))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
+
+ # substring parameter must be unicode, not byte str
+ substring = try_unicode(substring, IRC_ENCODING)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message("no match for [%s] on posts by %s" % (substring, nick))
else:
self.message("no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
|
ehabkost/passerd
|
f6ef9d694ad364d23c99ef3497d78b3f58bc2068
|
recommend a newer sqlalchemy
|
diff --git a/INSTALL.markdown b/INSTALL.markdown
index 37529b3..3926e1f 100644
--- a/INSTALL.markdown
+++ b/INSTALL.markdown
@@ -1,63 +1,63 @@
What do I need, to use Passerd?
-------------------------------
_Passerd_ is written in Python. You need Python (of course!), and the following
Python modules:
* twisted (and its 'twisted.words' module)
* sqlite
-* sqlalchemy
+* sqlalchemy (recommended version 0.5.4 or later)
* oauth
* A patched version of twitty-twister -- but don't worry: it is automatically fetched by `git submodule` and `./run.sh` (see run instructions below)
Optional dependencies:
* For running Passerd in _daemon_ mode:
* [python-daemon](http://pypi.python.org/pypi/python-daemon/)
* Python [lockfile](http://pypi.python.org/pypi/lockfile/) module
Below you'll find instructions to easily get the dependencies on some operating
systems:
### On Fedora
To install the dependencies on a Fedora machine, run:
yum install python-twisted python-twisted-words python-sqlalchemy python-oauth
For the optional packages:
yum install python-daemon python-lockfile
### On Mandriva
These dependencies currently match the 2010.0 release but should be ok for others:
urpmi python-twisted-words python-sqlite python-sqlalchemy python-oauth
How do I run it?
----------------
Right now the recommended way to run Passerd is to check out the source
directly from the git repository.
### From the git repository:
* Check out the [git repository][gitrepo]
* `git clone git://github.com/ehabkost/passerd.git`
* `cd passerd`
* Run `git submodule init`
* Run `git submodule update`
* Run `./run.sh`
* Point your IRC client to server `localhost`, port `6667`
* Join the `#new-user-setup` channel on the server
* Follow the instructions from `passerd-bot`
* Have fun!
See the `USERGUIDE` file for more information.
[gitrepo]: http://github.com/ehabkost/passerd
|
ehabkost/passerd
|
97fe2bcc314b04b108908f637c2944672d4e751b
|
run.sh: fix the missing-submodule-update code
|
diff --git a/run.sh b/run.sh
index 287632c..89e3f1a 100755
--- a/run.sh
+++ b/run.sh
@@ -1,25 +1,25 @@
#!/bin/bash
mydir="$(dirname "$0")"
add_pypath()
{
if [ -n "$PYTHONPATH" ];then
PYTHONPATH="$1:$PYTHONPATH"
else
PYTHONPATH="$1"
fi
}
-if [ ! -d "$mydir/third-party/twitty-twister" ];then
+if [ ! -f "$mydir/third-party/twitty-twister/twittytwister/twitter.py" ];then
echo "You need to update the twitty-twister submodule. Run:" >&2
echo " git submodule init"
echo " git submodule update"
exit 1
fi
add_pypath "$mydir/third-party/twitty-twister"
add_pypath "$mydir"
export PYTHONPATH
mkdir -p "$HOME/.passerd"
"$mydir/bin/passerd" "$HOME/.passerd/data.sqlite" "$@"
|
ehabkost/passerd
|
b423c3baabb5f4925ae9599d6295e58f9c1b690a
|
call daemon.open()/.close() manually
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 0012043..7b87939 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -1685,533 +1685,535 @@ class PasserdProtocol(IRC):
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, version.VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, version.VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(timeout=self.factory.opts.api_timeout, *args, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = version.USER_AGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
channel = ListChannel(self, user, list_name)
if channel:
self.channels[name] = channel
return channel
def get_channel(self, name):
return self.channels.get(name)
def get_target(self, name):
if name.startswith('#'):
return self.get_channel(name)
else:
return self.get_user(name)
def mask_matches(self, mask):
#FIXME: match wildcards?
u = self.get_user(mask)
if u:
yield u
def who_matches(self, mask):
#TODO: make WHO list channel users
for u in self.mask_matches(mask):
#XXX: WTF do "H" and "G" mean?
yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
def whois_twitter_user(self, u, tu):
self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
#FIXME: find a better way to send user information, instead of RPL_AWAY
# - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
def oneline(s):
#FIXME: create a escape_post() function
return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
def whois_mask(self, mask):
def doit():
self.dbg("fetching user info for %s" % (mask))
self.api.show_user(mask).addCallback(got_user).addErrback(error)
def got_user(tu):
self.dbg("got user info!")
self.global_twuser_cache.got_api_user_info(tu)
u = self.get_twitter_user(tu.id)
self.whois_twitter_user(u, tu)
def error(e):
self.send_reply(irc.ERR_NOSUCHNICK, mask, ':Error fetching user info - %s' % (e.value))
doit()
class PasserdFactory(Factory):
protocol = PasserdProtocol
def __init__(self, opts):
url = 'sqlite:///%s' % (opts.database)
self.opts = opts
self.data = DataStore(url)
self.data.create_tables()
self.global_twuser_cache = TwitterUserCache(self)
class PasserdGlobalOptions:
def __init__(self):
# set the defaults:
self.listen = ('0.0.0.0', 6667)
#logging:
self.logstream = sys.stderr
# list of (logger_name, level) pairs
# - sqlalchemy is too verbose on the INFO loglevel
# - enable oauth debugging, by now
self.loglevels = [(None, logging.INFO),
('sqlalchemy', logging.ERROR),
('passerd.oauth',logging.DEBUG),
('passerd.feeds',logging.DEBUG),
('passerd.scheduler',logging.DEBUG)]
self.logformat = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
self.api_timeout = 60
self.daemon_mode = False
self.pidfile = None
def parse_cmdline(args, opts):
def parse_hostport(option, optstr, value, parser):
try:
host, rawport = value.rsplit(":", 1)
port = int(rawport)
except ValueError:
parser.error("invalid listen address, expected HOST:PORT")
opts.listen = (host, port)
def set_loglevels(levels):
opts.loglevels = levels
def open_logfile(option, optstr, value, parser):
opts.logstream = open(value, 'a')
parser = optparse.OptionParser("%prog [options] <database path>")
parser.add_option("-l", "--listen", type="string",
action="callback", callback=parse_hostport,
metavar="HOST:PORT", help="listen address")
parser.add_option("-D", "--debug",
action="callback", callback=lambda *args: set_loglevels([(None,logging.DEBUG)]),
help="Enable debug logging")
parser.add_option("--logformat",
metavar="FORMAT", type="string", default=None,
help="Set the logging format")
parser.add_option("-d", "--daemon",
action="store_true", dest="daemon_mode")
parser.add_option("-L", "--log-file",
metavar="FILENAME", type="string",
action="callback", callback=open_logfile)
parser.add_option("-p", "--pid-file",
metavar="FILENAME", type="string",
dest="pidfile")
_, args = parser.parse_args(args, opts)
if not args:
parser.error("the database path is needed!")
opts.database = args[0]
return opts
def setup_logging(opts):
# root logger:
r = logging.getLogger()
if opts.logstream:
handler = logging.StreamHandler(opts.logstream)
f = logging.Formatter(opts.logformat)
handler.setFormatter(f)
r.addHandler(handler)
for name,level in opts.loglevels:
logging.getLogger(name).setLevel(level)
def _run(opts):
pinfo("Starting Passerd. Will listen on address %s:%d" % opts.listen)
reactor.listenTCP(interface=opts.listen[0], port=opts.listen[1],
factory=PasserdFactory(opts))
pinfo("Starting Twisted reactor loop")
try:
reactor.run()
finally:
pinfo("Terminating")
class PidFile:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
dbg("locking pidfile %s", self.filename)
self.file = open(self.filename, 'w')
fcntl.lockf(self.file, fcntl.LOCK_EX|fcntl.LOCK_NB)
self.file.write('%d\n' % (os.getpid()))
self.file.flush()
def __exit__(self):
dbg("unlocking pidfile %s", self.filename)
os.unlink(self.filename)
fcntl.lockf(self.file, fcntl.LOCK_UN)
self.file.close()
def run_as_daemon(opts):
try:
import daemon
except ImportError:
raise Exception("You need the python-daemon module, to run Passerd on daemon mode")
pidfile = None
if opts.pidfile:
pidfile = PidFile(opts.pidfile)
# I don't want python-daemon to mess with any open file. The files we open
# on initialization will be kept, because they are our log files and sockets.
# stdin/stdout/stderr will be redirected to /dev/null, so they may be kept open,
# too.
preserve = range(MAXFD)
+ dc = daemon.DaemonContext(files_preserve=preserve, pidfile=pidfile)
+ dc.open()
try:
- with daemon.DaemonContext(files_preserve=preserve, pidfile=pidfile):
- _run(opts)
+ _run(opts)
except Exception,e:
logger.exception(e)
+ dc.close()
MAXFD = 2048
def run():
# be careful: avoid opening files before the _run() call. the
# daemon module will close it if you don't include it on files_preserve.
opts = PasserdGlobalOptions()
parse_cmdline(sys.argv[1:], opts)
setup_logging(opts)
if opts.daemon_mode:
run_as_daemon(opts)
else:
_run(opts)
__all__ = ['run']
|
ehabkost/passerd
|
889aba366f4ded2f1810cfbc7ca93693d9406d13
|
improve text of rate-limit error message
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 1d28217..0012043 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -101,1026 +101,1026 @@ MAX_FRIEND_PAGE_REQS = 10
# minimum post age (in seconds) to allow it to be used for RTs.
# useful to avoid surprises when using the !RT command
#TODO: make this configurable
MIN_LATEST_POST_AGE = 2
# IRC protocol constants:
####
# Other error codes we may use:
ERR_NEEDREGGEDNICK = '477'
# logging helpers:
####
logger = logging.getLogger("passerd")
dbg = logger.debug
pinfo = logger.info
perror = logger.error
class ErrorReply(Exception):
"""Special exception class used to generate IRC numeric replies"""
def __init__(self, command, *args):
self.command = command
self.args = args
class MissingOAuthRegistration(Exception):
pass
class MessageTooLong(Exception):
def __init__(self, text, length):
self.text = text
self.length = length
Exception.__init__(self, 'message too long (%d characters)' % (length))
class TwitterUserInfo:
"""Just carries simple data for a Twitter user
"""
def from_data(self, d):
self.screen_name = d.twitter_screen_name
self.name = d.twitter_name
return self
def to_data(self, d):
d.twitter_screen_name = self.screen_name
d.twitter_name = self.name
return self
def __repr__(self):
return 'TwitterUserInfo(%r, %r)' % (self.screen_name, self.name)
class TwitterUserCache:
"""Caches information about Twitter users
This is server-global, and is just an interface to the twitter_users database
table.
"""
def __init__(self, proto):
self.proto = proto
self.callbacks = CallbackList()
def addCallback(self, cb, *args, **kwargs):
"""Add a new callback function
Callback function is called with arguments: (twitter_user, old_info, new_info)
old_info may be None, if it's a new user
"""
self.callbacks.addCallback(cb, *args, **kwargs)
def _change_data(self, d, old_info, new_info):
# callbacks must becalled _before_ updating the data:
self.callbacks.callback(d.twitter_id, old_info, new_info)
new_info.to_data(d)
def _new_user(self, id, info):
d = TwitterUserData(twitter_id=id)
self._change_data(d, None, info)
#FIXME: encapsulate the following session operations, somehow:
self.proto.data.session.add(d)
self.proto.data.session.commit()
return d
def _update_user_info(self, id, new_info):
d = self.lookup_id(id)
if d is None:
return self._new_user(id, new_info)
old_info = TwitterUserInfo().from_data(d)
self._change_data(d, old_info, new_info)
#FIXME: encapsulate the following session operation, somehow:
self.proto.data.session.commit()
return d
def update_user_info(self, id, screen_name, name):
id = int(id)
i = TwitterUserInfo()
i.screen_name = screen_name
i.name = name
return self._update_user_info(id, i)
def got_api_user_info(self, u):
self.update_user_info(u.id, u.screen_name, u.name)
def lookup_id(self, id):
id = int(id)
#FIXME: encapsulate the following session operations, somehow:
d = self.proto.data.query(TwitterUserData).get(id)
if d is None:
return None
return d
def lookup_screen_name(self, name):
# not
try:
u = self.proto.data.query(TwitterUserData).filter(func.lower(TwitterUserData.twitter_screen_name)==name.lower()).one()
except MultipleResultsFound:
# multiple matches are possible if screen_names are reused.
# if that happens, be on the safe side: don't return anything
u = None
except NoResultFound:
u = None
return u
class TwitterIrcUser(IrcUser):
"""Common class for multiple methods of contacting IRC users"""
def _target_params(self, params):
"""Must return a dictionary containing user_id or screen_name, depending on
how much information we already have about the user.
"""
raise NotImplementedError("_target_params not implemented")
def send_direct_message(self, text):
d = defer.Deferred()
ok = []
def got_msg(msg):
ok.append(msg)
d.callback(msg)
def done(*args):
if not ok:
self.proto.notice("ERROR: Didn't get direct message info back when sending DM")
self.proto.api.send_direct_message(text, delegate=got_msg, params=self._target_params()).addCallbacks(done, d.errback)
return d
def messageReceived(self, sender, msg):
assert (sender is self.proto.the_user)
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
#TODO: maybe there's a better error code for this?
raise ErrorReply(irc.RPL_AWAY, self.nick, ':message too long (%d characters), not sent.' % (len(msg)))
def doit():
self.send_direct_message(msg).addCallbacks(done, error)
def done(msg):
self.proto.notice("Direct Message to %s sent. ID: %s" % (self.nick, msg.id))
def error(e):
self.proto.send_reply(irc.RPL_AWAY, self.nick, ":Error sending Direct Message: %s" % (e.value))
doit()
class UnavailableTwitterData:
"""Fake TwitterUserData object for unavailable info"""
def __init__(self, id):
self.twitter_id = id
twitter_screen_name = property(lambda self: 'user-id-%s' % (self.twitter_id))
twitter_name = property(lambda self: 'Twitter User (info not fetched yet)')
class CachedTwitterIrcUser(TwitterIrcUser):
"""An IrcUser object for cached Twitter user info
Objects of this class may be short-lived, just to return info of a random
Twitter user for which we don't have much data.
"""
def __init__(self, proto, cache, id):
IrcUser.__init__(self, proto)
self._twitter_id = id
self.cache = cache
self._data = None
def _target_params(self):
return {'user_id':self._twitter_id}
def data_changed(self, old_info, new_info):
dbg("CachedTwitterIrcUser.data_changed! %r %r" % (old_info, new_info))
if (old_info is None) or (old_info.screen_name != new_info.screen_name):
self.notifyNickChange(str(new_info.screen_name))
def __get_data(self):
if self._data is None:
self._data = self.cache.lookup_id(self._twitter_id)
return self._data
def _get_data(self):
d = self.__get_data()
if d is None:
return UnavailableTwitterData(self._twitter_id)
return d
def has_data(self):
"""Checks if the Twitter user info is known"""
return (self.__get_data() is not None)
data = property(_get_data)
nick = property(lambda self: str(self.data.twitter_screen_name))
username = property(lambda self: str(self.data.twitter_screen_name))
real_name = property(lambda self: self.data.twitter_name.encode('utf-8'))
hostname = property(lambda self: 'twitter.com')
class UnknownTwitterUser(TwitterIrcUser):
"""An IrcUser object for an user we don't know anything about, but may be a valid Twitter user"""
def __init__(self, proto, nickname):
self.proto = proto
self.nick = nickname
self.username = nickname
real_name = 'Unknown User'
hostname = 'twitter.com'
def _target_params(self):
return {'screen_name':self.nick}
class TwitterIrcUserCache:
"""Cache of CachedTwitterIrcUser objects
A TwitterIrcUserCache is client-specific (not server-global), and takes
care of creating CachedTwitterIrcUser objects for some queries.
"""
def __init__(self, proto, cache):
self.proto = proto
self.cache = cache
self.cache.addCallback(self._user_changed)
self._watched_ids = {}
def _user_changed(self, id, old_info, new_info):
dbg("user_changed: %r, %r, %r" % (id, old_info, new_info))
if id in self._watched_ids:
dbg("user_changed (%s): is being watched." % (id))
u = self._get_user(id).data_changed(old_info, new_info)
def _get_user(self, id):
u = CachedTwitterIrcUser(self.proto, self.cache, id)
return u
def watch_user_id(self, id):
"""Start watching user ID for changes"""
self._watched_ids[id] = True
def watch_user_ids(self, ids):
for id in ids:
self.watch_user_id(id)
def watch_user(self, u):
self.watch_user_id(u._twitter_id)
def get_user(self, id):
return self._get_user(id)
def fetch_individual_user_info(self, unknown_users):
#TODO: implement me
pass
def fetch_all_friend_info(self, user, unknown_users):
#TODO: unify this paging code with the one on FriendlistMixIn
reqs = []
def request_cursor(cursor):
self.proto.dbg("requesting a page from the friend list: %s" % (str(cursor)))
reqs.append(cursor)
self.proto.api.list_friends(got_user, user=user, params={'cursor':cursor},
page_delegate=end_page).addCallbacks(done, error)
def got_user(u):
self.proto.global_twuser_cache.got_api_user_info(u)
def end_page(next, prev):
unk = [u for u in unknown_users if not u.has_data()]
num = len(unk)
if num == 0:
self.proto.notice("I know all friends of %s, now!" % (user))
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addCallback(self.got_entry)
f.addErrback(self.refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
dbg("nickname %s not found", nick)
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
dbg("no posts by uid %s", uid)
return None
if substring:
matches = []
i = 1
while i <= len(recent):
r = recent[-i]
#TODO: make it more flexible, ignoring punctuation and spaces
if substring.lower() in r.text.lower():
matches.append(r)
i += 1
if not matches:
return None
if len(matches) > 1:
raise Exception("Multiple matches for [%s] on posts by %s" % (substring, nick))
# yay, single match:
r = matches[0]
else:
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent, I don't know if it's the one you want. Use words from the text to identify it" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
dbg("#twitter got_entry. id: %s", e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("#twitter refresh error")
#FIXME: stop showing repeated errors and just let the user know when service is back
if e.check(twisted.web.error.Error):
if str(e.value.status) == '503':
self.bot_notice("Look! A flying whale! -- %s" % (e.value))
return
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.value.status == '400' and remaining == 0:
self.wait_rate_limit()
self.bot_notice("error refreshing feed: %s" % (e.value))
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
- self.bot_msg('You still can force the check by sending `!`. Also '
- 'you can check the rate limit by sending `!rate`.')
+ self.bot_msg('You can still try to fetch new tweets using `!`. Also, '
+ 'you can check the rate limit using `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallback(done)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def _friendList(self, delegate, params={}, page_delegate=None):
#TODO: include the user on the list of channel members, too
# (the user whose timeline is being followed, not the Passerd
# authenticated user)
return self.proto.api.friends_ids(delegate, self.user, params=params,
page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
|
ehabkost/passerd
|
bcfe1f4cab50dc6be3129ecf4fc9f728b13796b6
|
use python2.4 syntax on '(keyword=value, *args)' calls
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index a211164..1d28217 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -1081,1137 +1081,1137 @@ class PasserdCommands(CommandHelpMixin, CommandDialog):
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Debug the recent-post matching code"
importance_recent = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, r.text))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message("no match for [%s] on posts by %s" % (substring, nick))
else:
self.message("no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
- return self.sendMessage(*params, prefix=sender.full_id())
+ return self.sendMessage(prefix=sender.full_id(), *params)
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, version.VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, version.VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
- api = Twitter(*args, timeout=self.factory.opts.api_timeout, **kwargs)
+ api = Twitter(timeout=self.factory.opts.api_timeout, *args, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = version.USER_AGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
channel = ListChannel(self, user, list_name)
if channel:
self.channels[name] = channel
return channel
def get_channel(self, name):
return self.channels.get(name)
def get_target(self, name):
if name.startswith('#'):
return self.get_channel(name)
else:
return self.get_user(name)
def mask_matches(self, mask):
#FIXME: match wildcards?
u = self.get_user(mask)
if u:
yield u
def who_matches(self, mask):
#TODO: make WHO list channel users
for u in self.mask_matches(mask):
#XXX: WTF do "H" and "G" mean?
yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
def whois_twitter_user(self, u, tu):
self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
#FIXME: find a better way to send user information, instead of RPL_AWAY
# - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
def oneline(s):
#FIXME: create a escape_post() function
return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
def whois_mask(self, mask):
def doit():
self.dbg("fetching user info for %s" % (mask))
self.api.show_user(mask).addCallback(got_user).addErrback(error)
def got_user(tu):
self.dbg("got user info!")
self.global_twuser_cache.got_api_user_info(tu)
u = self.get_twitter_user(tu.id)
self.whois_twitter_user(u, tu)
def error(e):
self.send_reply(irc.ERR_NOSUCHNICK, mask, ':Error fetching user info - %s' % (e.value))
doit()
class PasserdFactory(Factory):
protocol = PasserdProtocol
def __init__(self, opts):
url = 'sqlite:///%s' % (opts.database)
self.opts = opts
self.data = DataStore(url)
self.data.create_tables()
self.global_twuser_cache = TwitterUserCache(self)
class PasserdGlobalOptions:
def __init__(self):
# set the defaults:
self.listen = ('0.0.0.0', 6667)
#logging:
self.logstream = sys.stderr
# list of (logger_name, level) pairs
# - sqlalchemy is too verbose on the INFO loglevel
# - enable oauth debugging, by now
self.loglevels = [(None, logging.INFO),
('sqlalchemy', logging.ERROR),
('passerd.oauth',logging.DEBUG),
('passerd.feeds',logging.DEBUG),
('passerd.scheduler',logging.DEBUG)]
self.logformat = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
self.api_timeout = 60
self.daemon_mode = False
self.pidfile = None
def parse_cmdline(args, opts):
def parse_hostport(option, optstr, value, parser):
try:
host, rawport = value.rsplit(":", 1)
port = int(rawport)
except ValueError:
parser.error("invalid listen address, expected HOST:PORT")
opts.listen = (host, port)
def set_loglevels(levels):
opts.loglevels = levels
def open_logfile(option, optstr, value, parser):
opts.logstream = open(value, 'a')
parser = optparse.OptionParser("%prog [options] <database path>")
parser.add_option("-l", "--listen", type="string",
action="callback", callback=parse_hostport,
metavar="HOST:PORT", help="listen address")
parser.add_option("-D", "--debug",
action="callback", callback=lambda *args: set_loglevels([(None,logging.DEBUG)]),
help="Enable debug logging")
parser.add_option("--logformat",
metavar="FORMAT", type="string", default=None,
help="Set the logging format")
parser.add_option("-d", "--daemon",
action="store_true", dest="daemon_mode")
parser.add_option("-L", "--log-file",
metavar="FILENAME", type="string",
action="callback", callback=open_logfile)
parser.add_option("-p", "--pid-file",
metavar="FILENAME", type="string",
dest="pidfile")
_, args = parser.parse_args(args, opts)
if not args:
parser.error("the database path is needed!")
opts.database = args[0]
return opts
def setup_logging(opts):
# root logger:
r = logging.getLogger()
if opts.logstream:
handler = logging.StreamHandler(opts.logstream)
f = logging.Formatter(opts.logformat)
handler.setFormatter(f)
r.addHandler(handler)
for name,level in opts.loglevels:
logging.getLogger(name).setLevel(level)
def _run(opts):
pinfo("Starting Passerd. Will listen on address %s:%d" % opts.listen)
reactor.listenTCP(interface=opts.listen[0], port=opts.listen[1],
factory=PasserdFactory(opts))
pinfo("Starting Twisted reactor loop")
try:
reactor.run()
finally:
pinfo("Terminating")
class PidFile:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
dbg("locking pidfile %s", self.filename)
self.file = open(self.filename, 'w')
fcntl.lockf(self.file, fcntl.LOCK_EX|fcntl.LOCK_NB)
self.file.write('%d\n' % (os.getpid()))
self.file.flush()
def __exit__(self):
dbg("unlocking pidfile %s", self.filename)
os.unlink(self.filename)
fcntl.lockf(self.file, fcntl.LOCK_UN)
self.file.close()
def run_as_daemon(opts):
try:
import daemon
except ImportError:
raise Exception("You need the python-daemon module, to run Passerd on daemon mode")
pidfile = None
if opts.pidfile:
pidfile = PidFile(opts.pidfile)
# I don't want python-daemon to mess with any open file. The files we open
# on initialization will be kept, because they are our log files and sockets.
# stdin/stdout/stderr will be redirected to /dev/null, so they may be kept open,
# too.
preserve = range(MAXFD)
try:
with daemon.DaemonContext(files_preserve=preserve, pidfile=pidfile):
_run(opts)
except Exception,e:
logger.exception(e)
MAXFD = 2048
def run():
# be careful: avoid opening files before the _run() call. the
# daemon module will close it if you don't include it on files_preserve.
opts = PasserdGlobalOptions()
parse_cmdline(sys.argv[1:], opts)
setup_logging(opts)
if opts.daemon_mode:
run_as_daemon(opts)
else:
_run(opts)
__all__ = ['run']
|
ehabkost/passerd
|
3217e40904d29393357621bfaaad877b52b8961a
|
handle windows-1252 chars too
|
diff --git a/passerd/tests/__init__.py b/passerd/tests/__init__.py
index 2b37caf..ccdf244 100644
--- a/passerd/tests/__init__.py
+++ b/passerd/tests/__init__.py
@@ -1,22 +1,22 @@
import unittest, doctest
-modules = 'dialogs formatting'.split()
+modules = 'dialogs formatting encoding'.split()
docmodules = []
def suite():
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for n in modules:
passerd = __import__('passerd.tests.%s' % (n))
module = getattr(passerd.tests, n)
tests = loader.loadTestsFromModule(module)
suite.addTests(tests)
for dm in docmodules:
suite.addTest(doctest.DocTestSuite(dm))
return suite
if __name__ == '__main__':
unittest.TextTestRunner().run(suite())
diff --git a/passerd/tests/encoding.py b/passerd/tests/encoding.py
new file mode 100644
index 0000000..22e152f
--- /dev/null
+++ b/passerd/tests/encoding.py
@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+
+import unittest
+
+from passerd.util import try_unicode
+
+class EncodingTests(unittest.TestCase):
+ def assertEqualsU(self, a, b):
+ self.assertTrue(isinstance(a, unicode))
+ self.assertTrue(isinstance(b, unicode))
+ self.assertEquals(len(a), len(b))
+ for i in range(len(a)):
+ self.assertEquals(a[i], b[i], 'mismatch at char %d: %r != %r' % (i, a[i], b[i]))
+
+ def testAscii(self):
+ self.assertEqualsU(try_unicode('abcde'), u'abcde')
+
+ def testSimpleUtf8(self):
+ # 'abcáéÃxÅ'
+ self.assertEqualsU(try_unicode('abc\xc3\xa1\xc3\xa9\xc3\xadx\xc5\x84'), u'abc\xe1\xe9\xedx\u0144')
+
+ def testUtf8BMP(self):
+ u = u''.join([unichr(i) for i in range(0, 0xdc00)])
+ e = u.encode('utf-8')
+ self.assertEquals(try_unicode(e), u)
+ self.assertEqualsU(try_unicode(e), u)
+
+ def testSimpleLatin1(self):
+ # 'abcáà üx'
+ l = 'abc\xe1\xe0\xfcx'
+ self.assertEqualsU(try_unicode(l), u'abcáà üx')
+
+ def testFullLatin1(self):
+ """ISO-8859-1 support, for all printable chars"""
+ chars = range(0x20, 0x7f)+range(0xa0,0x100)
+ l = ''.join(chr(c) for c in chars)
+ u = try_unicode(l)
+ for i in range(len(chars)):
+ self.assertEquals(chars[i], ord(u[i]))
+
+ def testSimpleWindows1252(self):
+ w = 'this is a test \x99 - d\xe9j\xe0 vu. \x9c'
+ u = try_unicode(w)
+ self.assertEqualsU(u, u'this is a test ⢠- déjà vu. Å')
diff --git a/passerd/util.py b/passerd/util.py
index b5b3f55..721993f 100644
--- a/passerd/util.py
+++ b/passerd/util.py
@@ -1,41 +1,41 @@
-ENCODINGS = ['utf-8', 'iso-8859-1']
+ENCODINGS = ['utf-8', 'windows-1252']
def hooks(fn):
"""Decorator that call beforeFoo() and afterFoo() methods if available"""
name = fn.func_name
upname = name[0].upper()+name[1:]
before = 'before%s' % (upname)
after = 'after%s' % (upname)
def call_with_hooks(self, *args, **kwargs):
if hasattr(self, before):
getattr(self, before)(*args, **kwargs)
r = fn(self, *args, **kwargs)
if hasattr(self, after):
getattr(self, after)(*args, **kwargs)
return r
return call_with_hooks
def try_unicode(s, enc=None):
for e in [enc]+ENCODINGS:
if not e:
continue
try:
return unicode(s, e)
except:
pass
# no success:
raise Exception("couldn't decode message as unicode")
def to_str(s, enc):
if isinstance(s, unicode):
return s.encode(enc)
elif isinstance(s, str):
return s
else:
raise Exception("%r is not str (type: %r)" % (s, type(s)))
|
ehabkost/passerd
|
daac34d3d0eb2651d912c01e6a4716908ceef278
|
Version 0.1.0
|
diff --git a/NEWS.markdown b/NEWS.markdown
index a00fd5d..8dcb56f 100644
--- a/NEWS.markdown
+++ b/NEWS.markdown
@@ -1,72 +1,74 @@
### Current development version:
+### Passerd 0.1.0 - 24 Jan 2010
+
* Add a simple scheduling algorithm that will make sure Passerd don't kill the
Twitter API rate-limit if the user joins too many Passerd channels.
* Fix auto-`@` of nickname replies when nicknames have digits on it
* Set timeout on API calls to avoid getting stuck if HTTP requests take too
long to reply
* Retweets are shown as messages from the original poster, with a note
by passerd-bot
(configurable by `!be concise` option)
* Multi-line tweets aren't shown as multiple lines anymore
(configurable by `!be verbose` option)
* Lower-level `!config` command to set specific configuration variables
* Support for running Passerd in _daemon_ mode
* Retweet support using `!rt` command
### Passerd 0.0.5 - 6 Jan 2010
* Don't continue refreshing feeds if rate-limit is hit. This is a temporary
solution until a true rate-limit-adjusting scheduler is written
* Unify `passerd-bot` commands and implementation of `!command` on `#twitter`
* Including a help system
* Add a `!post` command (aliases: `!tw`, `!twit`, `!update`)
* Paranoid mode: if you are afraid of posting by mistake when typing on
your IRC client, you can enable a "paranoid" mode using the `!be paranoid`
command.
When in this mode, you can only post to twitter using `!post` (or the aliases
above)
### Passerd 0.0.4.2 - 28 Dec 2009
* Updated twitty-twister version. On 0.0.4, I forgot to update the
twitty-twister git commit reference, and broke twitter posting.
### Passerd 0.0.4.1 - 28 Dec 2009
* Fix a problem on the OAuth access token request method. A POST
request with no Content-Length may case a 411 Length Required
error (probably on some proxy servers).
* Thanks to Bogdano Arendartchuk for the fix.
### Passerd 0.0.4 - 27 Dec 2009
* Ability to follow lists using `#@username/list` channels
* Ability to get updates from a single user using `#@username` channels
* Implement #mentions channel, for mentions of `@username`
* OAuth support! Now you don't need to give your Twitter password to
Passerd (and you'll get a nice "from Passerd" note on your Twits. :)
* Optional nickserv-style authentication support
* Better error messages (using a `passerd-bot` IRC user)
* Now with a real (but still a bit ugly) web page at [passerd.raisama.net](http://passerd.raisama.net/)
### Passerd 0.0.3 - 18 Dec 2009
* Ability to send updates to Twitter
* Fetch detailed user info from Twitter on-demand, only if necessary
* Basic command-line option support
* Implement Twitter follow/unfollow as IRCK KICK/INVITE
### Passerd 0.0.2 - 15 Dec 2009
* List Twitter friends as IRC contacts
### Passerd 0.0.1 - 14 Dec 2009
* Basic Twitter reading ability
diff --git a/passerd/version.py b/passerd/version.py
index 93b9e37..c0c1088 100644
--- a/passerd/version.py
+++ b/passerd/version.py
@@ -1,4 +1,4 @@
NAME = 'Passerd'
-VERSION = '0.0.5'
+VERSION = '0.1.0'
USER_AGENT = '%s/%s' % (NAME, VERSION)
URL = 'http://passerd.raisama.net/'
|
ehabkost/passerd
|
62937c0f3551e6277561a888208f318c17f493ee
|
basic distutils setup.py file
|
diff --git a/.gitignore b/.gitignore
index 5ff47da..6477d4f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
*.pyc
tags
docs/html/*.html
.*.swp
+build/
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 114866f..a211164 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -1,579 +1,576 @@
#!/usr/bin/env python
#
# Passerd - An IRC server as a gateway to Twitter
#
# Author: Eduardo Habkost <ehabkost@raisama.net>
#
# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys, os, logging, time, re, random
import fcntl, signal
import gc
import optparse
import rfc822 # for date/time parsing
from twisted.words.protocols import irc
from twisted.words.protocols.irc import IRC
from twisted.internet.protocol import Factory
from twisted.internet import reactor, defer
import twisted.web.error
from twittytwister.twitter import Twitter, TwitterClientInfo
from passerd.data import DataStore, TwitterUserData
from passerd.callbacks import CallbackList
from passerd.utils import full_entity_decode
from passerd.feeds import HomeTimelineFeed, ListTimelineFeed, UserTimelineFeed, MentionsFeed, DirectMessagesFeed
from passerd.scheduler import ApiScheduler
from passerd import dialogs
from passerd.dialogs import Dialog, CommandDialog, CommandHelpMixin, attach_dialog_to_channel, attach_dialog_to_bot
from passerd.util import try_unicode, to_str
from passerd.irc import IrcUser, IrcChannel, IrcServer
from passerd.poauth import OAuthClient, oauth_consumer
+from passerd import version
import oauth.oauth as oauth
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from sqlalchemy.sql.expression import func
# client/user-agent info:
####
-MYNAME = 'Passerd'
-VERSION = '0.0.5'
-MYAGENT = '%s/%s' % (MYNAME, VERSION)
#FIXME: use a real hostname?
MYHOST = 'passerd.server'
-MYURL = 'http://passerd.raisama.net/'
-CLIENT_INFO = TwitterClientInfo(MYNAME, VERSION, MYURL)
+CLIENT_INFO = TwitterClientInfo(version.NAME, version.VERSION, version.URL)
# IRC protocol stuff:
####
# the only mode supported, right now:
SUPPORTED_CHAN_MODES = 'b'
# No user mode is supported, by now:
SUPPORTED_USER_MODES = '0'
IRC_ENCODING = 'utf-8'
# Twitter protocol stuff:
####
BASE_URL = 'https://twitter.com'
TWITTER_ENCODING = 'utf-8'
LENGTH_LIMIT = 140
# Some limits:
####
# keep latest 100 post on each channel, to create in_reply_to field.
REPLY_HISTORY_SIZE = 100
# if more than MAX_USER_INFO_FETCH users are unknown, use /statuses/friends to fetch user info.
# otherwise, just fetch individual user info
MAX_USER_INFO_FETCH = 0 # individual fetch is not implemented yet...
# the maximum number of sequential friend list page requests:
MAX_FRIEND_PAGE_REQS = 10
# minimum post age (in seconds) to allow it to be used for RTs.
# useful to avoid surprises when using the !RT command
#TODO: make this configurable
MIN_LATEST_POST_AGE = 2
# IRC protocol constants:
####
# Other error codes we may use:
ERR_NEEDREGGEDNICK = '477'
# logging helpers:
####
logger = logging.getLogger("passerd")
dbg = logger.debug
pinfo = logger.info
perror = logger.error
class ErrorReply(Exception):
"""Special exception class used to generate IRC numeric replies"""
def __init__(self, command, *args):
self.command = command
self.args = args
class MissingOAuthRegistration(Exception):
pass
class MessageTooLong(Exception):
def __init__(self, text, length):
self.text = text
self.length = length
Exception.__init__(self, 'message too long (%d characters)' % (length))
class TwitterUserInfo:
"""Just carries simple data for a Twitter user
"""
def from_data(self, d):
self.screen_name = d.twitter_screen_name
self.name = d.twitter_name
return self
def to_data(self, d):
d.twitter_screen_name = self.screen_name
d.twitter_name = self.name
return self
def __repr__(self):
return 'TwitterUserInfo(%r, %r)' % (self.screen_name, self.name)
class TwitterUserCache:
"""Caches information about Twitter users
This is server-global, and is just an interface to the twitter_users database
table.
"""
def __init__(self, proto):
self.proto = proto
self.callbacks = CallbackList()
def addCallback(self, cb, *args, **kwargs):
"""Add a new callback function
Callback function is called with arguments: (twitter_user, old_info, new_info)
old_info may be None, if it's a new user
"""
self.callbacks.addCallback(cb, *args, **kwargs)
def _change_data(self, d, old_info, new_info):
# callbacks must becalled _before_ updating the data:
self.callbacks.callback(d.twitter_id, old_info, new_info)
new_info.to_data(d)
def _new_user(self, id, info):
d = TwitterUserData(twitter_id=id)
self._change_data(d, None, info)
#FIXME: encapsulate the following session operations, somehow:
self.proto.data.session.add(d)
self.proto.data.session.commit()
return d
def _update_user_info(self, id, new_info):
d = self.lookup_id(id)
if d is None:
return self._new_user(id, new_info)
old_info = TwitterUserInfo().from_data(d)
self._change_data(d, old_info, new_info)
#FIXME: encapsulate the following session operation, somehow:
self.proto.data.session.commit()
return d
def update_user_info(self, id, screen_name, name):
id = int(id)
i = TwitterUserInfo()
i.screen_name = screen_name
i.name = name
return self._update_user_info(id, i)
def got_api_user_info(self, u):
self.update_user_info(u.id, u.screen_name, u.name)
def lookup_id(self, id):
id = int(id)
#FIXME: encapsulate the following session operations, somehow:
d = self.proto.data.query(TwitterUserData).get(id)
if d is None:
return None
return d
def lookup_screen_name(self, name):
# not
try:
u = self.proto.data.query(TwitterUserData).filter(func.lower(TwitterUserData.twitter_screen_name)==name.lower()).one()
except MultipleResultsFound:
# multiple matches are possible if screen_names are reused.
# if that happens, be on the safe side: don't return anything
u = None
except NoResultFound:
u = None
return u
class TwitterIrcUser(IrcUser):
"""Common class for multiple methods of contacting IRC users"""
def _target_params(self, params):
"""Must return a dictionary containing user_id or screen_name, depending on
how much information we already have about the user.
"""
raise NotImplementedError("_target_params not implemented")
def send_direct_message(self, text):
d = defer.Deferred()
ok = []
def got_msg(msg):
ok.append(msg)
d.callback(msg)
def done(*args):
if not ok:
self.proto.notice("ERROR: Didn't get direct message info back when sending DM")
self.proto.api.send_direct_message(text, delegate=got_msg, params=self._target_params()).addCallbacks(done, d.errback)
return d
def messageReceived(self, sender, msg):
assert (sender is self.proto.the_user)
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
#TODO: maybe there's a better error code for this?
raise ErrorReply(irc.RPL_AWAY, self.nick, ':message too long (%d characters), not sent.' % (len(msg)))
def doit():
self.send_direct_message(msg).addCallbacks(done, error)
def done(msg):
self.proto.notice("Direct Message to %s sent. ID: %s" % (self.nick, msg.id))
def error(e):
self.proto.send_reply(irc.RPL_AWAY, self.nick, ":Error sending Direct Message: %s" % (e.value))
doit()
class UnavailableTwitterData:
"""Fake TwitterUserData object for unavailable info"""
def __init__(self, id):
self.twitter_id = id
twitter_screen_name = property(lambda self: 'user-id-%s' % (self.twitter_id))
twitter_name = property(lambda self: 'Twitter User (info not fetched yet)')
class CachedTwitterIrcUser(TwitterIrcUser):
"""An IrcUser object for cached Twitter user info
Objects of this class may be short-lived, just to return info of a random
Twitter user for which we don't have much data.
"""
def __init__(self, proto, cache, id):
IrcUser.__init__(self, proto)
self._twitter_id = id
self.cache = cache
self._data = None
def _target_params(self):
return {'user_id':self._twitter_id}
def data_changed(self, old_info, new_info):
dbg("CachedTwitterIrcUser.data_changed! %r %r" % (old_info, new_info))
if (old_info is None) or (old_info.screen_name != new_info.screen_name):
self.notifyNickChange(str(new_info.screen_name))
def __get_data(self):
if self._data is None:
self._data = self.cache.lookup_id(self._twitter_id)
return self._data
def _get_data(self):
d = self.__get_data()
if d is None:
return UnavailableTwitterData(self._twitter_id)
return d
def has_data(self):
"""Checks if the Twitter user info is known"""
return (self.__get_data() is not None)
data = property(_get_data)
nick = property(lambda self: str(self.data.twitter_screen_name))
username = property(lambda self: str(self.data.twitter_screen_name))
real_name = property(lambda self: self.data.twitter_name.encode('utf-8'))
hostname = property(lambda self: 'twitter.com')
class UnknownTwitterUser(TwitterIrcUser):
"""An IrcUser object for an user we don't know anything about, but may be a valid Twitter user"""
def __init__(self, proto, nickname):
self.proto = proto
self.nick = nickname
self.username = nickname
real_name = 'Unknown User'
hostname = 'twitter.com'
def _target_params(self):
return {'screen_name':self.nick}
class TwitterIrcUserCache:
"""Cache of CachedTwitterIrcUser objects
A TwitterIrcUserCache is client-specific (not server-global), and takes
care of creating CachedTwitterIrcUser objects for some queries.
"""
def __init__(self, proto, cache):
self.proto = proto
self.cache = cache
self.cache.addCallback(self._user_changed)
self._watched_ids = {}
def _user_changed(self, id, old_info, new_info):
dbg("user_changed: %r, %r, %r" % (id, old_info, new_info))
if id in self._watched_ids:
dbg("user_changed (%s): is being watched." % (id))
u = self._get_user(id).data_changed(old_info, new_info)
def _get_user(self, id):
u = CachedTwitterIrcUser(self.proto, self.cache, id)
return u
def watch_user_id(self, id):
"""Start watching user ID for changes"""
self._watched_ids[id] = True
def watch_user_ids(self, ids):
for id in ids:
self.watch_user_id(id)
def watch_user(self, u):
self.watch_user_id(u._twitter_id)
def get_user(self, id):
return self._get_user(id)
def fetch_individual_user_info(self, unknown_users):
#TODO: implement me
pass
def fetch_all_friend_info(self, user, unknown_users):
#TODO: unify this paging code with the one on FriendlistMixIn
reqs = []
def request_cursor(cursor):
self.proto.dbg("requesting a page from the friend list: %s" % (str(cursor)))
reqs.append(cursor)
self.proto.api.list_friends(got_user, user=user, params={'cursor':cursor},
page_delegate=end_page).addCallbacks(done, error)
def got_user(u):
self.proto.global_twuser_cache.got_api_user_info(u)
def end_page(next, prev):
unk = [u for u in unknown_users if not u.has_data()]
num = len(unk)
if num == 0:
self.proto.notice("I know all friends of %s, now!" % (user))
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addCallback(self.got_entry)
f.addErrback(self.refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
dbg("nickname %s not found", nick)
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
dbg("no posts by uid %s", uid)
return None
if substring:
matches = []
i = 1
while i <= len(recent):
r = recent[-i]
#TODO: make it more flexible, ignoring punctuation and spaces
if substring.lower() in r.text.lower():
matches.append(r)
i += 1
if not matches:
return None
if len(matches) > 1:
raise Exception("Multiple matches for [%s] on posts by %s" % (substring, nick))
# yay, single match:
r = matches[0]
else:
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent, I don't know if it's the one you want. Use words from the text to identify it" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
@@ -1269,952 +1266,952 @@ class NewUserDialog(ProtoDialog, Dialog):
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(*params, prefix=sender.full_id())
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
- self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, VERSION))
+ self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, version.VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
- self.send_reply(irc.RPL_MYINFO, self.myhost, VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
+ self.send_reply(irc.RPL_MYINFO, self.myhost, version.VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(*args, timeout=self.factory.opts.api_timeout, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
- api.agent = MYAGENT
+ api.agent = version.USER_AGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
channel = ListChannel(self, user, list_name)
if channel:
self.channels[name] = channel
return channel
def get_channel(self, name):
return self.channels.get(name)
def get_target(self, name):
if name.startswith('#'):
return self.get_channel(name)
else:
return self.get_user(name)
def mask_matches(self, mask):
#FIXME: match wildcards?
u = self.get_user(mask)
if u:
yield u
def who_matches(self, mask):
#TODO: make WHO list channel users
for u in self.mask_matches(mask):
#XXX: WTF do "H" and "G" mean?
yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
def whois_twitter_user(self, u, tu):
self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
#FIXME: find a better way to send user information, instead of RPL_AWAY
# - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
def oneline(s):
#FIXME: create a escape_post() function
return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
def whois_mask(self, mask):
def doit():
self.dbg("fetching user info for %s" % (mask))
self.api.show_user(mask).addCallback(got_user).addErrback(error)
def got_user(tu):
self.dbg("got user info!")
self.global_twuser_cache.got_api_user_info(tu)
u = self.get_twitter_user(tu.id)
self.whois_twitter_user(u, tu)
def error(e):
self.send_reply(irc.ERR_NOSUCHNICK, mask, ':Error fetching user info - %s' % (e.value))
doit()
class PasserdFactory(Factory):
protocol = PasserdProtocol
def __init__(self, opts):
url = 'sqlite:///%s' % (opts.database)
self.opts = opts
self.data = DataStore(url)
self.data.create_tables()
self.global_twuser_cache = TwitterUserCache(self)
class PasserdGlobalOptions:
def __init__(self):
# set the defaults:
self.listen = ('0.0.0.0', 6667)
#logging:
self.logstream = sys.stderr
# list of (logger_name, level) pairs
# - sqlalchemy is too verbose on the INFO loglevel
# - enable oauth debugging, by now
self.loglevels = [(None, logging.INFO),
('sqlalchemy', logging.ERROR),
('passerd.oauth',logging.DEBUG),
('passerd.feeds',logging.DEBUG),
('passerd.scheduler',logging.DEBUG)]
self.logformat = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
self.api_timeout = 60
self.daemon_mode = False
self.pidfile = None
def parse_cmdline(args, opts):
def parse_hostport(option, optstr, value, parser):
try:
host, rawport = value.rsplit(":", 1)
port = int(rawport)
except ValueError:
parser.error("invalid listen address, expected HOST:PORT")
opts.listen = (host, port)
def set_loglevels(levels):
opts.loglevels = levels
def open_logfile(option, optstr, value, parser):
opts.logstream = open(value, 'a')
parser = optparse.OptionParser("%prog [options] <database path>")
parser.add_option("-l", "--listen", type="string",
action="callback", callback=parse_hostport,
metavar="HOST:PORT", help="listen address")
parser.add_option("-D", "--debug",
action="callback", callback=lambda *args: set_loglevels([(None,logging.DEBUG)]),
help="Enable debug logging")
parser.add_option("--logformat",
metavar="FORMAT", type="string", default=None,
help="Set the logging format")
parser.add_option("-d", "--daemon",
action="store_true", dest="daemon_mode")
parser.add_option("-L", "--log-file",
metavar="FILENAME", type="string",
action="callback", callback=open_logfile)
parser.add_option("-p", "--pid-file",
metavar="FILENAME", type="string",
dest="pidfile")
_, args = parser.parse_args(args, opts)
if not args:
parser.error("the database path is needed!")
opts.database = args[0]
return opts
def setup_logging(opts):
# root logger:
r = logging.getLogger()
if opts.logstream:
handler = logging.StreamHandler(opts.logstream)
f = logging.Formatter(opts.logformat)
handler.setFormatter(f)
r.addHandler(handler)
for name,level in opts.loglevels:
logging.getLogger(name).setLevel(level)
def _run(opts):
pinfo("Starting Passerd. Will listen on address %s:%d" % opts.listen)
reactor.listenTCP(interface=opts.listen[0], port=opts.listen[1],
factory=PasserdFactory(opts))
pinfo("Starting Twisted reactor loop")
try:
reactor.run()
finally:
pinfo("Terminating")
class PidFile:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
dbg("locking pidfile %s", self.filename)
self.file = open(self.filename, 'w')
fcntl.lockf(self.file, fcntl.LOCK_EX|fcntl.LOCK_NB)
self.file.write('%d\n' % (os.getpid()))
self.file.flush()
def __exit__(self):
dbg("unlocking pidfile %s", self.filename)
os.unlink(self.filename)
fcntl.lockf(self.file, fcntl.LOCK_UN)
self.file.close()
def run_as_daemon(opts):
try:
import daemon
except ImportError:
raise Exception("You need the python-daemon module, to run Passerd on daemon mode")
pidfile = None
if opts.pidfile:
pidfile = PidFile(opts.pidfile)
# I don't want python-daemon to mess with any open file. The files we open
# on initialization will be kept, because they are our log files and sockets.
# stdin/stdout/stderr will be redirected to /dev/null, so they may be kept open,
# too.
preserve = range(MAXFD)
try:
with daemon.DaemonContext(files_preserve=preserve, pidfile=pidfile):
_run(opts)
except Exception,e:
logger.exception(e)
MAXFD = 2048
def run():
# be careful: avoid opening files before the _run() call. the
# daemon module will close it if you don't include it on files_preserve.
opts = PasserdGlobalOptions()
parse_cmdline(sys.argv[1:], opts)
setup_logging(opts)
if opts.daemon_mode:
run_as_daemon(opts)
else:
_run(opts)
__all__ = ['run']
diff --git a/passerd/version.py b/passerd/version.py
new file mode 100644
index 0000000..93b9e37
--- /dev/null
+++ b/passerd/version.py
@@ -0,0 +1,4 @@
+NAME = 'Passerd'
+VERSION = '0.0.5'
+USER_AGENT = '%s/%s' % (NAME, VERSION)
+URL = 'http://passerd.raisama.net/'
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..a9f53dd
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,13 @@
+from distutils.core import setup
+from passerd import version
+setup(name='passerd',
+ version=version.VERSION,
+ description='Passerd IRC-Twitter gateway',
+ url=version.URL,
+ author='Eduardo Habkost',
+ author_email='ehabkost@raisama.net',
+ license='MIT',
+ platforms='any',
+ packages=['passerd'],
+ scripts=['bin/passerd'],
+ )
|
ehabkost/passerd
|
e855dc1aa6ebfeedcdc66eb52924735c6eb84ac9
|
daemon setup & pidfile changes
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index a188aa5..114866f 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -1,539 +1,540 @@
#!/usr/bin/env python
#
# Passerd - An IRC server as a gateway to Twitter
#
# Author: Eduardo Habkost <ehabkost@raisama.net>
#
# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
-import sys, logging, time, re, random
+import sys, os, logging, time, re, random
+import fcntl, signal
import gc
import optparse
import rfc822 # for date/time parsing
from twisted.words.protocols import irc
from twisted.words.protocols.irc import IRC
from twisted.internet.protocol import Factory
from twisted.internet import reactor, defer
import twisted.web.error
from twittytwister.twitter import Twitter, TwitterClientInfo
from passerd.data import DataStore, TwitterUserData
from passerd.callbacks import CallbackList
from passerd.utils import full_entity_decode
from passerd.feeds import HomeTimelineFeed, ListTimelineFeed, UserTimelineFeed, MentionsFeed, DirectMessagesFeed
from passerd.scheduler import ApiScheduler
from passerd import dialogs
from passerd.dialogs import Dialog, CommandDialog, CommandHelpMixin, attach_dialog_to_channel, attach_dialog_to_bot
from passerd.util import try_unicode, to_str
from passerd.irc import IrcUser, IrcChannel, IrcServer
from passerd.poauth import OAuthClient, oauth_consumer
import oauth.oauth as oauth
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from sqlalchemy.sql.expression import func
# client/user-agent info:
####
MYNAME = 'Passerd'
VERSION = '0.0.5'
MYAGENT = '%s/%s' % (MYNAME, VERSION)
#FIXME: use a real hostname?
MYHOST = 'passerd.server'
MYURL = 'http://passerd.raisama.net/'
CLIENT_INFO = TwitterClientInfo(MYNAME, VERSION, MYURL)
# IRC protocol stuff:
####
# the only mode supported, right now:
SUPPORTED_CHAN_MODES = 'b'
# No user mode is supported, by now:
SUPPORTED_USER_MODES = '0'
IRC_ENCODING = 'utf-8'
# Twitter protocol stuff:
####
BASE_URL = 'https://twitter.com'
TWITTER_ENCODING = 'utf-8'
LENGTH_LIMIT = 140
# Some limits:
####
# keep latest 100 post on each channel, to create in_reply_to field.
REPLY_HISTORY_SIZE = 100
# if more than MAX_USER_INFO_FETCH users are unknown, use /statuses/friends to fetch user info.
# otherwise, just fetch individual user info
MAX_USER_INFO_FETCH = 0 # individual fetch is not implemented yet...
# the maximum number of sequential friend list page requests:
MAX_FRIEND_PAGE_REQS = 10
# minimum post age (in seconds) to allow it to be used for RTs.
# useful to avoid surprises when using the !RT command
#TODO: make this configurable
MIN_LATEST_POST_AGE = 2
# IRC protocol constants:
####
# Other error codes we may use:
ERR_NEEDREGGEDNICK = '477'
# logging helpers:
####
logger = logging.getLogger("passerd")
dbg = logger.debug
pinfo = logger.info
perror = logger.error
class ErrorReply(Exception):
"""Special exception class used to generate IRC numeric replies"""
def __init__(self, command, *args):
self.command = command
self.args = args
class MissingOAuthRegistration(Exception):
pass
class MessageTooLong(Exception):
def __init__(self, text, length):
self.text = text
self.length = length
Exception.__init__(self, 'message too long (%d characters)' % (length))
class TwitterUserInfo:
"""Just carries simple data for a Twitter user
"""
def from_data(self, d):
self.screen_name = d.twitter_screen_name
self.name = d.twitter_name
return self
def to_data(self, d):
d.twitter_screen_name = self.screen_name
d.twitter_name = self.name
return self
def __repr__(self):
return 'TwitterUserInfo(%r, %r)' % (self.screen_name, self.name)
class TwitterUserCache:
"""Caches information about Twitter users
This is server-global, and is just an interface to the twitter_users database
table.
"""
def __init__(self, proto):
self.proto = proto
self.callbacks = CallbackList()
def addCallback(self, cb, *args, **kwargs):
"""Add a new callback function
Callback function is called with arguments: (twitter_user, old_info, new_info)
old_info may be None, if it's a new user
"""
self.callbacks.addCallback(cb, *args, **kwargs)
def _change_data(self, d, old_info, new_info):
# callbacks must becalled _before_ updating the data:
self.callbacks.callback(d.twitter_id, old_info, new_info)
new_info.to_data(d)
def _new_user(self, id, info):
d = TwitterUserData(twitter_id=id)
self._change_data(d, None, info)
#FIXME: encapsulate the following session operations, somehow:
self.proto.data.session.add(d)
self.proto.data.session.commit()
return d
def _update_user_info(self, id, new_info):
d = self.lookup_id(id)
if d is None:
return self._new_user(id, new_info)
old_info = TwitterUserInfo().from_data(d)
self._change_data(d, old_info, new_info)
#FIXME: encapsulate the following session operation, somehow:
self.proto.data.session.commit()
return d
def update_user_info(self, id, screen_name, name):
id = int(id)
i = TwitterUserInfo()
i.screen_name = screen_name
i.name = name
return self._update_user_info(id, i)
def got_api_user_info(self, u):
self.update_user_info(u.id, u.screen_name, u.name)
def lookup_id(self, id):
id = int(id)
#FIXME: encapsulate the following session operations, somehow:
d = self.proto.data.query(TwitterUserData).get(id)
if d is None:
return None
return d
def lookup_screen_name(self, name):
# not
try:
u = self.proto.data.query(TwitterUserData).filter(func.lower(TwitterUserData.twitter_screen_name)==name.lower()).one()
except MultipleResultsFound:
# multiple matches are possible if screen_names are reused.
# if that happens, be on the safe side: don't return anything
u = None
except NoResultFound:
u = None
return u
class TwitterIrcUser(IrcUser):
"""Common class for multiple methods of contacting IRC users"""
def _target_params(self, params):
"""Must return a dictionary containing user_id or screen_name, depending on
how much information we already have about the user.
"""
raise NotImplementedError("_target_params not implemented")
def send_direct_message(self, text):
d = defer.Deferred()
ok = []
def got_msg(msg):
ok.append(msg)
d.callback(msg)
def done(*args):
if not ok:
self.proto.notice("ERROR: Didn't get direct message info back when sending DM")
self.proto.api.send_direct_message(text, delegate=got_msg, params=self._target_params()).addCallbacks(done, d.errback)
return d
def messageReceived(self, sender, msg):
assert (sender is self.proto.the_user)
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
#TODO: maybe there's a better error code for this?
raise ErrorReply(irc.RPL_AWAY, self.nick, ':message too long (%d characters), not sent.' % (len(msg)))
def doit():
self.send_direct_message(msg).addCallbacks(done, error)
def done(msg):
self.proto.notice("Direct Message to %s sent. ID: %s" % (self.nick, msg.id))
def error(e):
self.proto.send_reply(irc.RPL_AWAY, self.nick, ":Error sending Direct Message: %s" % (e.value))
doit()
class UnavailableTwitterData:
"""Fake TwitterUserData object for unavailable info"""
def __init__(self, id):
self.twitter_id = id
twitter_screen_name = property(lambda self: 'user-id-%s' % (self.twitter_id))
twitter_name = property(lambda self: 'Twitter User (info not fetched yet)')
class CachedTwitterIrcUser(TwitterIrcUser):
"""An IrcUser object for cached Twitter user info
Objects of this class may be short-lived, just to return info of a random
Twitter user for which we don't have much data.
"""
def __init__(self, proto, cache, id):
IrcUser.__init__(self, proto)
self._twitter_id = id
self.cache = cache
self._data = None
def _target_params(self):
return {'user_id':self._twitter_id}
def data_changed(self, old_info, new_info):
dbg("CachedTwitterIrcUser.data_changed! %r %r" % (old_info, new_info))
if (old_info is None) or (old_info.screen_name != new_info.screen_name):
self.notifyNickChange(str(new_info.screen_name))
def __get_data(self):
if self._data is None:
self._data = self.cache.lookup_id(self._twitter_id)
return self._data
def _get_data(self):
d = self.__get_data()
if d is None:
return UnavailableTwitterData(self._twitter_id)
return d
def has_data(self):
"""Checks if the Twitter user info is known"""
return (self.__get_data() is not None)
data = property(_get_data)
nick = property(lambda self: str(self.data.twitter_screen_name))
username = property(lambda self: str(self.data.twitter_screen_name))
real_name = property(lambda self: self.data.twitter_name.encode('utf-8'))
hostname = property(lambda self: 'twitter.com')
class UnknownTwitterUser(TwitterIrcUser):
"""An IrcUser object for an user we don't know anything about, but may be a valid Twitter user"""
def __init__(self, proto, nickname):
self.proto = proto
self.nick = nickname
self.username = nickname
real_name = 'Unknown User'
hostname = 'twitter.com'
def _target_params(self):
return {'screen_name':self.nick}
class TwitterIrcUserCache:
"""Cache of CachedTwitterIrcUser objects
A TwitterIrcUserCache is client-specific (not server-global), and takes
care of creating CachedTwitterIrcUser objects for some queries.
"""
def __init__(self, proto, cache):
self.proto = proto
self.cache = cache
self.cache.addCallback(self._user_changed)
self._watched_ids = {}
def _user_changed(self, id, old_info, new_info):
dbg("user_changed: %r, %r, %r" % (id, old_info, new_info))
if id in self._watched_ids:
dbg("user_changed (%s): is being watched." % (id))
u = self._get_user(id).data_changed(old_info, new_info)
def _get_user(self, id):
u = CachedTwitterIrcUser(self.proto, self.cache, id)
return u
def watch_user_id(self, id):
"""Start watching user ID for changes"""
self._watched_ids[id] = True
def watch_user_ids(self, ids):
for id in ids:
self.watch_user_id(id)
def watch_user(self, u):
self.watch_user_id(u._twitter_id)
def get_user(self, id):
return self._get_user(id)
def fetch_individual_user_info(self, unknown_users):
#TODO: implement me
pass
def fetch_all_friend_info(self, user, unknown_users):
#TODO: unify this paging code with the one on FriendlistMixIn
reqs = []
def request_cursor(cursor):
self.proto.dbg("requesting a page from the friend list: %s" % (str(cursor)))
reqs.append(cursor)
self.proto.api.list_friends(got_user, user=user, params={'cursor':cursor},
page_delegate=end_page).addCallbacks(done, error)
def got_user(u):
self.proto.global_twuser_cache.got_api_user_info(u)
def end_page(next, prev):
unk = [u for u in unknown_users if not u.has_data()]
num = len(unk)
if num == 0:
self.proto.notice("I know all friends of %s, now!" % (user))
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addCallback(self.got_entry)
f.addErrback(self.refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
dbg("nickname %s not found", nick)
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
dbg("no posts by uid %s", uid)
return None
@@ -1632,565 +1633,588 @@ class PasserdProtocol(IRC):
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(*args, timeout=self.factory.opts.api_timeout, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = MYAGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
channel = ListChannel(self, user, list_name)
if channel:
self.channels[name] = channel
return channel
def get_channel(self, name):
return self.channels.get(name)
def get_target(self, name):
if name.startswith('#'):
return self.get_channel(name)
else:
return self.get_user(name)
def mask_matches(self, mask):
#FIXME: match wildcards?
u = self.get_user(mask)
if u:
yield u
def who_matches(self, mask):
#TODO: make WHO list channel users
for u in self.mask_matches(mask):
#XXX: WTF do "H" and "G" mean?
yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
def whois_twitter_user(self, u, tu):
self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
#FIXME: find a better way to send user information, instead of RPL_AWAY
# - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
def oneline(s):
#FIXME: create a escape_post() function
return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
def whois_mask(self, mask):
def doit():
self.dbg("fetching user info for %s" % (mask))
self.api.show_user(mask).addCallback(got_user).addErrback(error)
def got_user(tu):
self.dbg("got user info!")
self.global_twuser_cache.got_api_user_info(tu)
u = self.get_twitter_user(tu.id)
self.whois_twitter_user(u, tu)
def error(e):
self.send_reply(irc.ERR_NOSUCHNICK, mask, ':Error fetching user info - %s' % (e.value))
doit()
class PasserdFactory(Factory):
protocol = PasserdProtocol
def __init__(self, opts):
url = 'sqlite:///%s' % (opts.database)
self.opts = opts
self.data = DataStore(url)
self.data.create_tables()
self.global_twuser_cache = TwitterUserCache(self)
class PasserdGlobalOptions:
def __init__(self):
# set the defaults:
self.listen = ('0.0.0.0', 6667)
#logging:
self.logstream = sys.stderr
# list of (logger_name, level) pairs
# - sqlalchemy is too verbose on the INFO loglevel
# - enable oauth debugging, by now
self.loglevels = [(None, logging.INFO),
('sqlalchemy', logging.ERROR),
('passerd.oauth',logging.DEBUG),
('passerd.feeds',logging.DEBUG),
('passerd.scheduler',logging.DEBUG)]
self.logformat = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
self.api_timeout = 60
self.daemon_mode = False
self.pidfile = None
def parse_cmdline(args, opts):
def parse_hostport(option, optstr, value, parser):
try:
host, rawport = value.rsplit(":", 1)
port = int(rawport)
except ValueError:
parser.error("invalid listen address, expected HOST:PORT")
opts.listen = (host, port)
def set_loglevels(levels):
opts.loglevels = levels
def open_logfile(option, optstr, value, parser):
opts.logstream = open(value, 'a')
parser = optparse.OptionParser("%prog [options] <database path>")
parser.add_option("-l", "--listen", type="string",
action="callback", callback=parse_hostport,
metavar="HOST:PORT", help="listen address")
parser.add_option("-D", "--debug",
action="callback", callback=lambda *args: set_loglevels([(None,logging.DEBUG)]),
help="Enable debug logging")
parser.add_option("--logformat",
metavar="FORMAT", type="string", default=None,
help="Set the logging format")
parser.add_option("-d", "--daemon",
action="store_true", dest="daemon_mode")
parser.add_option("-L", "--log-file",
metavar="FILENAME", type="string",
action="callback", callback=open_logfile)
parser.add_option("-p", "--pid-file",
metavar="FILENAME", type="string",
dest="pidfile")
_, args = parser.parse_args(args, opts)
if not args:
parser.error("the database path is needed!")
opts.database = args[0]
return opts
def setup_logging(opts):
-
# root logger:
r = logging.getLogger()
if opts.logstream:
handler = logging.StreamHandler(opts.logstream)
f = logging.Formatter(opts.logformat)
handler.setFormatter(f)
r.addHandler(handler)
for name,level in opts.loglevels:
logging.getLogger(name).setLevel(level)
-
def _run(opts):
pinfo("Starting Passerd. Will listen on address %s:%d" % opts.listen)
reactor.listenTCP(interface=opts.listen[0], port=opts.listen[1],
factory=PasserdFactory(opts))
pinfo("Starting Twisted reactor loop")
- reactor.run()
+ try:
+ reactor.run()
+ finally:
+ pinfo("Terminating")
+
+class PidFile:
+ def __init__(self, filename):
+ self.filename = filename
+
+ def __enter__(self):
+ dbg("locking pidfile %s", self.filename)
+ self.file = open(self.filename, 'w')
+ fcntl.lockf(self.file, fcntl.LOCK_EX|fcntl.LOCK_NB)
+ self.file.write('%d\n' % (os.getpid()))
+ self.file.flush()
+
+ def __exit__(self):
+ dbg("unlocking pidfile %s", self.filename)
+ os.unlink(self.filename)
+ fcntl.lockf(self.file, fcntl.LOCK_UN)
+ self.file.close()
+
+
+def run_as_daemon(opts):
+ try:
+ import daemon
+ except ImportError:
+ raise Exception("You need the python-daemon module, to run Passerd on daemon mode")
+
+ pidfile = None
+ if opts.pidfile:
+ pidfile = PidFile(opts.pidfile)
+
+ # I don't want python-daemon to mess with any open file. The files we open
+ # on initialization will be kept, because they are our log files and sockets.
+ # stdin/stdout/stderr will be redirected to /dev/null, so they may be kept open,
+ # too.
+ preserve = range(MAXFD)
+ try:
+ with daemon.DaemonContext(files_preserve=preserve, pidfile=pidfile):
+ _run(opts)
+ except Exception,e:
+ logger.exception(e)
+
+MAXFD = 2048
def run():
# be careful: avoid opening files before the _run() call. the
# daemon module will close it if you don't include it on files_preserve.
opts = PasserdGlobalOptions()
parse_cmdline(sys.argv[1:], opts)
- setup_logging(opts)
- preserve = []
- if opts.logstream:
- preserve.append(opts.logstream)
-
- pidfile = None
- if opts.pidfile:
- try:
- import lockfile
- except ImportError:
- raise Exception("You need the Python lockfile module, to set a pidfile")
- pidfile = lockfile.FileLock(opts.pidfile)
+ setup_logging(opts)
if opts.daemon_mode:
- try:
- import daemon
- except ImportError:
- raise Exception("You need the python-daemon module, to run Passerd on daemon mode")
- with daemon.DaemonContext(files_preserve=preserve, pidfile=pidfile):
- try:
- _run(opts)
- except Exception,e:
- logger.exception(e)
+ run_as_daemon(opts)
else:
_run(opts)
__all__ = ['run']
|
ehabkost/passerd
|
d078968e20c2f4fc6739fc6544ecdbca7888e7c8
|
full_entity_decode: decode all html entities twice
|
diff --git a/passerd/utils.py b/passerd/utils.py
index a40b22c..855e27c 100644
--- a/passerd/utils.py
+++ b/passerd/utils.py
@@ -1,30 +1,30 @@
"""
Random utility functions
`htmlentitydecode` based on example from:
http://wiki.python.org/moin/EscapingHtml
"""
import re
from htmlentitydefs import name2codepoint
def htmlentitydecode(s):
s = re.sub(
'&(%s);' % '|'.join(name2codepoint),
lambda m: unichr(name2codepoint[m.group(1)]), s)
s = re.sub('&#([0-9]+);', lambda m: unichr(int(m.group(1))), s)
return s
def undo_xss_escaping(s):
# undo the '<' and '>' escaping done by Twitter
return s.replace('<', '<').replace('>', '>')
def full_entity_decode(s):
"""Undo the stupid entity encoding done by Twitter
- '>' and '<' are entity-encoded twice!
+ Data is entity-encoded twice!
"""
- return undo_xss_escaping(htmlentitydecode(s))
+ return htmlentitydecode(htmlentitydecode(s))
__all__ = ["htmlentitydecode", "undo_xss_escaping", "full_entity_decode"]
|
ehabkost/passerd
|
b0db0be8636d46c40d526f39ec7c9702fef4e29d
|
fix setting of importance of !recent command
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 4e6fb09..a188aa5 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -637,1026 +637,1026 @@ class TwitterChannel(IrcChannel):
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallback(done)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def _friendList(self, delegate, params={}, page_delegate=None):
#TODO: include the user on the list of channel members, too
# (the user whose timeline is being followed, not the Passerd
# authenticated user)
return self.proto.api.friends_ids(delegate, self.user, params=params,
page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
- shorthelp_recent = "Test the recent-post matching code"
- importance_gc = dialogs.CMD_IMP_DEBUGGING
+ shorthelp_recent = "Debug the recent-post matching code"
+ importance_recent = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, r.text))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_rt = "Retweet a post"
importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
self.message('If no text is specified, the latest post from <nick> is retweeted.')
self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message("no match for [%s] on posts by %s" % (substring, nick))
else:
self.message("no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(*params, prefix=sender.full_id())
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
|
ehabkost/passerd
|
25d00dcd37f72ea27d86921bc61d767fb0d8b189
|
fix !rt help text
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 2fb84ed..4e6fb09 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -653,1028 +653,1030 @@ class TwitterChannel(IrcChannel):
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def _friendList(self, delegate, params={}, page_delegate=None):
#TODO: include the user on the list of channel members, too
# (the user whose timeline is being followed, not the Passerd
# authenticated user)
return self.proto.api.friends_ids(delegate, self.user, params=params,
page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Test the recent-post matching code"
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, r.text))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
- shorthelp_recent = "Retweet a post"
- importance_gc = dialogs.CMD_IMP_COMMON
+ shorthelp_rt = "Retweet a post"
+ importance_rt = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
+ self.message('If no text is specified, the latest post from <nick> is retweeted.')
+ self.message('If text is specified, the post containing the supplied text is retweeted')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message("no match for [%s] on posts by %s" % (substring, nick))
else:
self.message("no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
#FIXME: create a escape_post() function
t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
#FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(*params, prefix=sender.full_id())
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
|
ehabkost/passerd
|
1ccef2099b468e0646b3a34d4eed5111ab2ad162
|
fix multi-line-reply bug on RT command reply
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 8c5ecb4..2fb84ed 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -680,1512 +680,1515 @@ class TwitterChannel(IrcChannel):
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def _friendList(self, delegate, params={}, page_delegate=None):
#TODO: include the user on the list of channel members, too
# (the user whose timeline is being followed, not the Passerd
# authenticated user)
return self.proto.api.friends_ids(delegate, self.user, params=params,
page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Test the recent-post matching code"
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, r.text))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Retweet a post"
importance_gc = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message("no match for [%s] on posts by %s" % (substring, nick))
else:
self.message("no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
- self.message("Retweeted: <%s> %s" % (r.user.screen_name, r.text))
-
+ #FIXME: create a escape_post() function
+ t = full_entity_decode(r.text).replace('\n', ' ').replace('\r', ' ')
+ self.message("Retweeted: <%s> %s" % (r.user.screen_name, t))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
+ #FIXME: create a escape_post() function
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(*params, prefix=sender.full_id())
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel notice: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
if '\r' in msg or '\n' in msg: # just in case
logger.error("Oops! newlines on channel privmsg: %r", msg)
msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(*args, timeout=self.factory.opts.api_timeout, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = MYAGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
channel = ListChannel(self, user, list_name)
if channel:
self.channels[name] = channel
return channel
def get_channel(self, name):
return self.channels.get(name)
def get_target(self, name):
if name.startswith('#'):
return self.get_channel(name)
else:
return self.get_user(name)
def mask_matches(self, mask):
#FIXME: match wildcards?
u = self.get_user(mask)
if u:
yield u
def who_matches(self, mask):
#TODO: make WHO list channel users
for u in self.mask_matches(mask):
#XXX: WTF do "H" and "G" mean?
yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
def whois_twitter_user(self, u, tu):
self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
#FIXME: find a better way to send user information, instead of RPL_AWAY
# - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
def oneline(s):
+ #FIXME: create a escape_post() function
return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
def whois_mask(self, mask):
def doit():
self.dbg("fetching user info for %s" % (mask))
self.api.show_user(mask).addCallback(got_user).addErrback(error)
def got_user(tu):
self.dbg("got user info!")
self.global_twuser_cache.got_api_user_info(tu)
u = self.get_twitter_user(tu.id)
self.whois_twitter_user(u, tu)
def error(e):
self.send_reply(irc.ERR_NOSUCHNICK, mask, ':Error fetching user info - %s' % (e.value))
doit()
class PasserdFactory(Factory):
protocol = PasserdProtocol
def __init__(self, opts):
url = 'sqlite:///%s' % (opts.database)
self.opts = opts
self.data = DataStore(url)
self.data.create_tables()
self.global_twuser_cache = TwitterUserCache(self)
class PasserdGlobalOptions:
def __init__(self):
# set the defaults:
self.listen = ('0.0.0.0', 6667)
#logging:
self.logstream = sys.stderr
# list of (logger_name, level) pairs
# - sqlalchemy is too verbose on the INFO loglevel
# - enable oauth debugging, by now
self.loglevels = [(None, logging.INFO),
('sqlalchemy', logging.ERROR),
('passerd.oauth',logging.DEBUG),
('passerd.feeds',logging.DEBUG),
('passerd.scheduler',logging.DEBUG)]
self.logformat = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
self.api_timeout = 60
self.daemon_mode = False
self.pidfile = None
def parse_cmdline(args, opts):
def parse_hostport(option, optstr, value, parser):
try:
host, rawport = value.rsplit(":", 1)
port = int(rawport)
except ValueError:
parser.error("invalid listen address, expected HOST:PORT")
opts.listen = (host, port)
def set_loglevels(levels):
opts.loglevels = levels
def open_logfile(option, optstr, value, parser):
opts.logstream = open(value, 'a')
parser = optparse.OptionParser("%prog [options] <database path>")
parser.add_option("-l", "--listen", type="string",
action="callback", callback=parse_hostport,
metavar="HOST:PORT", help="listen address")
parser.add_option("-D", "--debug",
action="callback", callback=lambda *args: set_loglevels([(None,logging.DEBUG)]),
help="Enable debug logging")
parser.add_option("--logformat",
metavar="FORMAT", type="string", default=None,
help="Set the logging format")
parser.add_option("-d", "--daemon",
action="store_true", dest="daemon_mode")
parser.add_option("-L", "--log-file",
metavar="FILENAME", type="string",
action="callback", callback=open_logfile)
parser.add_option("-p", "--pid-file",
metavar="FILENAME", type="string",
dest="pidfile")
_, args = parser.parse_args(args, opts)
if not args:
parser.error("the database path is needed!")
opts.database = args[0]
return opts
def setup_logging(opts):
# root logger:
r = logging.getLogger()
if opts.logstream:
handler = logging.StreamHandler(opts.logstream)
f = logging.Formatter(opts.logformat)
handler.setFormatter(f)
r.addHandler(handler)
for name,level in opts.loglevels:
logging.getLogger(name).setLevel(level)
def _run(opts):
pinfo("Starting Passerd. Will listen on address %s:%d" % opts.listen)
reactor.listenTCP(interface=opts.listen[0], port=opts.listen[1],
factory=PasserdFactory(opts))
pinfo("Starting Twisted reactor loop")
reactor.run()
def run():
# be careful: avoid opening files before the _run() call. the
# daemon module will close it if you don't include it on files_preserve.
opts = PasserdGlobalOptions()
parse_cmdline(sys.argv[1:], opts)
setup_logging(opts)
preserve = []
if opts.logstream:
preserve.append(opts.logstream)
pidfile = None
if opts.pidfile:
try:
import lockfile
except ImportError:
raise Exception("You need the Python lockfile module, to set a pidfile")
pidfile = lockfile.FileLock(opts.pidfile)
if opts.daemon_mode:
try:
import daemon
except ImportError:
raise Exception("You need the python-daemon module, to run Passerd on daemon mode")
with daemon.DaemonContext(files_preserve=preserve, pidfile=pidfile):
try:
_run(opts)
except Exception,e:
logger.exception(e)
else:
_run(opts)
__all__ = ['run']
|
ehabkost/passerd
|
920890293f84487b7e3416080a2bee06996492c8
|
protect send_notice() & send_privmsg() against newlines
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 25e47a8..8c5ecb4 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -1088,1027 +1088,1033 @@ class PasserdCommands(CommandHelpMixin, CommandDialog):
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Test the recent-post matching code"
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_recent(self, args):
nick,substring = self.split_args(args)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if r:
self.message("match: id: %r. text: %r" % (r.id, r.text))
else:
self.message("no match...")
#TODO: add 'needs_chan' decorator
shorthelp_recent = "Retweet a post"
importance_gc = dialogs.CMD_IMP_COMMON
def help_rt(self, args):
self.cmd_syntax('rt', 'nick [part of post text]')
def command_rt(self, args):
if not self.chan:
self.message("The RT command only works in a channel")
return
nick,substring = self.split_args(args)
try:
r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
except Exception,e:
self.message("error: %s" % (e))
return
if not r:
if substring:
self.message("no match for [%s] on posts by %s" % (substring, nick))
else:
self.message("no posts from %s" % (nick))
return
data = []
def got_it(e):
r = e.retweeted_status
data.append(r)
self.message("Retweeted: <%s> %s" % (r.user.screen_name, r.text))
def done(*args):
if not data:
self.message("Unexpected error: no RT data returned by the Twitter server")
def error(e):
self.message("Error while retweeting: %s" % (e.value))
self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(*params, prefix=sender.full_id())
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
+ if '\r' in msg or '\n' in msg: # just in case
+ logger.error("Oops! newlines on channel notice: %r", msg)
+ msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
+ if '\r' in msg or '\n' in msg: # just in case
+ logger.error("Oops! newlines on channel privmsg: %r", msg)
+ msg = msg.replace('\r',' ').replace('\n', ' ')
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(*args, timeout=self.factory.opts.api_timeout, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = MYAGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
channel = ListChannel(self, user, list_name)
if channel:
self.channels[name] = channel
return channel
def get_channel(self, name):
return self.channels.get(name)
def get_target(self, name):
if name.startswith('#'):
return self.get_channel(name)
else:
return self.get_user(name)
def mask_matches(self, mask):
#FIXME: match wildcards?
u = self.get_user(mask)
if u:
yield u
def who_matches(self, mask):
#TODO: make WHO list channel users
for u in self.mask_matches(mask):
#XXX: WTF do "H" and "G" mean?
yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
def whois_twitter_user(self, u, tu):
self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
#FIXME: find a better way to send user information, instead of RPL_AWAY
# - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
def oneline(s):
return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
def whois_mask(self, mask):
def doit():
self.dbg("fetching user info for %s" % (mask))
self.api.show_user(mask).addCallback(got_user).addErrback(error)
def got_user(tu):
self.dbg("got user info!")
self.global_twuser_cache.got_api_user_info(tu)
u = self.get_twitter_user(tu.id)
self.whois_twitter_user(u, tu)
def error(e):
self.send_reply(irc.ERR_NOSUCHNICK, mask, ':Error fetching user info - %s' % (e.value))
doit()
class PasserdFactory(Factory):
protocol = PasserdProtocol
def __init__(self, opts):
url = 'sqlite:///%s' % (opts.database)
self.opts = opts
self.data = DataStore(url)
self.data.create_tables()
self.global_twuser_cache = TwitterUserCache(self)
class PasserdGlobalOptions:
def __init__(self):
# set the defaults:
self.listen = ('0.0.0.0', 6667)
#logging:
self.logstream = sys.stderr
# list of (logger_name, level) pairs
# - sqlalchemy is too verbose on the INFO loglevel
# - enable oauth debugging, by now
self.loglevels = [(None, logging.INFO),
('sqlalchemy', logging.ERROR),
('passerd.oauth',logging.DEBUG),
('passerd.feeds',logging.DEBUG),
('passerd.scheduler',logging.DEBUG)]
self.logformat = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
self.api_timeout = 60
self.daemon_mode = False
self.pidfile = None
def parse_cmdline(args, opts):
def parse_hostport(option, optstr, value, parser):
try:
host, rawport = value.rsplit(":", 1)
port = int(rawport)
except ValueError:
parser.error("invalid listen address, expected HOST:PORT")
opts.listen = (host, port)
def set_loglevels(levels):
opts.loglevels = levels
def open_logfile(option, optstr, value, parser):
opts.logstream = open(value, 'a')
parser = optparse.OptionParser("%prog [options] <database path>")
parser.add_option("-l", "--listen", type="string",
action="callback", callback=parse_hostport,
metavar="HOST:PORT", help="listen address")
parser.add_option("-D", "--debug",
action="callback", callback=lambda *args: set_loglevels([(None,logging.DEBUG)]),
help="Enable debug logging")
|
ehabkost/passerd
|
1c96f1f01a523b7d96354a127666292579031d22
|
implement "!RT" command
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index dbcde08..25e47a8 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -1,1634 +1,1713 @@
#!/usr/bin/env python
#
# Passerd - An IRC server as a gateway to Twitter
#
# Author: Eduardo Habkost <ehabkost@raisama.net>
#
# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys, logging, time, re, random
import gc
import optparse
import rfc822 # for date/time parsing
from twisted.words.protocols import irc
from twisted.words.protocols.irc import IRC
from twisted.internet.protocol import Factory
from twisted.internet import reactor, defer
import twisted.web.error
from twittytwister.twitter import Twitter, TwitterClientInfo
from passerd.data import DataStore, TwitterUserData
from passerd.callbacks import CallbackList
from passerd.utils import full_entity_decode
from passerd.feeds import HomeTimelineFeed, ListTimelineFeed, UserTimelineFeed, MentionsFeed, DirectMessagesFeed
from passerd.scheduler import ApiScheduler
from passerd import dialogs
from passerd.dialogs import Dialog, CommandDialog, CommandHelpMixin, attach_dialog_to_channel, attach_dialog_to_bot
from passerd.util import try_unicode, to_str
from passerd.irc import IrcUser, IrcChannel, IrcServer
from passerd.poauth import OAuthClient, oauth_consumer
import oauth.oauth as oauth
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from sqlalchemy.sql.expression import func
# client/user-agent info:
####
MYNAME = 'Passerd'
VERSION = '0.0.5'
MYAGENT = '%s/%s' % (MYNAME, VERSION)
#FIXME: use a real hostname?
MYHOST = 'passerd.server'
MYURL = 'http://passerd.raisama.net/'
CLIENT_INFO = TwitterClientInfo(MYNAME, VERSION, MYURL)
# IRC protocol stuff:
####
# the only mode supported, right now:
SUPPORTED_CHAN_MODES = 'b'
# No user mode is supported, by now:
SUPPORTED_USER_MODES = '0'
IRC_ENCODING = 'utf-8'
# Twitter protocol stuff:
####
BASE_URL = 'https://twitter.com'
TWITTER_ENCODING = 'utf-8'
LENGTH_LIMIT = 140
# Some limits:
####
# keep latest 100 post on each channel, to create in_reply_to field.
REPLY_HISTORY_SIZE = 100
# if more than MAX_USER_INFO_FETCH users are unknown, use /statuses/friends to fetch user info.
# otherwise, just fetch individual user info
MAX_USER_INFO_FETCH = 0 # individual fetch is not implemented yet...
# the maximum number of sequential friend list page requests:
MAX_FRIEND_PAGE_REQS = 10
+# minimum post age (in seconds) to allow it to be used for RTs.
+# useful to avoid surprises when using the !RT command
+#TODO: make this configurable
+MIN_LATEST_POST_AGE = 2
# IRC protocol constants:
####
# Other error codes we may use:
ERR_NEEDREGGEDNICK = '477'
# logging helpers:
####
logger = logging.getLogger("passerd")
dbg = logger.debug
pinfo = logger.info
perror = logger.error
class ErrorReply(Exception):
"""Special exception class used to generate IRC numeric replies"""
def __init__(self, command, *args):
self.command = command
self.args = args
class MissingOAuthRegistration(Exception):
pass
class MessageTooLong(Exception):
def __init__(self, text, length):
self.text = text
self.length = length
Exception.__init__(self, 'message too long (%d characters)' % (length))
class TwitterUserInfo:
"""Just carries simple data for a Twitter user
"""
def from_data(self, d):
self.screen_name = d.twitter_screen_name
self.name = d.twitter_name
return self
def to_data(self, d):
d.twitter_screen_name = self.screen_name
d.twitter_name = self.name
return self
def __repr__(self):
return 'TwitterUserInfo(%r, %r)' % (self.screen_name, self.name)
class TwitterUserCache:
"""Caches information about Twitter users
This is server-global, and is just an interface to the twitter_users database
table.
"""
def __init__(self, proto):
self.proto = proto
self.callbacks = CallbackList()
def addCallback(self, cb, *args, **kwargs):
"""Add a new callback function
Callback function is called with arguments: (twitter_user, old_info, new_info)
old_info may be None, if it's a new user
"""
self.callbacks.addCallback(cb, *args, **kwargs)
def _change_data(self, d, old_info, new_info):
# callbacks must becalled _before_ updating the data:
self.callbacks.callback(d.twitter_id, old_info, new_info)
new_info.to_data(d)
def _new_user(self, id, info):
d = TwitterUserData(twitter_id=id)
self._change_data(d, None, info)
#FIXME: encapsulate the following session operations, somehow:
self.proto.data.session.add(d)
self.proto.data.session.commit()
return d
def _update_user_info(self, id, new_info):
d = self.lookup_id(id)
if d is None:
return self._new_user(id, new_info)
old_info = TwitterUserInfo().from_data(d)
self._change_data(d, old_info, new_info)
#FIXME: encapsulate the following session operation, somehow:
self.proto.data.session.commit()
return d
def update_user_info(self, id, screen_name, name):
id = int(id)
i = TwitterUserInfo()
i.screen_name = screen_name
i.name = name
return self._update_user_info(id, i)
def got_api_user_info(self, u):
self.update_user_info(u.id, u.screen_name, u.name)
def lookup_id(self, id):
id = int(id)
#FIXME: encapsulate the following session operations, somehow:
d = self.proto.data.query(TwitterUserData).get(id)
if d is None:
return None
return d
def lookup_screen_name(self, name):
# not
try:
u = self.proto.data.query(TwitterUserData).filter(func.lower(TwitterUserData.twitter_screen_name)==name.lower()).one()
except MultipleResultsFound:
# multiple matches are possible if screen_names are reused.
# if that happens, be on the safe side: don't return anything
u = None
except NoResultFound:
u = None
return u
class TwitterIrcUser(IrcUser):
"""Common class for multiple methods of contacting IRC users"""
def _target_params(self, params):
"""Must return a dictionary containing user_id or screen_name, depending on
how much information we already have about the user.
"""
raise NotImplementedError("_target_params not implemented")
def send_direct_message(self, text):
d = defer.Deferred()
ok = []
def got_msg(msg):
ok.append(msg)
d.callback(msg)
def done(*args):
if not ok:
self.proto.notice("ERROR: Didn't get direct message info back when sending DM")
self.proto.api.send_direct_message(text, delegate=got_msg, params=self._target_params()).addCallbacks(done, d.errback)
return d
def messageReceived(self, sender, msg):
assert (sender is self.proto.the_user)
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
#TODO: maybe there's a better error code for this?
raise ErrorReply(irc.RPL_AWAY, self.nick, ':message too long (%d characters), not sent.' % (len(msg)))
def doit():
self.send_direct_message(msg).addCallbacks(done, error)
def done(msg):
self.proto.notice("Direct Message to %s sent. ID: %s" % (self.nick, msg.id))
def error(e):
self.proto.send_reply(irc.RPL_AWAY, self.nick, ":Error sending Direct Message: %s" % (e.value))
doit()
class UnavailableTwitterData:
"""Fake TwitterUserData object for unavailable info"""
def __init__(self, id):
self.twitter_id = id
twitter_screen_name = property(lambda self: 'user-id-%s' % (self.twitter_id))
twitter_name = property(lambda self: 'Twitter User (info not fetched yet)')
class CachedTwitterIrcUser(TwitterIrcUser):
"""An IrcUser object for cached Twitter user info
Objects of this class may be short-lived, just to return info of a random
Twitter user for which we don't have much data.
"""
def __init__(self, proto, cache, id):
IrcUser.__init__(self, proto)
self._twitter_id = id
self.cache = cache
self._data = None
def _target_params(self):
return {'user_id':self._twitter_id}
def data_changed(self, old_info, new_info):
dbg("CachedTwitterIrcUser.data_changed! %r %r" % (old_info, new_info))
if (old_info is None) or (old_info.screen_name != new_info.screen_name):
self.notifyNickChange(str(new_info.screen_name))
def __get_data(self):
if self._data is None:
self._data = self.cache.lookup_id(self._twitter_id)
return self._data
def _get_data(self):
d = self.__get_data()
if d is None:
return UnavailableTwitterData(self._twitter_id)
return d
def has_data(self):
"""Checks if the Twitter user info is known"""
return (self.__get_data() is not None)
data = property(_get_data)
nick = property(lambda self: str(self.data.twitter_screen_name))
username = property(lambda self: str(self.data.twitter_screen_name))
real_name = property(lambda self: self.data.twitter_name.encode('utf-8'))
hostname = property(lambda self: 'twitter.com')
class UnknownTwitterUser(TwitterIrcUser):
"""An IrcUser object for an user we don't know anything about, but may be a valid Twitter user"""
def __init__(self, proto, nickname):
self.proto = proto
self.nick = nickname
self.username = nickname
real_name = 'Unknown User'
hostname = 'twitter.com'
def _target_params(self):
return {'screen_name':self.nick}
class TwitterIrcUserCache:
"""Cache of CachedTwitterIrcUser objects
A TwitterIrcUserCache is client-specific (not server-global), and takes
care of creating CachedTwitterIrcUser objects for some queries.
"""
def __init__(self, proto, cache):
self.proto = proto
self.cache = cache
self.cache.addCallback(self._user_changed)
self._watched_ids = {}
def _user_changed(self, id, old_info, new_info):
dbg("user_changed: %r, %r, %r" % (id, old_info, new_info))
if id in self._watched_ids:
dbg("user_changed (%s): is being watched." % (id))
u = self._get_user(id).data_changed(old_info, new_info)
def _get_user(self, id):
u = CachedTwitterIrcUser(self.proto, self.cache, id)
return u
def watch_user_id(self, id):
"""Start watching user ID for changes"""
self._watched_ids[id] = True
def watch_user_ids(self, ids):
for id in ids:
self.watch_user_id(id)
def watch_user(self, u):
self.watch_user_id(u._twitter_id)
def get_user(self, id):
return self._get_user(id)
def fetch_individual_user_info(self, unknown_users):
#TODO: implement me
pass
def fetch_all_friend_info(self, user, unknown_users):
#TODO: unify this paging code with the one on FriendlistMixIn
reqs = []
def request_cursor(cursor):
self.proto.dbg("requesting a page from the friend list: %s" % (str(cursor)))
reqs.append(cursor)
self.proto.api.list_friends(got_user, user=user, params={'cursor':cursor},
page_delegate=end_page).addCallbacks(done, error)
def got_user(u):
self.proto.global_twuser_cache.got_api_user_info(u)
def end_page(next, prev):
unk = [u for u in unknown_users if not u.has_data()]
num = len(unk)
if num == 0:
self.proto.notice("I know all friends of %s, now!" % (user))
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addCallback(self.got_entry)
f.addErrback(self.refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
+ dbg("nickname %s not found", nick)
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
+ dbg("no posts by uid %s", uid)
return None
- r = recent[-1]
- if min_age:
- #FIXME: add date parsing support to twitty-twister
- #FIXME: show a list of alternatives to the user
- # (how to do that for replies?)
- t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
- if t > time.time() - min_age:
- raise Exception("latest post by %s is too recent" % (nick))
+
+ if substring:
+ matches = []
+ i = 1
+ while i <= len(recent):
+ r = recent[-i]
+ #TODO: make it more flexible, ignoring punctuation and spaces
+ if substring.lower() in r.text.lower():
+ matches.append(r)
+ i += 1
+
+ if not matches:
+ return None
+
+ if len(matches) > 1:
+ raise Exception("Multiple matches for [%s] on posts by %s" % (substring, nick))
+
+ # yay, single match:
+ r = matches[0]
+ else:
+ r = recent[-1]
+ if min_age:
+ #FIXME: add date parsing support to twitty-twister
+ #FIXME: show a list of alternatives to the user
+ # (how to do that for replies?)
+ t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
+ if t > time.time() - min_age:
+ raise Exception("latest post by %s is too recent, I don't know if it's the one you want. Use words from the text to identify it" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
dbg("#twitter got_entry. id: %s", e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("#twitter refresh error")
#FIXME: stop showing repeated errors and just let the user know when service is back
if e.check(twisted.web.error.Error):
if str(e.value.status) == '503':
self.bot_notice("Look! A flying whale! -- %s" % (e.value))
return
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.value.status == '400' and remaining == 0:
self.wait_rate_limit()
self.bot_notice("error refreshing feed: %s" % (e.value))
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You still can force the check by sending `!`. Also '
'you can check the rate limit by sending `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallback(done)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def _friendList(self, delegate, params={}, page_delegate=None):
#TODO: include the user on the list of channel members, too
# (the user whose timeline is being followed, not the Passerd
# authenticated user)
return self.proto.api.friends_ids(delegate, self.user, params=params,
page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
+ #TODO: add 'needs_chan' decorator
+
+ shorthelp_recent = "Test the recent-post matching code"
+ importance_gc = dialogs.CMD_IMP_DEBUGGING
+ def command_recent(self, args):
+ nick,substring = self.split_args(args)
+ try:
+ r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
+ except Exception,e:
+ self.message("error: %s" % (e))
+ return
+
+ if r:
+ self.message("match: id: %r. text: %r" % (r.id, r.text))
+ else:
+ self.message("no match...")
+
+ #TODO: add 'needs_chan' decorator
+ shorthelp_recent = "Retweet a post"
+ importance_gc = dialogs.CMD_IMP_COMMON
+ def help_rt(self, args):
+ self.cmd_syntax('rt', 'nick [part of post text]')
+ def command_rt(self, args):
+ if not self.chan:
+ self.message("The RT command only works in a channel")
+ return
+
+ nick,substring = self.split_args(args)
+ try:
+ r = self.chan.recent_post(nick, substring, MIN_LATEST_POST_AGE)
+ except Exception,e:
+ self.message("error: %s" % (e))
+ return
+
+ if not r:
+ if substring:
+ self.message("no match for [%s] on posts by %s" % (substring, nick))
+ else:
+ self.message("no posts from %s" % (nick))
+ return
+
+ data = []
+ def got_it(e):
+ r = e.retweeted_status
+ data.append(r)
+ self.message("Retweeted: <%s> %s" % (r.user.screen_name, r.text))
+ def done(*args):
+ if not data:
+ self.message("Unexpected error: no RT data returned by the Twitter server")
+
+ def error(e):
+ self.message("Error while retweeting: %s" % (e.value))
+ self.proto.api.retweet(str(r.id), got_it).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
#FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(*params, prefix=sender.full_id())
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
|
ehabkost/passerd
|
5f64e38796ac6ab4323eefd8956ef0a579648208
|
make lookup_screen_name() case-insensitive
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 5f21a92..dbcde08 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -1,738 +1,738 @@
#!/usr/bin/env python
#
# Passerd - An IRC server as a gateway to Twitter
#
# Author: Eduardo Habkost <ehabkost@raisama.net>
#
# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys, logging, time, re, random
import gc
import optparse
import rfc822 # for date/time parsing
from twisted.words.protocols import irc
from twisted.words.protocols.irc import IRC
from twisted.internet.protocol import Factory
from twisted.internet import reactor, defer
import twisted.web.error
from twittytwister.twitter import Twitter, TwitterClientInfo
from passerd.data import DataStore, TwitterUserData
from passerd.callbacks import CallbackList
from passerd.utils import full_entity_decode
from passerd.feeds import HomeTimelineFeed, ListTimelineFeed, UserTimelineFeed, MentionsFeed, DirectMessagesFeed
from passerd.scheduler import ApiScheduler
from passerd import dialogs
from passerd.dialogs import Dialog, CommandDialog, CommandHelpMixin, attach_dialog_to_channel, attach_dialog_to_bot
from passerd.util import try_unicode, to_str
from passerd.irc import IrcUser, IrcChannel, IrcServer
from passerd.poauth import OAuthClient, oauth_consumer
import oauth.oauth as oauth
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
-
+from sqlalchemy.sql.expression import func
# client/user-agent info:
####
MYNAME = 'Passerd'
VERSION = '0.0.5'
MYAGENT = '%s/%s' % (MYNAME, VERSION)
#FIXME: use a real hostname?
MYHOST = 'passerd.server'
MYURL = 'http://passerd.raisama.net/'
CLIENT_INFO = TwitterClientInfo(MYNAME, VERSION, MYURL)
# IRC protocol stuff:
####
# the only mode supported, right now:
SUPPORTED_CHAN_MODES = 'b'
# No user mode is supported, by now:
SUPPORTED_USER_MODES = '0'
IRC_ENCODING = 'utf-8'
# Twitter protocol stuff:
####
BASE_URL = 'https://twitter.com'
TWITTER_ENCODING = 'utf-8'
LENGTH_LIMIT = 140
# Some limits:
####
# keep latest 100 post on each channel, to create in_reply_to field.
REPLY_HISTORY_SIZE = 100
# if more than MAX_USER_INFO_FETCH users are unknown, use /statuses/friends to fetch user info.
# otherwise, just fetch individual user info
MAX_USER_INFO_FETCH = 0 # individual fetch is not implemented yet...
# the maximum number of sequential friend list page requests:
MAX_FRIEND_PAGE_REQS = 10
# IRC protocol constants:
####
# Other error codes we may use:
ERR_NEEDREGGEDNICK = '477'
# logging helpers:
####
logger = logging.getLogger("passerd")
dbg = logger.debug
pinfo = logger.info
perror = logger.error
class ErrorReply(Exception):
"""Special exception class used to generate IRC numeric replies"""
def __init__(self, command, *args):
self.command = command
self.args = args
class MissingOAuthRegistration(Exception):
pass
class MessageTooLong(Exception):
def __init__(self, text, length):
self.text = text
self.length = length
Exception.__init__(self, 'message too long (%d characters)' % (length))
class TwitterUserInfo:
"""Just carries simple data for a Twitter user
"""
def from_data(self, d):
self.screen_name = d.twitter_screen_name
self.name = d.twitter_name
return self
def to_data(self, d):
d.twitter_screen_name = self.screen_name
d.twitter_name = self.name
return self
def __repr__(self):
return 'TwitterUserInfo(%r, %r)' % (self.screen_name, self.name)
class TwitterUserCache:
"""Caches information about Twitter users
This is server-global, and is just an interface to the twitter_users database
table.
"""
def __init__(self, proto):
self.proto = proto
self.callbacks = CallbackList()
def addCallback(self, cb, *args, **kwargs):
"""Add a new callback function
Callback function is called with arguments: (twitter_user, old_info, new_info)
old_info may be None, if it's a new user
"""
self.callbacks.addCallback(cb, *args, **kwargs)
def _change_data(self, d, old_info, new_info):
# callbacks must becalled _before_ updating the data:
self.callbacks.callback(d.twitter_id, old_info, new_info)
new_info.to_data(d)
def _new_user(self, id, info):
d = TwitterUserData(twitter_id=id)
self._change_data(d, None, info)
#FIXME: encapsulate the following session operations, somehow:
self.proto.data.session.add(d)
self.proto.data.session.commit()
return d
def _update_user_info(self, id, new_info):
d = self.lookup_id(id)
if d is None:
return self._new_user(id, new_info)
old_info = TwitterUserInfo().from_data(d)
self._change_data(d, old_info, new_info)
#FIXME: encapsulate the following session operation, somehow:
self.proto.data.session.commit()
return d
def update_user_info(self, id, screen_name, name):
id = int(id)
i = TwitterUserInfo()
i.screen_name = screen_name
i.name = name
return self._update_user_info(id, i)
def got_api_user_info(self, u):
self.update_user_info(u.id, u.screen_name, u.name)
def lookup_id(self, id):
id = int(id)
#FIXME: encapsulate the following session operations, somehow:
d = self.proto.data.query(TwitterUserData).get(id)
if d is None:
return None
return d
def lookup_screen_name(self, name):
# not
try:
- u = self.proto.data.query(TwitterUserData).filter_by(twitter_screen_name=name).one()
+ u = self.proto.data.query(TwitterUserData).filter(func.lower(TwitterUserData.twitter_screen_name)==name.lower()).one()
except MultipleResultsFound:
# multiple matches are possible if screen_names are reused.
# if that happens, be on the safe side: don't return anything
u = None
except NoResultFound:
u = None
return u
class TwitterIrcUser(IrcUser):
"""Common class for multiple methods of contacting IRC users"""
def _target_params(self, params):
"""Must return a dictionary containing user_id or screen_name, depending on
how much information we already have about the user.
"""
raise NotImplementedError("_target_params not implemented")
def send_direct_message(self, text):
d = defer.Deferred()
ok = []
def got_msg(msg):
ok.append(msg)
d.callback(msg)
def done(*args):
if not ok:
self.proto.notice("ERROR: Didn't get direct message info back when sending DM")
self.proto.api.send_direct_message(text, delegate=got_msg, params=self._target_params()).addCallbacks(done, d.errback)
return d
def messageReceived(self, sender, msg):
assert (sender is self.proto.the_user)
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
#TODO: maybe there's a better error code for this?
raise ErrorReply(irc.RPL_AWAY, self.nick, ':message too long (%d characters), not sent.' % (len(msg)))
def doit():
self.send_direct_message(msg).addCallbacks(done, error)
def done(msg):
self.proto.notice("Direct Message to %s sent. ID: %s" % (self.nick, msg.id))
def error(e):
self.proto.send_reply(irc.RPL_AWAY, self.nick, ":Error sending Direct Message: %s" % (e.value))
doit()
class UnavailableTwitterData:
"""Fake TwitterUserData object for unavailable info"""
def __init__(self, id):
self.twitter_id = id
twitter_screen_name = property(lambda self: 'user-id-%s' % (self.twitter_id))
twitter_name = property(lambda self: 'Twitter User (info not fetched yet)')
class CachedTwitterIrcUser(TwitterIrcUser):
"""An IrcUser object for cached Twitter user info
Objects of this class may be short-lived, just to return info of a random
Twitter user for which we don't have much data.
"""
def __init__(self, proto, cache, id):
IrcUser.__init__(self, proto)
self._twitter_id = id
self.cache = cache
self._data = None
def _target_params(self):
return {'user_id':self._twitter_id}
def data_changed(self, old_info, new_info):
dbg("CachedTwitterIrcUser.data_changed! %r %r" % (old_info, new_info))
if (old_info is None) or (old_info.screen_name != new_info.screen_name):
self.notifyNickChange(str(new_info.screen_name))
def __get_data(self):
if self._data is None:
self._data = self.cache.lookup_id(self._twitter_id)
return self._data
def _get_data(self):
d = self.__get_data()
if d is None:
return UnavailableTwitterData(self._twitter_id)
return d
def has_data(self):
"""Checks if the Twitter user info is known"""
return (self.__get_data() is not None)
data = property(_get_data)
nick = property(lambda self: str(self.data.twitter_screen_name))
username = property(lambda self: str(self.data.twitter_screen_name))
real_name = property(lambda self: self.data.twitter_name.encode('utf-8'))
hostname = property(lambda self: 'twitter.com')
class UnknownTwitterUser(TwitterIrcUser):
"""An IrcUser object for an user we don't know anything about, but may be a valid Twitter user"""
def __init__(self, proto, nickname):
self.proto = proto
self.nick = nickname
self.username = nickname
real_name = 'Unknown User'
hostname = 'twitter.com'
def _target_params(self):
return {'screen_name':self.nick}
class TwitterIrcUserCache:
"""Cache of CachedTwitterIrcUser objects
A TwitterIrcUserCache is client-specific (not server-global), and takes
care of creating CachedTwitterIrcUser objects for some queries.
"""
def __init__(self, proto, cache):
self.proto = proto
self.cache = cache
self.cache.addCallback(self._user_changed)
self._watched_ids = {}
def _user_changed(self, id, old_info, new_info):
dbg("user_changed: %r, %r, %r" % (id, old_info, new_info))
if id in self._watched_ids:
dbg("user_changed (%s): is being watched." % (id))
u = self._get_user(id).data_changed(old_info, new_info)
def _get_user(self, id):
u = CachedTwitterIrcUser(self.proto, self.cache, id)
return u
def watch_user_id(self, id):
"""Start watching user ID for changes"""
self._watched_ids[id] = True
def watch_user_ids(self, ids):
for id in ids:
self.watch_user_id(id)
def watch_user(self, u):
self.watch_user_id(u._twitter_id)
def get_user(self, id):
return self._get_user(id)
def fetch_individual_user_info(self, unknown_users):
#TODO: implement me
pass
def fetch_all_friend_info(self, user, unknown_users):
#TODO: unify this paging code with the one on FriendlistMixIn
reqs = []
def request_cursor(cursor):
self.proto.dbg("requesting a page from the friend list: %s" % (str(cursor)))
reqs.append(cursor)
self.proto.api.list_friends(got_user, user=user, params={'cursor':cursor},
page_delegate=end_page).addCallbacks(done, error)
def got_user(u):
self.proto.global_twuser_cache.got_api_user_info(u)
def end_page(next, prev):
unk = [u for u in unknown_users if not u.has_data()]
num = len(unk)
if num == 0:
self.proto.notice("I know all friends of %s, now!" % (user))
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addCallback(self.got_entry)
f.addErrback(self.refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
return None
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
dbg("#twitter got_entry. id: %s", e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("#twitter refresh error")
#FIXME: stop showing repeated errors and just let the user know when service is back
if e.check(twisted.web.error.Error):
if str(e.value.status) == '503':
self.bot_notice("Look! A flying whale! -- %s" % (e.value))
return
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.value.status == '400' and remaining == 0:
self.wait_rate_limit()
self.bot_notice("error refreshing feed: %s" % (e.value))
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You still can force the check by sending `!`. Also '
'you can check the rate limit by sending `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallback(done)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
|
ehabkost/passerd
|
704121d657fd2eb6b573bb4f3ce7f4671e5575d9
|
add -p/--pid-file cmdline option
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 3846008..5f21a92 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -1500,595 +1500,607 @@ class PasserdProtocol(IRC):
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(*params, prefix=sender.full_id())
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(*args, timeout=self.factory.opts.api_timeout, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = MYAGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
channel = ListChannel(self, user, list_name)
if channel:
self.channels[name] = channel
return channel
def get_channel(self, name):
return self.channels.get(name)
def get_target(self, name):
if name.startswith('#'):
return self.get_channel(name)
else:
return self.get_user(name)
def mask_matches(self, mask):
#FIXME: match wildcards?
u = self.get_user(mask)
if u:
yield u
def who_matches(self, mask):
#TODO: make WHO list channel users
for u in self.mask_matches(mask):
#XXX: WTF do "H" and "G" mean?
yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
def whois_twitter_user(self, u, tu):
self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
#FIXME: find a better way to send user information, instead of RPL_AWAY
# - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
def oneline(s):
return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
def whois_mask(self, mask):
def doit():
self.dbg("fetching user info for %s" % (mask))
self.api.show_user(mask).addCallback(got_user).addErrback(error)
def got_user(tu):
self.dbg("got user info!")
self.global_twuser_cache.got_api_user_info(tu)
u = self.get_twitter_user(tu.id)
self.whois_twitter_user(u, tu)
def error(e):
self.send_reply(irc.ERR_NOSUCHNICK, mask, ':Error fetching user info - %s' % (e.value))
doit()
class PasserdFactory(Factory):
protocol = PasserdProtocol
def __init__(self, opts):
url = 'sqlite:///%s' % (opts.database)
self.opts = opts
self.data = DataStore(url)
self.data.create_tables()
self.global_twuser_cache = TwitterUserCache(self)
class PasserdGlobalOptions:
def __init__(self):
# set the defaults:
self.listen = ('0.0.0.0', 6667)
#logging:
self.logstream = sys.stderr
# list of (logger_name, level) pairs
# - sqlalchemy is too verbose on the INFO loglevel
# - enable oauth debugging, by now
self.loglevels = [(None, logging.INFO),
('sqlalchemy', logging.ERROR),
('passerd.oauth',logging.DEBUG),
('passerd.feeds',logging.DEBUG),
('passerd.scheduler',logging.DEBUG)]
self.logformat = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
self.api_timeout = 60
self.daemon_mode = False
+ self.pidfile = None
def parse_cmdline(args, opts):
def parse_hostport(option, optstr, value, parser):
try:
host, rawport = value.rsplit(":", 1)
port = int(rawport)
except ValueError:
parser.error("invalid listen address, expected HOST:PORT")
opts.listen = (host, port)
def set_loglevels(levels):
opts.loglevels = levels
def open_logfile(option, optstr, value, parser):
opts.logstream = open(value, 'a')
parser = optparse.OptionParser("%prog [options] <database path>")
parser.add_option("-l", "--listen", type="string",
action="callback", callback=parse_hostport,
metavar="HOST:PORT", help="listen address")
parser.add_option("-D", "--debug",
action="callback", callback=lambda *args: set_loglevels([(None,logging.DEBUG)]),
help="Enable debug logging")
parser.add_option("--logformat",
metavar="FORMAT", type="string", default=None,
help="Set the logging format")
parser.add_option("-d", "--daemon",
action="store_true", dest="daemon_mode")
parser.add_option("-L", "--log-file",
metavar="FILENAME", type="string",
action="callback", callback=open_logfile)
+ parser.add_option("-p", "--pid-file",
+ metavar="FILENAME", type="string",
+ dest="pidfile")
_, args = parser.parse_args(args, opts)
if not args:
parser.error("the database path is needed!")
opts.database = args[0]
return opts
def setup_logging(opts):
# root logger:
r = logging.getLogger()
if opts.logstream:
handler = logging.StreamHandler(opts.logstream)
f = logging.Formatter(opts.logformat)
handler.setFormatter(f)
r.addHandler(handler)
for name,level in opts.loglevels:
logging.getLogger(name).setLevel(level)
def _run(opts):
pinfo("Starting Passerd. Will listen on address %s:%d" % opts.listen)
reactor.listenTCP(interface=opts.listen[0], port=opts.listen[1],
factory=PasserdFactory(opts))
pinfo("Starting Twisted reactor loop")
reactor.run()
def run():
# be careful: avoid opening files before the _run() call. the
# daemon module will close it if you don't include it on files_preserve.
opts = PasserdGlobalOptions()
parse_cmdline(sys.argv[1:], opts)
setup_logging(opts)
preserve = []
if opts.logstream:
preserve.append(opts.logstream)
+ pidfile = None
+ if opts.pidfile:
+ try:
+ import lockfile
+ except ImportError:
+ raise Exception("You need the Python lockfile module, to set a pidfile")
+ pidfile = lockfile.FileLock(opts.pidfile)
+
if opts.daemon_mode:
try:
import daemon
except ImportError:
- raise Exception("You need the python-daemon module to run Passerd on daemon mode")
- with daemon.DaemonContext(files_preserve=preserve):
+ raise Exception("You need the python-daemon module, to run Passerd on daemon mode")
+ with daemon.DaemonContext(files_preserve=preserve, pidfile=pidfile):
try:
_run(opts)
except Exception,e:
logger.exception(e)
else:
_run(opts)
__all__ = ['run']
|
ehabkost/passerd
|
f326daba623064410719fe68684dfbf34c691969
|
doc updates
|
diff --git a/INSTALL.markdown b/INSTALL.markdown
index 68c47cf..37529b3 100644
--- a/INSTALL.markdown
+++ b/INSTALL.markdown
@@ -1,52 +1,63 @@
What do I need, to use Passerd?
-------------------------------
_Passerd_ is written in Python. You need Python (of course!), and the following
Python modules:
* twisted (and its 'twisted.words' module)
* sqlite
* sqlalchemy
* oauth
* A patched version of twitty-twister -- but don't worry: it is automatically fetched by `git submodule` and `./run.sh` (see run instructions below)
+Optional dependencies:
+
+* For running Passerd in _daemon_ mode:
+ * [python-daemon](http://pypi.python.org/pypi/python-daemon/)
+ * Python [lockfile](http://pypi.python.org/pypi/lockfile/) module
+
+
Below you'll find instructions to easily get the dependencies on some operating
systems:
### On Fedora
To install the dependencies on a Fedora machine, run:
yum install python-twisted python-twisted-words python-sqlalchemy python-oauth
+For the optional packages:
+
+ yum install python-daemon python-lockfile
+
### On Mandriva
These dependencies currently match the 2010.0 release but should be ok for others:
urpmi python-twisted-words python-sqlite python-sqlalchemy python-oauth
How do I run it?
----------------
Right now the recommended way to run Passerd is to check out the source
directly from the git repository.
### From the git repository:
* Check out the [git repository][gitrepo]
* `git clone git://github.com/ehabkost/passerd.git`
* `cd passerd`
* Run `git submodule init`
* Run `git submodule update`
* Run `./run.sh`
* Point your IRC client to server `localhost`, port `6667`
* Join the `#new-user-setup` channel on the server
* Follow the instructions from `passerd-bot`
* Have fun!
See the `USERGUIDE` file for more information.
[gitrepo]: http://github.com/ehabkost/passerd
diff --git a/NEWS.markdown b/NEWS.markdown
index b1e395a..5823d95 100644
--- a/NEWS.markdown
+++ b/NEWS.markdown
@@ -1,80 +1,71 @@
### Current development version:
-* Add a simple scheduling algorithm that will make sure Passerd don't
- kill the Twitter API rate-limit if the user joins too many Passerd
- channels.
-
- With this in place, Passerd will never make more than 80 requests per hour,
- even if many feeds are being followed at the same time (not taking the
- channel-join-time and login-time requests into account, though).
-
+* Add a simple scheduling algorithm that will make sure Passerd don't kill the
+ Twitter API rate-limit if the user joins too many Passerd channels.
* Fix auto-`@` of nickname replies when nicknames have digits on it
-
* Set timeout on API calls to avoid getting stuck if HTTP requests take too
long to reply
-
* Retweets are shown as messages from the original poster, with a note
by passerd-bot
(configurable by "!be concise" option)
-
* Multi-line tweets aren't shown as multiple lines anymore
(configurable by "!be verbose" option)
-
* Lower-level "!config" command to set specific configuration variables
+* Support for running Passerd in _daemon_ mode
### Passerd 0.0.5 - 6 Jan 2010
* Don't continue refreshing feeds if rate-limit is hit. This is a temporary
solution until a true rate-limit-adjusting scheduler is written
* Unify `passerd-bot` commands and implementation of `!command` on `#twitter`
* Including a help system
* Add a `!post` command (aliases: `!tw`, `!twit`, `!update`)
* Paranoid mode: if you are afraid of posting by mistake when typing on
your IRC client, you can enable a "paranoid" mode using the `!be paranoid`
command.
When in this mode, you can only post to twitter using `!post` (or the aliases
above)
### Passerd 0.0.4.2 - 28 Dec 2009
* Updated twitty-twister version. On 0.0.4, I forgot to update the
twitty-twister git commit reference, and broke twitter posting.
### Passerd 0.0.4.1 - 28 Dec 2009
* Fix a problem on the OAuth access token request method. A POST
request with no Content-Length may case a 411 Length Required
error (probably on some proxy servers).
* Thanks to Bogdano Arendartchuk for the fix.
### Passerd 0.0.4 - 27 Dec 2009
* Ability to follow lists using `#@username/list` channels
* Ability to get updates from a single user using `#@username` channels
* Implement #mentions channel, for mentions of `@username`
* OAuth support! Now you don't need to give your Twitter password to
Passerd (and you'll get a nice "from Passerd" note on your Twits. :)
* Optional nickserv-style authentication support
* Better error messages (using a `passerd-bot` IRC user)
* Now with a real (but still a bit ugly) web page at [passerd.raisama.net](http://passerd.raisama.net/)
### Passerd 0.0.3 - 18 Dec 2009
* Ability to send updates to Twitter
* Fetch detailed user info from Twitter on-demand, only if necessary
* Basic command-line option support
* Implement Twitter follow/unfollow as IRCK KICK/INVITE
### Passerd 0.0.2 - 15 Dec 2009
* List Twitter friends as IRC contacts
### Passerd 0.0.1 - 14 Dec 2009
* Basic Twitter reading ability
|
ehabkost/passerd
|
eb4c579e367f0a3c094871e3ee17ebcf348f55e4
|
add -d (daemon mode) and -L (log file) command-line options
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index faff19b..3846008 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -1499,566 +1499,596 @@ class PasserdProtocol(IRC):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(*params, prefix=sender.full_id())
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(*args, timeout=self.factory.opts.api_timeout, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = MYAGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
channel = ListChannel(self, user, list_name)
if channel:
self.channels[name] = channel
return channel
def get_channel(self, name):
return self.channels.get(name)
def get_target(self, name):
if name.startswith('#'):
return self.get_channel(name)
else:
return self.get_user(name)
def mask_matches(self, mask):
#FIXME: match wildcards?
u = self.get_user(mask)
if u:
yield u
def who_matches(self, mask):
#TODO: make WHO list channel users
for u in self.mask_matches(mask):
#XXX: WTF do "H" and "G" mean?
yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
def whois_twitter_user(self, u, tu):
self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
#FIXME: find a better way to send user information, instead of RPL_AWAY
# - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
def oneline(s):
return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
def whois_mask(self, mask):
def doit():
self.dbg("fetching user info for %s" % (mask))
self.api.show_user(mask).addCallback(got_user).addErrback(error)
def got_user(tu):
self.dbg("got user info!")
self.global_twuser_cache.got_api_user_info(tu)
u = self.get_twitter_user(tu.id)
self.whois_twitter_user(u, tu)
def error(e):
self.send_reply(irc.ERR_NOSUCHNICK, mask, ':Error fetching user info - %s' % (e.value))
doit()
class PasserdFactory(Factory):
protocol = PasserdProtocol
def __init__(self, opts):
url = 'sqlite:///%s' % (opts.database)
self.opts = opts
self.data = DataStore(url)
self.data.create_tables()
self.global_twuser_cache = TwitterUserCache(self)
class PasserdGlobalOptions:
def __init__(self):
# set the defaults:
self.listen = ('0.0.0.0', 6667)
#logging:
self.logstream = sys.stderr
# list of (logger_name, level) pairs
# - sqlalchemy is too verbose on the INFO loglevel
# - enable oauth debugging, by now
self.loglevels = [(None, logging.INFO),
('sqlalchemy', logging.ERROR),
('passerd.oauth',logging.DEBUG),
('passerd.feeds',logging.DEBUG),
('passerd.scheduler',logging.DEBUG)]
self.logformat = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
self.api_timeout = 60
+ self.daemon_mode = False
+
def parse_cmdline(args, opts):
def parse_hostport(option, optstr, value, parser):
try:
host, rawport = value.rsplit(":", 1)
port = int(rawport)
except ValueError:
parser.error("invalid listen address, expected HOST:PORT")
opts.listen = (host, port)
def set_loglevels(levels):
opts.loglevels = levels
+ def open_logfile(option, optstr, value, parser):
+ opts.logstream = open(value, 'a')
+
parser = optparse.OptionParser("%prog [options] <database path>")
parser.add_option("-l", "--listen", type="string",
action="callback", callback=parse_hostport,
metavar="HOST:PORT", help="listen address")
parser.add_option("-D", "--debug",
action="callback", callback=lambda *args: set_loglevels([(None,logging.DEBUG)]),
help="Enable debug logging")
parser.add_option("--logformat",
metavar="FORMAT", type="string", default=None,
help="Set the logging format")
- _, args = parser.parse_args(args)
+ parser.add_option("-d", "--daemon",
+ action="store_true", dest="daemon_mode")
+ parser.add_option("-L", "--log-file",
+ metavar="FILENAME", type="string",
+ action="callback", callback=open_logfile)
+ _, args = parser.parse_args(args, opts)
if not args:
parser.error("the database path is needed!")
opts.database = args[0]
return opts
def setup_logging(opts):
- ch = logging.StreamHandler(opts.logstream)
- f = logging.Formatter(opts.logformat)
- ch.setFormatter(f)
-
# root logger:
r = logging.getLogger()
- r.addHandler(ch)
+
+ if opts.logstream:
+ handler = logging.StreamHandler(opts.logstream)
+ f = logging.Formatter(opts.logformat)
+ handler.setFormatter(f)
+ r.addHandler(handler)
for name,level in opts.loglevels:
logging.getLogger(name).setLevel(level)
+def _run(opts):
+ pinfo("Starting Passerd. Will listen on address %s:%d" % opts.listen)
+ reactor.listenTCP(interface=opts.listen[0], port=opts.listen[1],
+ factory=PasserdFactory(opts))
+ pinfo("Starting Twisted reactor loop")
+ reactor.run()
+
def run():
+ # be careful: avoid opening files before the _run() call. the
+ # daemon module will close it if you don't include it on files_preserve.
opts = PasserdGlobalOptions()
parse_cmdline(sys.argv[1:], opts)
setup_logging(opts)
+ preserve = []
+ if opts.logstream:
+ preserve.append(opts.logstream)
- pinfo("Starting Passerd. Will listen on address %s:%d" % opts.listen)
- reactor.listenTCP(interface=opts.listen[0], port=opts.listen[1],
- factory=PasserdFactory(opts))
- pinfo("Starting Twisted reactor loop.")
- reactor.run()
+ if opts.daemon_mode:
+ try:
+ import daemon
+ except ImportError:
+ raise Exception("You need the python-daemon module to run Passerd on daemon mode")
+ with daemon.DaemonContext(files_preserve=preserve):
+ try:
+ _run(opts)
+ except Exception,e:
+ logger.exception(e)
+ else:
+ _run(opts)
__all__ = ['run']
|
ehabkost/passerd
|
914aa90fed3206e667ae46d35046bb03ba805629
|
add FIXME note
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 6e33365..faff19b 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -704,1024 +704,1025 @@ class TwitterChannel(IrcChannel):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def _friendList(self, delegate, params={}, page_delegate=None):
#TODO: include the user on the list of channel members, too
# (the user whose timeline is being followed, not the Passerd
# authenticated user)
return self.proto.api.friends_ids(delegate, self.user, params=params,
page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
+ #FIXME: clear password field if Twitter password option is chosen
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(*params, prefix=sender.full_id())
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(*args, timeout=self.factory.opts.api_timeout, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = MYAGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
|
ehabkost/passerd
|
cd03db6deaab16c9a700bca4b59727f4ccb589f3
|
"on" is a valid value for boolean variables, too
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 4dc6ed4..6e33365 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -940,1025 +940,1025 @@ class ConfigInfo:
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
- true_values = ['true', 't', '1', 'y', 'yes']
+ true_values = ['true', 't', '1', 'y', 'yes', 'on']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(*params, prefix=sender.full_id())
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(*args, timeout=self.factory.opts.api_timeout, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = MYAGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
channel = ListChannel(self, user, list_name)
if channel:
self.channels[name] = channel
return channel
def get_channel(self, name):
return self.channels.get(name)
def get_target(self, name):
if name.startswith('#'):
return self.get_channel(name)
else:
return self.get_user(name)
def mask_matches(self, mask):
#FIXME: match wildcards?
u = self.get_user(mask)
if u:
yield u
def who_matches(self, mask):
#TODO: make WHO list channel users
for u in self.mask_matches(mask):
#XXX: WTF do "H" and "G" mean?
yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
def whois_twitter_user(self, u, tu):
self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
#FIXME: find a better way to send user information, instead of RPL_AWAY
# - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
def oneline(s):
return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
def whois_mask(self, mask):
def doit():
|
ehabkost/passerd
|
0ecd68a823504f56ce3cd2ea64e52804704f4d1e
|
Add multiline/RT formatting unit test
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index ae0619a..4dc6ed4 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -898,1025 +898,1025 @@ class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def topic(self):
return "User timeline -- %s" % (self.user)
def _friendList(self, delegate, params={}, page_delegate=None):
#TODO: include the user on the list of channel members, too
# (the user whose timeline is being followed, not the Passerd
# authenticated user)
return self.proto.api.friends_ids(delegate, self.user, params=params,
page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
def show_all(self):
self.message('%-10s %s' % ('Option', 'Value'))
for o in ConfigInfo.all_opts():
v = self.proto.user_cfg_var(o)
if v is None:
v = '-'
self.message(u'%-10s %s' % (o, v))
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
- lines.append(line.encode(IRC_ENCODING))
+ lines.append(line)
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(*params, prefix=sender.full_id())
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(*args, timeout=self.factory.opts.api_timeout, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = MYAGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
diff --git a/passerd/tests/__init__.py b/passerd/tests/__init__.py
index 4be696b..2b37caf 100644
--- a/passerd/tests/__init__.py
+++ b/passerd/tests/__init__.py
@@ -1,22 +1,22 @@
import unittest, doctest
-modules = 'dialogs'.split()
+modules = 'dialogs formatting'.split()
docmodules = []
def suite():
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for n in modules:
passerd = __import__('passerd.tests.%s' % (n))
module = getattr(passerd.tests, n)
tests = loader.loadTestsFromModule(module)
suite.addTests(tests)
for dm in docmodules:
suite.addTest(doctest.DocTestSuite(dm))
return suite
if __name__ == '__main__':
unittest.TextTestRunner().run(suite())
diff --git a/passerd/tests/formatting.py b/passerd/tests/formatting.py
new file mode 100644
index 0000000..e631cf7
--- /dev/null
+++ b/passerd/tests/formatting.py
@@ -0,0 +1,86 @@
+# -*- coding: utf-8 -*-
+
+import unittest
+
+from passerd import ircd
+
+
+class FakeProto(ircd.PasserdProtocol):
+ """Fake PasserdProtocol object"""
+ def __init__(self):
+ self.user_cfg_vars = {}
+ self.privmsg_log = []
+ self.fake_users = {}
+ self.passerd_bot = 'this_is_passerd-bot'
+
+ def user_cfg_var_b(self, var):
+ return self.user_cfg_vars.get(var, False)
+
+ def get_twitter_user(self, twid):
+ return self.fake_users[twid]
+
+ def send_privmsg(self, sender, target, msg):
+ self.privmsg_log.append( (sender, target, msg) )
+
+class FakeChannel(ircd.TwitterChannel):
+ def __init__(self, proto):
+ self.proto = proto
+
+
+class O:
+ """Automatic kwargs->attributes object"""
+ def __init__(self, **kwargs):
+ self.__dict__.update(kwargs)
+
+
+class TestMsgFormatting(unittest.TestCase):
+ def setUp(self):
+ self.proto = FakeProto()
+ self.chan = FakeChannel(self.proto)
+
+ def testNoMultiOneLine(self):
+ self.proto.user_cfg_vars['multiline'] = False
+ t = u'aeióú'
+ self.proto.send_text('s', 't', t)
+ self.assertEquals(self.proto.privmsg_log, [('s','t', t)])
+
+ def testMultiOneLine(self):
+ self.proto.user_cfg_vars['multiline'] = True
+ t = u'aeióú2'
+ self.proto.send_text('s', 't', t)
+ self.assertEquals(self.proto.privmsg_log, [('s','t', t)])
+
+ def testNoMultiManyLines(self):
+ self.proto.user_cfg_vars['multiline'] = False
+ t = u'aei óú\nfoo barÃ\nüber yeah!'
+ self.proto.send_text('s', 't', t)
+ self.assertEquals(self.proto.privmsg_log, [('s','t', u'aei óú foo barà über yeah!')])
+
+ def testMultiManyLines(self):
+ self.proto.user_cfg_vars['multiline'] = True
+ t = u'aei óú\nfoo barÃ\nüber yeah!'
+ self.proto.send_text('s', 't', t)
+ self.assertEquals(self.proto.privmsg_log, [('s','t', u'aei óú'),('s','t',u'[...] foo barÃ'),('s','t',u'[...] über yeah!')])
+
+ def sendAliceBobRT(self):
+ self.alice_u = self.proto.fake_users[1] = 'this_is_alice'
+
+ alice = O(screen_name='alice', id=1)
+ bob = O(screen_name='bob', id=2)
+ orig = O(id=123, text=u'this is über cool!', user=alice)
+ rt = O(id=456, text=u'RT @alice: this is über cool ...', user=bob, retweeted_status=orig)
+
+ self.chan.printEntry(rt)
+
+ def testRtNoInline(self):
+ self.proto.user_cfg_vars['rt_inline'] = False
+ self.sendAliceBobRT()
+ self.assertEquals(self.proto.privmsg_log,
+ [(self.alice_u, self.chan, u'this is über cool!'),
+ (self.proto.passerd_bot, self.chan, '(alice retweeted by bob)')])
+
+ def testRtNoInline(self):
+ self.proto.user_cfg_vars['rt_inline'] = True
+ self.sendAliceBobRT()
+ self.assertEquals(self.proto.privmsg_log,
+ [(self.alice_u, self.chan, u'this is über cool! \x02[RT by @bob]\x02')])
|
ehabkost/passerd
|
e60a742bb7953019c38351fb102b795aff3f3a60
|
config: kill 'list' command
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 3dd1ca0..ae0619a 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -446,1049 +446,1048 @@ class TwitterIrcUserCache:
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addCallback(self.got_entry)
f.addErrback(self.refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
return None
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
dbg("#twitter got_entry. id: %s", e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("#twitter refresh error")
#FIXME: stop showing repeated errors and just let the user know when service is back
if e.check(twisted.web.error.Error):
if str(e.value.status) == '503':
self.bot_notice("Look! A flying whale! -- %s" % (e.value))
return
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.value.status == '400' and remaining == 0:
self.wait_rate_limit()
self.bot_notice("error refreshing feed: %s" % (e.value))
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You still can force the check by sending `!`. Also '
'you can check the rate limit by sending `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallback(done)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def _friendList(self, delegate, params={}, page_delegate=None):
#TODO: include the user on the list of channel members, too
# (the user whose timeline is being followed, not the Passerd
# authenticated user)
return self.proto.api.friends_ids(delegate, self.user, params=params,
page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigInfo:
"""Just a namespace for definitions of configuration options
"""
OPTIONS = set('rt_inline multiline careful'.split())
help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
help_multiline = 'Show multi-line posts as multiple IRC messages'
help_careful = "Don't post non-command channel messages to Twitter directly"
@classmethod
def all_opts(klass):
return list(klass.OPTIONS)
@classmethod
def has_opt(klass, o):
return o in klass.OPTIONS
@classmethod
def opt_help(klass, o):
return getattr(klass, 'help_%s' % (o), None)
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def help_set(self, args):
self.cmd_syntax('set', 'option value')
def command_set(self, args):
opt,value = self.split_args(args)
if not value:
self.help_set(None)
return
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
self.proto.set_user_cfg_var(opt, value)
self.message(u'Option %s set to: %s' % (opt, value))
+ def show_all(self):
+ self.message('%-10s %s' % ('Option', 'Value'))
+ for o in ConfigInfo.all_opts():
+ v = self.proto.user_cfg_var(o)
+ if v is None:
+ v = '-'
+ self.message(u'%-10s %s' % (o, v))
+
shorthelp_show = 'Show the value of a config option'
def command_show(self, args):
if not args:
- return self.command_list(args)
+ return self.show_all()
opt = args
if not ConfigInfo.has_opt(opt):
self.message("Invalid option name: %r" % (opt))
return
value = self.proto.user_cfg_var(opt)
if value is None:
self.message(u'Option %s is unset' % (opt))
else:
self.message(u'Option %s is set to: %s' % (opt, value))
- shorthelp_list = 'List all configuration variables'
- def command_list(self, args):
- self.message('%-10s %s' % ('Option', 'Value'))
- for o in ConfigInfo.all_opts():
- v = self.proto.user_cfg_var(o)
- if v is None:
- v = '-'
- self.message(u'%-10s %s' % (o, v))
-
def show_help(self, prefix, args):
CommandDialog.show_help(self, prefix, args)
self.message('%-10s %s' % ('Option', 'Description'))
for o in ConfigInfo.all_opts():
self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line.encode(IRC_ENCODING))
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
|
ehabkost/passerd
|
0655e889a8971af7209c5f48974c8158c0709e00
|
implement stupid low-level config-variable setting interface
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index fc7cf44..3dd1ca0 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -406,1080 +406,1146 @@ class TwitterIrcUserCache:
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addCallback(self.got_entry)
f.addErrback(self.refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
if is_rt:
rt_inline = self.proto.user_cfg_var_b('rt_inline')
if rt_inline:
#TODO: make RT inline format configurable
text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
self.proto.send_text(u, self, text)
if is_rt:
if not rt_inline:
self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
return None
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
dbg("#twitter got_entry. id: %s", e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("#twitter refresh error")
#FIXME: stop showing repeated errors and just let the user know when service is back
if e.check(twisted.web.error.Error):
if str(e.value.status) == '503':
self.bot_notice("Look! A flying whale! -- %s" % (e.value))
return
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.value.status == '400' and remaining == 0:
self.wait_rate_limit()
self.bot_notice("error refreshing feed: %s" % (e.value))
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You still can force the check by sending `!`. Also '
'you can check the rate limit by sending `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallback(done)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def _friendList(self, delegate, params={}, page_delegate=None):
#TODO: include the user on the list of channel members, too
# (the user whose timeline is being followed, not the Passerd
# authenticated user)
return self.proto.api.friends_ids(delegate, self.user, params=params,
page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
+class ConfigInfo:
+ """Just a namespace for definitions of configuration options
+ """
+ OPTIONS = set('rt_inline multiline careful'.split())
+
+ help_rt_inline = 'Show inline "[RT by @user]" info on Retweets'
+ help_multiline = 'Show multi-line posts as multiple IRC messages'
+ help_careful = "Don't post non-command channel messages to Twitter directly"
+
+ @classmethod
+ def all_opts(klass):
+ return list(klass.OPTIONS)
+
+ @classmethod
+ def has_opt(klass, o):
+ return o in klass.OPTIONS
+
+ @classmethod
+ def opt_help(klass, o):
+ return getattr(klass, 'help_%s' % (o), None)
+
+
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
+ def help_set(self, args):
+ self.cmd_syntax('set', 'option value')
def command_set(self, args):
- #FIXME: implement me
- self.message('Sorry, this is not implemented yet')
+ opt,value = self.split_args(args)
+ if not value:
+ self.help_set(None)
+ return
+
+ if not ConfigInfo.has_opt(opt):
+ self.message("Invalid option name: %r" % (opt))
+ return
+
+
+ self.proto.set_user_cfg_var(opt, value)
+ self.message(u'Option %s set to: %s' % (opt, value))
+
+ shorthelp_show = 'Show the value of a config option'
+ def command_show(self, args):
+ if not args:
+ return self.command_list(args)
+
+ opt = args
+ if not ConfigInfo.has_opt(opt):
+ self.message("Invalid option name: %r" % (opt))
+ return
+
+ value = self.proto.user_cfg_var(opt)
+ if value is None:
+ self.message(u'Option %s is unset' % (opt))
+ else:
+ self.message(u'Option %s is set to: %s' % (opt, value))
+
+ shorthelp_list = 'List all configuration variables'
+ def command_list(self, args):
+ self.message('%-10s %s' % ('Option', 'Value'))
+ for o in ConfigInfo.all_opts():
+ v = self.proto.user_cfg_var(o)
+ if v is None:
+ v = '-'
+ self.message(u'%-10s %s' % (o, v))
+
+ def show_help(self, prefix, args):
+ CommandDialog.show_help(self, prefix, args)
+ self.message('%-10s %s' % ('Option', 'Description'))
+ for o in ConfigInfo.all_opts():
+ self.message('%-10s %s' % (o, ConfigInfo.opt_help(o)))
+
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
shorthelp_concise = "Show every post as a single IRC message"
def command_concise(self, args):
self.message("OK. I know I talk too much")
self.proto.set_user_cfg_var('rt_inline', True)
self.proto.set_user_cfg_var('multiline', False)
shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
def command_verbose(self, args):
self.message("Thanks. I like to talk, you know :)")
self.proto.set_user_cfg_var('rt_inline', False)
self.proto.set_user_cfg_var('multiline', True)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
- #self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
+ self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
lines = []
if self.user_cfg_var_b('multiline'):
first = True
# handle newlines as multiple messages
for line in text.split('\n'):
if not line:
continue
if not first:
#TODO: find a better way to indicate multi-line posts
line = '[...] '+line
lines.append(line.encode(IRC_ENCODING))
first = False
else:
lines = [text.replace('\n', ' ')]
for l in lines:
self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
def user_cfg_var(self, var):
vname = 'config:%s' % (var)
return self.user_var(vname)
def user_cfg_var_b(self, var):
v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(*params, prefix=sender.full_id())
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
|
ehabkost/passerd
|
7d41032fcc832389a0f533e496455f1ce32c5cbc
|
add "!be concise" and "!be verbose" commands
|
diff --git a/passerd/ircd.py b/passerd/ircd.py
index 6c22e9e..fc7cf44 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -1,1868 +1,1898 @@
#!/usr/bin/env python
#
# Passerd - An IRC server as a gateway to Twitter
#
# Author: Eduardo Habkost <ehabkost@raisama.net>
#
# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys, logging, time, re, random
import gc
import optparse
import rfc822 # for date/time parsing
from twisted.words.protocols import irc
from twisted.words.protocols.irc import IRC
from twisted.internet.protocol import Factory
from twisted.internet import reactor, defer
import twisted.web.error
from twittytwister.twitter import Twitter, TwitterClientInfo
from passerd.data import DataStore, TwitterUserData
from passerd.callbacks import CallbackList
from passerd.utils import full_entity_decode
from passerd.feeds import HomeTimelineFeed, ListTimelineFeed, UserTimelineFeed, MentionsFeed, DirectMessagesFeed
from passerd.scheduler import ApiScheduler
from passerd import dialogs
from passerd.dialogs import Dialog, CommandDialog, CommandHelpMixin, attach_dialog_to_channel, attach_dialog_to_bot
from passerd.util import try_unicode, to_str
from passerd.irc import IrcUser, IrcChannel, IrcServer
from passerd.poauth import OAuthClient, oauth_consumer
import oauth.oauth as oauth
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
# client/user-agent info:
####
MYNAME = 'Passerd'
VERSION = '0.0.5'
MYAGENT = '%s/%s' % (MYNAME, VERSION)
#FIXME: use a real hostname?
MYHOST = 'passerd.server'
MYURL = 'http://passerd.raisama.net/'
CLIENT_INFO = TwitterClientInfo(MYNAME, VERSION, MYURL)
# IRC protocol stuff:
####
# the only mode supported, right now:
SUPPORTED_CHAN_MODES = 'b'
# No user mode is supported, by now:
SUPPORTED_USER_MODES = '0'
IRC_ENCODING = 'utf-8'
# Twitter protocol stuff:
####
BASE_URL = 'https://twitter.com'
TWITTER_ENCODING = 'utf-8'
LENGTH_LIMIT = 140
# Some limits:
####
# keep latest 100 post on each channel, to create in_reply_to field.
REPLY_HISTORY_SIZE = 100
# if more than MAX_USER_INFO_FETCH users are unknown, use /statuses/friends to fetch user info.
# otherwise, just fetch individual user info
MAX_USER_INFO_FETCH = 0 # individual fetch is not implemented yet...
# the maximum number of sequential friend list page requests:
MAX_FRIEND_PAGE_REQS = 10
# IRC protocol constants:
####
# Other error codes we may use:
ERR_NEEDREGGEDNICK = '477'
# logging helpers:
####
logger = logging.getLogger("passerd")
dbg = logger.debug
pinfo = logger.info
perror = logger.error
class ErrorReply(Exception):
"""Special exception class used to generate IRC numeric replies"""
def __init__(self, command, *args):
self.command = command
self.args = args
class MissingOAuthRegistration(Exception):
pass
class MessageTooLong(Exception):
def __init__(self, text, length):
self.text = text
self.length = length
Exception.__init__(self, 'message too long (%d characters)' % (length))
class TwitterUserInfo:
"""Just carries simple data for a Twitter user
"""
def from_data(self, d):
self.screen_name = d.twitter_screen_name
self.name = d.twitter_name
return self
def to_data(self, d):
d.twitter_screen_name = self.screen_name
d.twitter_name = self.name
return self
def __repr__(self):
return 'TwitterUserInfo(%r, %r)' % (self.screen_name, self.name)
class TwitterUserCache:
"""Caches information about Twitter users
This is server-global, and is just an interface to the twitter_users database
table.
"""
def __init__(self, proto):
self.proto = proto
self.callbacks = CallbackList()
def addCallback(self, cb, *args, **kwargs):
"""Add a new callback function
Callback function is called with arguments: (twitter_user, old_info, new_info)
old_info may be None, if it's a new user
"""
self.callbacks.addCallback(cb, *args, **kwargs)
def _change_data(self, d, old_info, new_info):
# callbacks must becalled _before_ updating the data:
self.callbacks.callback(d.twitter_id, old_info, new_info)
new_info.to_data(d)
def _new_user(self, id, info):
d = TwitterUserData(twitter_id=id)
self._change_data(d, None, info)
#FIXME: encapsulate the following session operations, somehow:
self.proto.data.session.add(d)
self.proto.data.session.commit()
return d
def _update_user_info(self, id, new_info):
d = self.lookup_id(id)
if d is None:
return self._new_user(id, new_info)
old_info = TwitterUserInfo().from_data(d)
self._change_data(d, old_info, new_info)
#FIXME: encapsulate the following session operation, somehow:
self.proto.data.session.commit()
return d
def update_user_info(self, id, screen_name, name):
id = int(id)
i = TwitterUserInfo()
i.screen_name = screen_name
i.name = name
return self._update_user_info(id, i)
def got_api_user_info(self, u):
self.update_user_info(u.id, u.screen_name, u.name)
def lookup_id(self, id):
id = int(id)
#FIXME: encapsulate the following session operations, somehow:
d = self.proto.data.query(TwitterUserData).get(id)
if d is None:
return None
return d
def lookup_screen_name(self, name):
# not
try:
u = self.proto.data.query(TwitterUserData).filter_by(twitter_screen_name=name).one()
except MultipleResultsFound:
# multiple matches are possible if screen_names are reused.
# if that happens, be on the safe side: don't return anything
u = None
except NoResultFound:
u = None
return u
class TwitterIrcUser(IrcUser):
"""Common class for multiple methods of contacting IRC users"""
def _target_params(self, params):
"""Must return a dictionary containing user_id or screen_name, depending on
how much information we already have about the user.
"""
raise NotImplementedError("_target_params not implemented")
def send_direct_message(self, text):
d = defer.Deferred()
ok = []
def got_msg(msg):
ok.append(msg)
d.callback(msg)
def done(*args):
if not ok:
self.proto.notice("ERROR: Didn't get direct message info back when sending DM")
self.proto.api.send_direct_message(text, delegate=got_msg, params=self._target_params()).addCallbacks(done, d.errback)
return d
def messageReceived(self, sender, msg):
assert (sender is self.proto.the_user)
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
#TODO: maybe there's a better error code for this?
raise ErrorReply(irc.RPL_AWAY, self.nick, ':message too long (%d characters), not sent.' % (len(msg)))
def doit():
self.send_direct_message(msg).addCallbacks(done, error)
def done(msg):
self.proto.notice("Direct Message to %s sent. ID: %s" % (self.nick, msg.id))
def error(e):
self.proto.send_reply(irc.RPL_AWAY, self.nick, ":Error sending Direct Message: %s" % (e.value))
doit()
class UnavailableTwitterData:
"""Fake TwitterUserData object for unavailable info"""
def __init__(self, id):
self.twitter_id = id
twitter_screen_name = property(lambda self: 'user-id-%s' % (self.twitter_id))
twitter_name = property(lambda self: 'Twitter User (info not fetched yet)')
class CachedTwitterIrcUser(TwitterIrcUser):
"""An IrcUser object for cached Twitter user info
Objects of this class may be short-lived, just to return info of a random
Twitter user for which we don't have much data.
"""
def __init__(self, proto, cache, id):
IrcUser.__init__(self, proto)
self._twitter_id = id
self.cache = cache
self._data = None
def _target_params(self):
return {'user_id':self._twitter_id}
def data_changed(self, old_info, new_info):
dbg("CachedTwitterIrcUser.data_changed! %r %r" % (old_info, new_info))
if (old_info is None) or (old_info.screen_name != new_info.screen_name):
self.notifyNickChange(str(new_info.screen_name))
def __get_data(self):
if self._data is None:
self._data = self.cache.lookup_id(self._twitter_id)
return self._data
def _get_data(self):
d = self.__get_data()
if d is None:
return UnavailableTwitterData(self._twitter_id)
return d
def has_data(self):
"""Checks if the Twitter user info is known"""
return (self.__get_data() is not None)
data = property(_get_data)
nick = property(lambda self: str(self.data.twitter_screen_name))
username = property(lambda self: str(self.data.twitter_screen_name))
real_name = property(lambda self: self.data.twitter_name.encode('utf-8'))
hostname = property(lambda self: 'twitter.com')
class UnknownTwitterUser(TwitterIrcUser):
"""An IrcUser object for an user we don't know anything about, but may be a valid Twitter user"""
def __init__(self, proto, nickname):
self.proto = proto
self.nick = nickname
self.username = nickname
real_name = 'Unknown User'
hostname = 'twitter.com'
def _target_params(self):
return {'screen_name':self.nick}
class TwitterIrcUserCache:
"""Cache of CachedTwitterIrcUser objects
A TwitterIrcUserCache is client-specific (not server-global), and takes
care of creating CachedTwitterIrcUser objects for some queries.
"""
def __init__(self, proto, cache):
self.proto = proto
self.cache = cache
self.cache.addCallback(self._user_changed)
self._watched_ids = {}
def _user_changed(self, id, old_info, new_info):
dbg("user_changed: %r, %r, %r" % (id, old_info, new_info))
if id in self._watched_ids:
dbg("user_changed (%s): is being watched." % (id))
u = self._get_user(id).data_changed(old_info, new_info)
def _get_user(self, id):
u = CachedTwitterIrcUser(self.proto, self.cache, id)
return u
def watch_user_id(self, id):
"""Start watching user ID for changes"""
self._watched_ids[id] = True
def watch_user_ids(self, ids):
for id in ids:
self.watch_user_id(id)
def watch_user(self, u):
self.watch_user_id(u._twitter_id)
def get_user(self, id):
return self._get_user(id)
def fetch_individual_user_info(self, unknown_users):
#TODO: implement me
pass
def fetch_all_friend_info(self, user, unknown_users):
#TODO: unify this paging code with the one on FriendlistMixIn
reqs = []
def request_cursor(cursor):
self.proto.dbg("requesting a page from the friend list: %s" % (str(cursor)))
reqs.append(cursor)
self.proto.api.list_friends(got_user, user=user, params={'cursor':cursor},
page_delegate=end_page).addCallbacks(done, error)
def got_user(u):
self.proto.global_twuser_cache.got_api_user_info(u)
def end_page(next, prev):
unk = [u for u in unknown_users if not u.has_data()]
num = len(unk)
if num == 0:
self.proto.notice("I know all friends of %s, now!" % (user))
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addCallback(self.got_entry)
f.addErrback(self.refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
e = entry
+ is_rt = False
if entry.retweeted_status:
e = entry.retweeted_status
+ is_rt = True
dbg("Retweet! RT ID: %r", entry.id)
u = self.proto.get_twitter_user(e.user.id)
dbg("entry id: %r", e.id)
text = e.text
dbg('entry text: %r' % (text))
- #TODO: what's the best way to format RTs?
+ if is_rt:
+ rt_inline = self.proto.user_cfg_var_b('rt_inline')
+ if rt_inline:
+ #TODO: make RT inline format configurable
+ text = '%s \x02[RT by @%s]\x02' % (text, entry.user.screen_name)
+
self.proto.send_text(u, self, text)
- if entry.retweeted_status:
- self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
+ if is_rt:
+ if not rt_inline:
+ self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
return None
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
def got_entry(self, e):
dbg("#twitter got_entry. id: %s", e.id)
self.cache_entry(e)
if e.retweeted_status:
self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("#twitter refresh error")
#FIXME: stop showing repeated errors and just let the user know when service is back
if e.check(twisted.web.error.Error):
if str(e.value.status) == '503':
self.bot_notice("Look! A flying whale! -- %s" % (e.value))
return
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.value.status == '400' and remaining == 0:
self.wait_rate_limit()
self.bot_notice("error refreshing feed: %s" % (e.value))
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You still can force the check by sending `!`. Also '
'you can check the rate limit by sending `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallback(done)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def _friendList(self, delegate, params={}, page_delegate=None):
#TODO: include the user on the list of channel members, too
# (the user whose timeline is being followed, not the Passerd
# authenticated user)
return self.proto.api.friends_ids(delegate, self.user, params=params,
page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def command_set(self, args):
#FIXME: implement me
self.message('Sorry, this is not implemented yet')
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
+ shorthelp_concise = "Show every post as a single IRC message"
+ def command_concise(self, args):
+ self.message("OK. I know I talk too much")
+ self.proto.set_user_cfg_var('rt_inline', True)
+ self.proto.set_user_cfg_var('multiline', False)
+
+ shorthelp_verbose = "Show multi-line posts as multiple lines, and RT info as additional passerd-bot messages"
+ def command_verbose(self, args):
+ self.message("Thanks. I like to talk, you know :)")
+ self.proto.set_user_cfg_var('rt_inline', False)
+ self.proto.set_user_cfg_var('multiline', True)
+
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
#self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
bm("Please tell me when you are ready, and we'll start the process")
bm("Are you ready? (yes/no)")
self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
def ask_restart():
bm("Do you want to restart?")
self.wait_for('^ *y|yes', start)
def start(msg, m):
bm("OK, let's do it:")
bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
consumer.get_oauth_token().addErrback(error_get_token)
def error_get_token(e):
bm("Error while trying to get an OAuth token: %s" % (e.value))
ask_restart()
def show_progress(msg):
bm("oauth progress: %s" % (msg))
def show_url(consumer, url):
bm("Now, go to: %s" % (url))
bm("After authorizing Passerd to access your account, you'll get a PIN")
bm("Please paste the PIN here")
self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
def got_pin(consumer, m):
pin = m.group(0)
bm("Got it. Thanks!")
bm("PIN: %r" % (pin))
consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
def pin_error(e):
bm("The PIN didn't work. I got this error: %s" % (e.value))
ask_restart()
def pin_worked(token):
bm('The PIN worked!')
bm("Now I will check if I can access your account...")
self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
def token_error(e):
bm("The OAuth authentication didn't work. Sorry :(")
bm("Error message: %s" % (e.value))
ask_restart()
def token_works(args):
token,api,u = args
bm("OAuth authentication worked!")
# change the user nickname to Twitter screen_name
nick = str(u.screen_name)
self.proto.the_user.force_nick(nick)
bm("Welcome to Passerd, %s" % (nick))
self.user_data = self.proto.set_user_token(u, token)
self.twitter_user = u
bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
bm("You have two authentication options:")
bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
bm("Which option do you want to use? (twitter/local)")
self.wait_for(r'^ *loc|^ *1 *$', setup_password)
self.wait_for(r'^ *twi|^ *2 *$', all_set)
def all_set(msg,m):
bm("OK, so you are all set")
bye_twpass()
self.wait_for('.*', bye_twpass)
def bye_twpass(*args):
bm("Just reconnect to Passerd using your Twitter password,")
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
def setup_password(msg,m):
bm("OK. Send your password as a message to the channel, and I will set it")
bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
bm("What will be your password?")
self.wait_for('.+', got_password)
self.wait_for('^ *generate *$', gen_password)
def got_password(msg,m):
pw = msg
if len(pw) < 6:
bm("This is a short password! Are you sure you want to use it?")
self.wait_for('.*', setup_password)
self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
else:
set_password(pw)
def gen_password(msg,m):
length = 16
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
pw = ''.join([random.choice(chars) for i in range(length)])
set_password(pw)
def set_password(pw):
self.proto.set_user_password(self.user_data, pw)
self.password = pw
bm("Password set to: %s" % (pw))
bye_pwset()
self.wait_for('.*', bye_pwset)
def bye_pwset(*args):
bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
welcome()
class UserSetupChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
self.dialog = d = NewUserDialog(proto)
attach_dialog_to_channel(d, self, self.proto.passerd_bot)
# start the dialog automatically if any message is received on
# the channel:
d.wait_for('.*', lambda *a: d.begin())
def list_members(self):
return [self.proto.the_user, self.proto.passerd_bot]
def afterUserJoined(self, who):
self.dialog.begin()
def requires_auth(fn):
"""A decorator for a generic authentication check before handling certain commands
This function should die soon. Having command-specific handling of
non-authenticated users would be better. Then we could make the commands
work as if everything is OK on the server, but without any real Twitter
user or channels available.
"""
def wrapper(self, *args, **kwargs):
if not self.is_authenticated():
raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
return fn(self, *args, **kwargs)
return wrapper
class PasserdProtocol(IRC):
def connectionMade(self):
self.quit_sent = False
IRC.connectionMade(self)
pinfo("Got connection from %s", self.hostname)
self.data = self.factory.data
#FIXME: use real names
self.myhost = MYHOST
self.password = None
# fields that will be available only after authentication:
self.api = None
self.scheduler = None
self.authenticated_user = None
self.user_data = None
self.got_user = False
self.got_nick = False
self.global_twuser_cache = self.factory.global_twuser_cache
self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
self.my_irc_server = IrcServer(self, self.myhost)
u = self.the_user = IrcUser(self)
u.nick = 'guest'
u.username = 'guest'
u.hostname = self.hostname
u.real_name = 'Unidentified User'
self.passerd_bot = PasserdBot(self, 'passerd-bot')
self.users = [self.the_user, self.passerd_bot]
predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
#TODO: keep a list of the fixed and joined channels,
# but use short-lived channel objects for other channel-query
# commands
self.channels = dict([(c.name, c) for c in predef_chans])
#FIXME: make the auto-join optional:
self.autojoin_channels = ['#twitter', '#mentions']
#FIXME: make joined_channels a more efficient list of channels
self.joined_channels = []
self.dm_feed = DirectMessagesFeed(self)
self.dm_feed.addCallback(self.gotDirectMessage)
self.dm_feed.addErrback(self.dmError)
dbg("Got new client")
def welcome_user(self):
for ch in self.autojoin_channels:
self.join_cname(ch)
self.dm_feed.start_refreshing()
self.scheduler.start()
def welcome_anonymous(self):
self.notice("Welcome, anonymous user!")
self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
def redirect_to_new_user_setup(self):
"""Send the user to the OAuth user setup channel"""
self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
self.join_cname('#new-user-setup')
def _set_scheduler(self, scheduler):
if self.scheduler:
self.scheduler.stop()
self.scheduler = None
self.scheduler = scheduler
def _userQuit(self, reason):
self.dm_feed.stop_refreshing()
for ch in self.joined_channels:
self.leave_channel(ch, reason)
self._set_scheduler(None)
self.quit_sent = True
def userQuit(self, reason):
if not self.quit_sent:
self._userQuit(reason)
self.quit_sent = True
def gotDirectMessage(self, msg):
self.global_twuser_cache.got_api_user_info(msg.sender)
sender = self.get_twitter_user(msg.sender.id, watch=True)
self.send_text(sender, self.the_user, msg.text)
def dmError(self, e):
self.notice("Error pulling Direct Messages: %s" % (e.value))
def send_text(self, sender, target, text):
# security:
text = full_entity_decode(text)
dbg('entities decoded: %r' % (text))
text = text.replace('\r', '\n')
- first = True
- # handle newlines as multiple messages
- for line in text.split('\n'):
- if not line:
- continue
- if not first:
- #TODO: find a better way to indicate multi-line posts
- line = '[...] '+line
- self.send_privmsg(sender, target, line.encode(IRC_ENCODING))
- first = False
+ lines = []
+ if self.user_cfg_var_b('multiline'):
+ first = True
+ # handle newlines as multiple messages
+ for line in text.split('\n'):
+ if not line:
+ continue
+ if not first:
+ #TODO: find a better way to indicate multi-line posts
+ line = '[...] '+line
+ lines.append(line.encode(IRC_ENCODING))
+ first = False
+ else:
+ lines = [text.replace('\n', ' ')]
+
+ for l in lines:
+ self.send_privmsg(sender, target, l)
def connectionLost(self, reason):
pinfo("connection to %s lost: %s", self.hostname, reason.value)
self.userQuit(str(reason))
IRC.connectionLost(self, reason)
def user_var(self, var):
"""Get any user var (config or internal feed state)"""
return self.data.get_var(self.user_data, var)
def set_user_var(self, var, value):
return self.data.set_var(self.user_data, var, value)
def set_user_cfg_var(self, var, value):
"""Set an user variable
Note that all vars are strings, and other types
are converted before setting the variables.
"""
# convert some data types to string
t = type(value)
if t is bool:
if value: value = '1'
else: value = '0'
vname = 'config:%s' % (var)
return self.set_user_var(vname, value)
- def user_cfg_var_b(self, var):
+ def user_cfg_var(self, var):
vname = 'config:%s' % (var)
- v = self.user_var(vname)
+ return self.user_var(vname)
+
+ def user_cfg_var_b(self, var):
+ v = self.user_cfg_var(var)
true_values = ['true', 't', '1', 'y', 'yes']
if v and v in true_values:
return True
else:
return False
def get_twitter_user(self, id, watch=False):
u = self.twitter_users.get_user(id)
if watch:
self.twitter_users.watch_user_id(id)
return u
def dbg(self, msg):
self.notice(msg)
## overwrite some methods of the twisted.words IRC class:
def sendMessage(self, *args, **kwargs):
dbg("sending message: %r %r" % (args, kwargs))
return IRC.sendMessage(self, *args, **kwargs)
def sendLine(self, *args, **kwargs):
dbg("sending line: %r %r" % (args, kwargs))
return IRC.sendLine(self, *args, **kwargs)
def _handleCommand(self, command, prefix, params):
"""Like IRC.handleCommand, but with no exception handling"""
method = getattr(self, "irc_%s" % (command), None)
if method is not None:
return method(prefix, params)
else:
return self.irc_unknown(prefix, command, params)
def handleCommand(self, *args, **kwargs):
def doit():
dbg("got command: %r %r" % (args, kwargs))
d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
d.addErrback(error)
def error(e):
ex = e.value
# ErrorReply exceptions are special: they generate a IRC error reply
if e.check(ErrorReply):
self.send_reply(ex.command, *ex.args)
return
perror("Got an exception: %s", e.getErrorMessage())
logger.exception(ex)
self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
doit()
def send_reply(self, cmd, *params, **kwargs):
return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
def send_message(self, sender, *params):
return self.sendMessage(*params, prefix=sender.full_id())
def server_message(self, cmd, *params):
return self.send_message(self.my_irc_server, cmd, *params)
def server_notice(self, target, msg):
self.send_notice(self.my_irc_server, target, msg)
def send_notice(self, sender, target, msg):
self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def send_privmsg(self, sender, target, msg):
self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
def notice(self, msg):
self.server_notice(self.the_user, msg)
def join_channel(self, chan):
if not (chan in self.joined_channels):
chan.userJoined(self.the_user)
self.joined_channels.append(chan)
def leave_channel(self, chan, reason):
if chan in self.joined_channels:
chan.userLeft(self.the_user, reason)
self.joined_channels.remove(chan)
def leave_cname(self, cname, reason):
channel = self.get_channel(cname)
if channel is not None:
self.leave_channel(channel, reason)
def join_cname(self, cname):
channel = self.get_channel(cname)
if channel is None:
channel = self.create_channel(cname)
dbg("get_channel %r" % (channel))
if channel is not None:
self.join_channel(channel)
def irc_PING(self, prefix, args):
self.server_message('PONG', args[0])
def irc_JOIN(self, prefix, params):
dbg("JOIN! %r %r" % (prefix, params))
cnames = params[0]
for c in cnames.split(','):
self.join_cname(c)
def irc_PART(self, prefix, params):
chans = params[0]
reason = None
if len(params) > 1:
reason = params[1]
for c in chans.split(','):
self.leave_cname(c, reason)
@requires_auth
def irc_INVITE(self, prefix, params):
nick = params[0]
cname = params[1]
chan = self.get_channel(cname)
if chan is not None:
chan.inviteUser(nick)
@requires_auth
def irc_KICK(self, prefix, params):
chans = params[0].split(',')
users = params[1].split(',')
for cname in chans:
chan = self.get_channel(cname)
if chan is not None:
chan.kickUsers(self.the_user, users)
def irc_QUIT(self, pref, params):
reason = None
if len(params) > 0:
reason = params[0]
self.userQuit(reason)
self.sendMessage('ERROR', ':Quit command received')
self.transport.loseConnection()
def irc_WHO(self, p, args):
for m in self.who_matches(args[0]):
self.send_reply(irc.RPL_WHOREPLY, *m)
self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
@requires_auth
def irc_WHOIS(self, p, args):
if len(args) > 2:
# invalid command
return
elif len(args) == 2:
# ignore server part
masks = args[1]
else:
masks = args[0]
masks = masks.split(',')
for m in masks:
self.whois_mask(m)
def irc_MODE(self, p, args):
tname = args[0]
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
target.modeRequest(self.the_user, args)
def irc_USERHOST(self, p, args):
if len(args) > 5:
args = args[:5]
r = []
for a in args:
u = self.get_user(a)
if u:
r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
if r:
self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
def irc_PRIVMSG(self, prefix, args):
tname = args[0]
msg = args[1]
sender = self.the_user
target = self.get_target(tname)
if target is None:
self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
return
# CTCP data:
if msg[0]==irc.X_DELIM:
m = irc.ctcpExtract(msg)
if m['extended']:
target.ctcpQueryReceived(sender, m['extended'])
# I won't handle the m['normal'] part. I don't trust this level of
# crazyness on the protocol
else:
target.messageReceived(sender, msg)
def irc_unknown(self, prefix, cmd, params):
dbg("CMD! %r %r %r" % (prefix, cmd, params))
self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
### authentication code:
def check_credentials(self, api, method):
d = defer.Deferred()
ok = []
def doit():
self.notice("Checking Twitter credentials using %s..." % (method))
api.verify_credentials(got_user).addCallback(done).addErrback(error)
def got_user(u):
self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
ok.append(u)
def done(*args):
if not ok:
d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
else:
d.callback(ok[0])
def error(e):
d.errback(e)
doit()
return d
def is_authenticated(self):
return (self.authenticated_user is not None)
def _send_welcome_replies(self):
"""Send standard IRC numeric replies after registration"""
self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, VERSION))
self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
self.send_reply(irc.RPL_MYINFO, self.myhost, VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
#TODO: send a MOTD with useful information
def set_authenticated_user(self, u):
self.authenticated_user = u
self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
def _twitter_api(self, *args, **kwargs):
"""Create a Twitter API object"""
api = Twitter(*args, timeout=self.factory.opts.api_timeout, **kwargs)
#FIXME; patch twitty-twister to accept agent=foobar
api.agent = MYAGENT
return api
def _check_basic_auth(self, username, password):
"""Run verify_credentials API call using basic auth
On success, pass a (api,auth_user) pair to the deferred callback
"""
api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
def doit():
return self.check_credentials(api, 'password').addCallback(done)
def done(u):
return (api, u)
return doit()
def test_oauth_token(self, token):
"""Check of the oauth token works
On success, pass a (token, api, auth_user) pair to the deferred callback
"""
api = self._twitter_api(consumer=oauth_consumer, token=token)
def doit():
return self.check_credentials(api, 'OAuth').addCallback(done)
def done(u):
return (token, api, u)
return doit()
def set_user_token(self, u, token):
udata = self.data.get_user(int(u.id), u.screen_name, create=True)
udata.oauth_token = token.key
udata.oauth_token_secret = token.secret
self.data.commit()
return udata
def set_user_password(self, udata, pw):
udata.set_password(pw)
assert udata.password_valid(pw) # sanity check
self.data.commit()
def _do_auth(self, username, password):
"""Authenticate username and password
"""
d = defer.Deferred()
def try_local_password():
"""Try to validate the password as a Passerd-only password"""
udata = self.data.get_user(None, username)
if udata is None:
return None
if not udata.password_valid(password):
return None
return udata
def doit():
# first, try the passerd-only passowrd:
udata = try_local_password()
if udata is not None:
self.notice("Your local Passerd password is valid")
return got_user(udata)
# if Passerd password doesn't work, try Twitter basic auth password:
self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
def basic_auth_ok(args):
api,u = args
udata = self.data.get_user(int(u.id), u.screen_name)
if udata is None:
return no_oauth_setup()
if not udata.oauth_token or not udata.oauth_token_secret:
return no_oauth_setup()
got_user(udata)
def no_oauth_setup():
d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
def got_user(udata):
token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
def oauth_works(args):
token,api,u = args
# authentication worked. set up variables:
self.api = api
self._set_scheduler(ApiScheduler(api))
self.set_authenticated_user(u)
d.callback(u)
def oauth_error(e):
if e.check(twisted.web.error.Error):
if str(e.value.status) == '401':
d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
return
d.errback(e)
doit()
return d
def _early_auth(self):
"""Run early password-authentication
This should be used only on the early registration stages.
"""
def doit():
self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
def auth_ok(u):
self._send_welcome_replies()
self.welcome_user()
def error(e):
if e.check(MissingOAuthRegistration):
self.notice("Error while authenticating - %s" % (e.value))
self.notice("Your connection will be considered anonymous, by now")
self._send_welcome_replies()
self.welcome_anonymous()
self.redirect_to_new_user_setup()
else:
self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
# on the other cases, drop the connection
self.transport.loseConnection()
doit()
def try_early_auth(self):
"""Try password-authentication on Twitter, if already got enough info"""
if self.api is not None:
# already set up authentication
return
if self.password is not None and self.got_user and self.got_nick:
self._early_auth()
def irc_NICK(self, prefix, params):
dbg("NICK %r" % (params))
nick = params[0]
if self.got_nick:
self.the_user.force_nick(nick)
else:
self.the_user.nick = nick
self.got_nick = True
self.try_early_auth()
def irc_PASS(self, p, args):
self.password = args[0]
self.try_early_auth()
def irc_USER(self, prefix, params):
dbg("USER %r" % (params))
username,_,_,real_name = params[0:4]
self.the_user.username = username
self.the_user.real_name = real_name
self.got_user = True
#TODO: accept connections without password, and allow a nickserv-style method of authentication
if self.password is not None:
# password set, try early authentication
self.try_early_auth()
else:
# not-authenticated-yet connection
self._send_welcome_replies()
self.welcome_anonymous()
def send_twitter_post(self, msg, args={}):
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
return defer.fail(MessageTooLong(msg, len(msg)))
return self.api.update(msg, params=args)
def get_user(self, nick):
#FIXME; index by nickname
for u in self.users:
if nick.lower() == u.nick.lower():
return u
# No Twitter user is available, if not authenticated yet
if not self.is_authenticated():
return None
#TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
# if not found, consider it's a potential Twitter user we don't know yet
return UnknownTwitterUser(self, nick)
def create_channel(self, name):
#TODO make it generic to allow more types of channels
#TODO: make it possible to create a short-lived channel object for
# channel-query commands
dbg("about to join channel: %s" % (name))
channel = None
if name.startswith("#@"):
rawname = name[2:]
try:
user, list_name = rawname.split('/', 1)
except ValueError:
# user channel:
user = rawname
if user:
channel = UserChannel(self, user)
else:
perror('invalid twitter user spec: %r' % (user))
else:
# list channel:
if not user or not list_name:
perror('invalid twitter list spec: %r' % (name))
else:
channel = ListChannel(self, user, list_name)
if channel:
self.channels[name] = channel
return channel
def get_channel(self, name):
return self.channels.get(name)
def get_target(self, name):
if name.startswith('#'):
return self.get_channel(name)
else:
return self.get_user(name)
def mask_matches(self, mask):
#FIXME: match wildcards?
u = self.get_user(mask)
if u:
yield u
def who_matches(self, mask):
#TODO: make WHO list channel users
for u in self.mask_matches(mask):
#XXX: WTF do "H" and "G" mean?
yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
def whois_twitter_user(self, u, tu):
self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
#FIXME: find a better way to send user information, instead of RPL_AWAY
# - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
def oneline(s):
return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
def whois_mask(self, mask):
|
ehabkost/passerd
|
fb956b2711e7a20fe3fcebe186fa7e166a943b52
|
display RTs as messages from the original poster
|
diff --git a/NEWS.markdown b/NEWS.markdown
index 83b4b3a..2c073b3 100644
--- a/NEWS.markdown
+++ b/NEWS.markdown
@@ -1,71 +1,74 @@
### Current development version:
* Add a simple scheduling algorithm that will make sure Passerd don't
kill the Twitter API rate-limit if the user joins too many Passerd
channels.
With this in place, Passerd will never make more than 80 requests per hour,
even if many feeds are being followed at the same time (not taking the
channel-join-time and login-time requests into account, though).
* Fix auto-`@` of nickname replies when nicknames have digits on it
* Set timeout on API calls to avoid getting stuck if HTTP requests take too
long to reply
+* Retweets are shown as messages from the original poster, with a note
+ by passerd-bot
+
### Passerd 0.0.5 - 6 Jan 2010
* Don't continue refreshing feeds if rate-limit is hit. This is a temporary
solution until a true rate-limit-adjusting scheduler is written
* Unify `passerd-bot` commands and implementation of `!command` on `#twitter`
* Including a help system
* Add a `!post` command (aliases: `!tw`, `!twit`, `!update`)
* Paranoid mode: if you are afraid of posting by mistake when typing on
your IRC client, you can enable a "paranoid" mode using the `!be paranoid`
command.
When in this mode, you can only post to twitter using `!post` (or the aliases
above)
### Passerd 0.0.4.2 - 28 Dec 2009
* Updated twitty-twister version. On 0.0.4, I forgot to update the
twitty-twister git commit reference, and broke twitter posting.
### Passerd 0.0.4.1 - 28 Dec 2009
* Fix a problem on the OAuth access token request method. A POST
request with no Content-Length may case a 411 Length Required
error (probably on some proxy servers).
* Thanks to Bogdano Arendartchuk for the fix.
### Passerd 0.0.4 - 27 Dec 2009
* Ability to follow lists using `#@username/list` channels
* Ability to get updates from a single user using `#@username` channels
* Implement #mentions channel, for mentions of `@username`
* OAuth support! Now you don't need to give your Twitter password to
Passerd (and you'll get a nice "from Passerd" note on your Twits. :)
* Optional nickserv-style authentication support
* Better error messages (using a `passerd-bot` IRC user)
* Now with a real (but still a bit ugly) web page at [passerd.raisama.net](http://passerd.raisama.net/)
### Passerd 0.0.3 - 18 Dec 2009
* Ability to send updates to Twitter
* Fetch detailed user info from Twitter on-demand, only if necessary
* Basic command-line option support
* Implement Twitter follow/unfollow as IRCK KICK/INVITE
### Passerd 0.0.2 - 15 Dec 2009
* List Twitter friends as IRC contacts
### Passerd 0.0.1 - 14 Dec 2009
* Basic Twitter reading ability
diff --git a/passerd/ircd.py b/passerd/ircd.py
index a2a7dd0..6c22e9e 100644
--- a/passerd/ircd.py
+++ b/passerd/ircd.py
@@ -1,1051 +1,1064 @@
#!/usr/bin/env python
#
# Passerd - An IRC server as a gateway to Twitter
#
# Author: Eduardo Habkost <ehabkost@raisama.net>
#
# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys, logging, time, re, random
import gc
import optparse
import rfc822 # for date/time parsing
from twisted.words.protocols import irc
from twisted.words.protocols.irc import IRC
from twisted.internet.protocol import Factory
from twisted.internet import reactor, defer
import twisted.web.error
from twittytwister.twitter import Twitter, TwitterClientInfo
from passerd.data import DataStore, TwitterUserData
from passerd.callbacks import CallbackList
from passerd.utils import full_entity_decode
from passerd.feeds import HomeTimelineFeed, ListTimelineFeed, UserTimelineFeed, MentionsFeed, DirectMessagesFeed
from passerd.scheduler import ApiScheduler
from passerd import dialogs
from passerd.dialogs import Dialog, CommandDialog, CommandHelpMixin, attach_dialog_to_channel, attach_dialog_to_bot
from passerd.util import try_unicode, to_str
from passerd.irc import IrcUser, IrcChannel, IrcServer
from passerd.poauth import OAuthClient, oauth_consumer
import oauth.oauth as oauth
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
# client/user-agent info:
####
MYNAME = 'Passerd'
VERSION = '0.0.5'
MYAGENT = '%s/%s' % (MYNAME, VERSION)
#FIXME: use a real hostname?
MYHOST = 'passerd.server'
MYURL = 'http://passerd.raisama.net/'
CLIENT_INFO = TwitterClientInfo(MYNAME, VERSION, MYURL)
# IRC protocol stuff:
####
# the only mode supported, right now:
SUPPORTED_CHAN_MODES = 'b'
# No user mode is supported, by now:
SUPPORTED_USER_MODES = '0'
IRC_ENCODING = 'utf-8'
# Twitter protocol stuff:
####
BASE_URL = 'https://twitter.com'
TWITTER_ENCODING = 'utf-8'
LENGTH_LIMIT = 140
# Some limits:
####
# keep latest 100 post on each channel, to create in_reply_to field.
REPLY_HISTORY_SIZE = 100
# if more than MAX_USER_INFO_FETCH users are unknown, use /statuses/friends to fetch user info.
# otherwise, just fetch individual user info
MAX_USER_INFO_FETCH = 0 # individual fetch is not implemented yet...
# the maximum number of sequential friend list page requests:
MAX_FRIEND_PAGE_REQS = 10
# IRC protocol constants:
####
# Other error codes we may use:
ERR_NEEDREGGEDNICK = '477'
# logging helpers:
####
logger = logging.getLogger("passerd")
dbg = logger.debug
pinfo = logger.info
perror = logger.error
class ErrorReply(Exception):
"""Special exception class used to generate IRC numeric replies"""
def __init__(self, command, *args):
self.command = command
self.args = args
class MissingOAuthRegistration(Exception):
pass
class MessageTooLong(Exception):
def __init__(self, text, length):
self.text = text
self.length = length
Exception.__init__(self, 'message too long (%d characters)' % (length))
class TwitterUserInfo:
"""Just carries simple data for a Twitter user
"""
def from_data(self, d):
self.screen_name = d.twitter_screen_name
self.name = d.twitter_name
return self
def to_data(self, d):
d.twitter_screen_name = self.screen_name
d.twitter_name = self.name
return self
def __repr__(self):
return 'TwitterUserInfo(%r, %r)' % (self.screen_name, self.name)
class TwitterUserCache:
"""Caches information about Twitter users
This is server-global, and is just an interface to the twitter_users database
table.
"""
def __init__(self, proto):
self.proto = proto
self.callbacks = CallbackList()
def addCallback(self, cb, *args, **kwargs):
"""Add a new callback function
Callback function is called with arguments: (twitter_user, old_info, new_info)
old_info may be None, if it's a new user
"""
self.callbacks.addCallback(cb, *args, **kwargs)
def _change_data(self, d, old_info, new_info):
# callbacks must becalled _before_ updating the data:
self.callbacks.callback(d.twitter_id, old_info, new_info)
new_info.to_data(d)
def _new_user(self, id, info):
d = TwitterUserData(twitter_id=id)
self._change_data(d, None, info)
#FIXME: encapsulate the following session operations, somehow:
self.proto.data.session.add(d)
self.proto.data.session.commit()
return d
def _update_user_info(self, id, new_info):
d = self.lookup_id(id)
if d is None:
return self._new_user(id, new_info)
old_info = TwitterUserInfo().from_data(d)
self._change_data(d, old_info, new_info)
#FIXME: encapsulate the following session operation, somehow:
self.proto.data.session.commit()
return d
def update_user_info(self, id, screen_name, name):
id = int(id)
i = TwitterUserInfo()
i.screen_name = screen_name
i.name = name
return self._update_user_info(id, i)
def got_api_user_info(self, u):
self.update_user_info(u.id, u.screen_name, u.name)
def lookup_id(self, id):
id = int(id)
#FIXME: encapsulate the following session operations, somehow:
d = self.proto.data.query(TwitterUserData).get(id)
if d is None:
return None
return d
def lookup_screen_name(self, name):
# not
try:
u = self.proto.data.query(TwitterUserData).filter_by(twitter_screen_name=name).one()
except MultipleResultsFound:
# multiple matches are possible if screen_names are reused.
# if that happens, be on the safe side: don't return anything
u = None
except NoResultFound:
u = None
return u
class TwitterIrcUser(IrcUser):
"""Common class for multiple methods of contacting IRC users"""
def _target_params(self, params):
"""Must return a dictionary containing user_id or screen_name, depending on
how much information we already have about the user.
"""
raise NotImplementedError("_target_params not implemented")
def send_direct_message(self, text):
d = defer.Deferred()
ok = []
def got_msg(msg):
ok.append(msg)
d.callback(msg)
def done(*args):
if not ok:
self.proto.notice("ERROR: Didn't get direct message info back when sending DM")
self.proto.api.send_direct_message(text, delegate=got_msg, params=self._target_params()).addCallbacks(done, d.errback)
return d
def messageReceived(self, sender, msg):
assert (sender is self.proto.the_user)
msg = try_unicode(msg, IRC_ENCODING)
if len(msg) > LENGTH_LIMIT:
#TODO: maybe there's a better error code for this?
raise ErrorReply(irc.RPL_AWAY, self.nick, ':message too long (%d characters), not sent.' % (len(msg)))
def doit():
self.send_direct_message(msg).addCallbacks(done, error)
def done(msg):
self.proto.notice("Direct Message to %s sent. ID: %s" % (self.nick, msg.id))
def error(e):
self.proto.send_reply(irc.RPL_AWAY, self.nick, ":Error sending Direct Message: %s" % (e.value))
doit()
class UnavailableTwitterData:
"""Fake TwitterUserData object for unavailable info"""
def __init__(self, id):
self.twitter_id = id
twitter_screen_name = property(lambda self: 'user-id-%s' % (self.twitter_id))
twitter_name = property(lambda self: 'Twitter User (info not fetched yet)')
class CachedTwitterIrcUser(TwitterIrcUser):
"""An IrcUser object for cached Twitter user info
Objects of this class may be short-lived, just to return info of a random
Twitter user for which we don't have much data.
"""
def __init__(self, proto, cache, id):
IrcUser.__init__(self, proto)
self._twitter_id = id
self.cache = cache
self._data = None
def _target_params(self):
return {'user_id':self._twitter_id}
def data_changed(self, old_info, new_info):
dbg("CachedTwitterIrcUser.data_changed! %r %r" % (old_info, new_info))
if (old_info is None) or (old_info.screen_name != new_info.screen_name):
self.notifyNickChange(str(new_info.screen_name))
def __get_data(self):
if self._data is None:
self._data = self.cache.lookup_id(self._twitter_id)
return self._data
def _get_data(self):
d = self.__get_data()
if d is None:
return UnavailableTwitterData(self._twitter_id)
return d
def has_data(self):
"""Checks if the Twitter user info is known"""
return (self.__get_data() is not None)
data = property(_get_data)
nick = property(lambda self: str(self.data.twitter_screen_name))
username = property(lambda self: str(self.data.twitter_screen_name))
real_name = property(lambda self: self.data.twitter_name.encode('utf-8'))
hostname = property(lambda self: 'twitter.com')
class UnknownTwitterUser(TwitterIrcUser):
"""An IrcUser object for an user we don't know anything about, but may be a valid Twitter user"""
def __init__(self, proto, nickname):
self.proto = proto
self.nick = nickname
self.username = nickname
real_name = 'Unknown User'
hostname = 'twitter.com'
def _target_params(self):
return {'screen_name':self.nick}
class TwitterIrcUserCache:
"""Cache of CachedTwitterIrcUser objects
A TwitterIrcUserCache is client-specific (not server-global), and takes
care of creating CachedTwitterIrcUser objects for some queries.
"""
def __init__(self, proto, cache):
self.proto = proto
self.cache = cache
self.cache.addCallback(self._user_changed)
self._watched_ids = {}
def _user_changed(self, id, old_info, new_info):
dbg("user_changed: %r, %r, %r" % (id, old_info, new_info))
if id in self._watched_ids:
dbg("user_changed (%s): is being watched." % (id))
u = self._get_user(id).data_changed(old_info, new_info)
def _get_user(self, id):
u = CachedTwitterIrcUser(self.proto, self.cache, id)
return u
def watch_user_id(self, id):
"""Start watching user ID for changes"""
self._watched_ids[id] = True
def watch_user_ids(self, ids):
for id in ids:
self.watch_user_id(id)
def watch_user(self, u):
self.watch_user_id(u._twitter_id)
def get_user(self, id):
return self._get_user(id)
def fetch_individual_user_info(self, unknown_users):
#TODO: implement me
pass
def fetch_all_friend_info(self, user, unknown_users):
#TODO: unify this paging code with the one on FriendlistMixIn
reqs = []
def request_cursor(cursor):
self.proto.dbg("requesting a page from the friend list: %s" % (str(cursor)))
reqs.append(cursor)
self.proto.api.list_friends(got_user, user=user, params={'cursor':cursor},
page_delegate=end_page).addCallbacks(done, error)
def got_user(u):
self.proto.global_twuser_cache.got_api_user_info(u)
def end_page(next, prev):
unk = [u for u in unknown_users if not u.has_data()]
num = len(unk)
if num == 0:
self.proto.notice("I know all friends of %s, now!" % (user))
return
self.proto.dbg("%d users are still unknown" % (num))
if not next or next == '0':
self.proto.dbg("yay! that was the last page!")
if num > 0:
self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
return
if len(reqs) > MAX_FRIEND_PAGE_REQS:
self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
return
request_cursor(next)
def done(*args):
self.proto.dbg("list_friends api request finished")
def error(e):
self.proto.dbg("list_friends error: %s" % (e))
request_cursor('-1')
def fetch_friend_info(self, user, friends):
dbg("fetch_friend_info: begin:")
unknown_users = [u for u in friends if not u.has_data()]
dbg("fetch_friend_info: got unknown friends...")
if len(unknown_users) == 0:
self.proto.notice("I already know all friends of %s. cool!" % (user))
return
dbg("%d unknown users..." % (len(unknown_users)))
self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
if len(unknown_users) < MAX_USER_INFO_FETCH:
self.fetch_individual_user_info(unknown_users)
else:
self.fetch_all_friend_info(user, unknown_users)
REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
class TwitterChannel(IrcChannel):
def __init__(self, proto, name):
IrcChannel.__init__(self, proto, name)
# REPLY_HISTORY_SIZE recent posts
self.recent_posts = []
# last post by each user ID
self.recent_by_user = {}
self.feeds = self._createFeeds()
for f in self.feeds:
f.addCallback(self.got_entry)
f.addErrback(self.refresh_error)
self.cmd_dialog = PasserdCommands(proto, self)
self.cmd_dialog.set_message_func(self.bot_msg)
self.cmd_dialog.set_cmd_prefix('!')
def _createFeeds(self):
raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
def userModeChar(self, u):
if u == self.proto.the_user:
return '@'
if u == self.proto.passerd_bot:
return '@'
return ''
def printEntry(self, entry):
- u = self.proto.get_twitter_user(entry.user.id)
- dbg("entry id: %r" % (entry.id))
- text = entry.text
+ e = entry
+ if entry.retweeted_status:
+ e = entry.retweeted_status
+ dbg("Retweet! RT ID: %r", entry.id)
+ u = self.proto.get_twitter_user(e.user.id)
+ dbg("entry id: %r", e.id)
+ text = e.text
dbg('entry text: %r' % (text))
+
+ #TODO: what's the best way to format RTs?
self.proto.send_text(u, self, text)
+ if entry.retweeted_status:
+ self.bot_msg("(%s retweeted by %s)" % (e.user.screen_name, entry.user.screen_name))
def _drop_one_old_entry(self):
#FIXME: Claudio reported a memory leak, I think it's here.
# remove from two lists:
# - recent_posts
# - last_post_by_user
drop = self.recent_posts.pop(0)
uid = int(drop.user.id)
# check if it is on the recent_by_user list, too:
urec = self.recent_by_user.get(uid, [])
if len(urec) > 0:
# we always remove entries from recent_by_user, so
# it should be the first on the list:
if int(urec[0].id) == int(drop.id):
urec.pop(0)
def _add_to_history(self, e):
self.recent_posts.append(e)
if self.recent_posts > REPLY_HISTORY_SIZE:
self._drop_one_old_entry()
uid = int(e.user.id)
self.recent_by_user.setdefault(uid, []).append(e)
def recent_post(self, nick, substring=None, min_age=None):
u = self.proto.global_twuser_cache.lookup_screen_name(nick)
if u is None:
# nickname not found
return None
uid = u.twitter_id
recent = self.recent_by_user.get(uid, [])
if len(recent) < 1:
return None
r = recent[-1]
if min_age:
#FIXME: add date parsing support to twitty-twister
#FIXME: show a list of alternatives to the user
# (how to do that for replies?)
t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
if t > time.time() - min_age:
raise Exception("latest post by %s is too recent" % (nick))
return r
def last_post_id(self, nick):
r = self.recent_post(nick)
if r is None:
return None
return int(r.id)
- def got_entry(self, e):
- dbg("#twitter got_entry. id: %s", e.id)
+ def cache_entry(self, e):
u = e.user
self.proto.global_twuser_cache.got_api_user_info(u)
self._add_to_history(e)
+
+ def got_entry(self, e):
+ dbg("#twitter got_entry. id: %s", e.id)
+ self.cache_entry(e)
+ if e.retweeted_status:
+ self.cache_entry(e.retweeted_status)
self.printEntry(e)
def bot_msg(self, msg):
self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
def bot_notice(self, msg):
self.proto.send_notice(self.proto.passerd_bot, self, msg)
def refresh_error(self, e):
dbg("#twitter refresh error")
#FIXME: stop showing repeated errors and just let the user know when service is back
if e.check(twisted.web.error.Error):
if str(e.value.status) == '503':
self.bot_notice("Look! A flying whale! -- %s" % (e.value))
return
remaining = self.proto.api.rate_limit_remaining
# note that it will not wait when remaining is None, which is
# intended
if e.value.status == '400' and remaining == 0:
self.wait_rate_limit()
self.bot_notice("error refreshing feed: %s" % (e.value))
def wait_rate_limit(self):
reset = time.ctime(self.proto.api.rate_limit_reset)
self.bot_msg('Ouch, the limit of requests per hour has been '
'reached. I will wait until %s to start checking the '
'Twitter timeline again.' % (reset))
self.bot_msg('You still can force the check by sending `!`. Also '
'you can check the rate limit by sending `!rate`.')
self.proto.scheduler.wait_rate_limit()
def start(self):
for f in self.feeds:
f.start_refreshing()
def stop(self):
dbg("stopping refresh of %s channel", self.name)
for f in self.feeds:
f.stop_refreshing()
def beforeUserJoined(self, user):
if not self.proto.is_authenticated():
# use the same numeric that Freenode uses
raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
def afterUserJoined(self, user):
dbg("user %s has joined!" % (user.full_id()))
self.start()
def beforeUserLeft(self, user, reason):
self.stop()
def beforeUserQuit(self, user, reason):
self.stop()
def forceRefresh(self, last):
def doit(f):
f._refresh(last_id=last).addCallback(done)
def done(num_args):
if num_args == 0:
#FIXME: we are sending notice as if it was from the user, here
self.bot_msg('people are quiet...')
for f in self.feeds:
doit(f)
def commandReceived(self, cmd):
"""Handle lines starting with '!'
"""
if cmd == '' or cmd == '!':
last = None
if cmd == '!':
last = 0
return self.forceRefresh(last)
self.cmd_dialog.recv_message(cmd)
def messageReceived(self, sender, msg):
if msg.startswith('!'):
return self.commandReceived(msg[1:])
# careful mode?
if not self.proto.user_cfg_var_b('careful'):
# simply post directly
self.do_send_twitter_post(msg)
else:
# careful mode: check if it's a valid command
r,_ = self.cmd_dialog.try_msg(msg)
if not r:
self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
def ctcp_ACTION(self, arg):
dbg("ACTION: %r" % (arg))
#TODO: make the behavior of "/me" messages configurable
self.do_send_twitter_post('/me %s' % (arg))
def do_send_twitter_post(self, msg):
def doit():
return self.send_twitter_post(msg)
def done(*args):
#FIXME: remove this notice once we update the channel topic. we don't need it.
self.bot_notice("Twitter update posted!!")
def error(e):
if e.check(MessageTooLong):
# message-too-long errors
self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
return
self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
def _add_in_reply_to(self, msg, args):
m = REPLY_RE.match(msg)
if m is None:
return msg
at = m.group(1)
nick = m.group(2)
end = m.group(3)
# just "username " at the beginning won't be considered
# a reply. User must use either "@username", "username:", or "username,"
if at != '@' and end == ' ':
return msg
#TODO: have some timing check, just in case the
# last post is too recent to be replied to (e.g. 0.1 second ago)
last_post = self.last_post_id(nick)
if last_post:
args['in_reply_to_status_id'] = str(last_post)
if not msg.startswith("@"):
msg = "@"+msg
#TODO: add "@" for users that are on the channel, but haven't posted recently?
return msg
def send_twitter_post(self, msg):
args = {}
msg = self._add_in_reply_to(msg, args)
dbg("msg: %r. args: %r", msg, args)
return self.proto.send_twitter_post(msg, args)
class FriendlistMixIn:
"""An extension to TwitterChannel to handle list of friends/members"""
def _friendList(self, delegate, params={}, page_delegate=None):
raise NotImplementedError("_friendList not implemented")
def _handleUserRefs(self, userrefs):
users = []
for u in userrefs:
users.append(self._user_object(u))
return users
def _fetch_user_info(self, users):
"""Can be used to trigger fetching of complete user info, if needed"""
pass
def _user_object(self, tu):
"""Can be overriden when get_friend_list() contains only user IDs"""
self.proto.global_twuser_cache.got_api_user_info(tu)
return self.proto.get_twitter_user(tu.id, watch=True)
def _get_friend_list(self):
d = defer.Deferred()
friends = set()
def got_page(next, prev):
self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
if not next or next == "0":
self.proto.dbg("%s user list: this was the last page" % (self.name))
d.callback(friends)
return
doit(next)
def doit(cursor):
params = {"cursor": cursor}
self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
def got_friend(ref):
friends.add(ref)
self.proto.dbg("I will fetch the list of users for %s" % (self.name))
doit("-1")
return d
def list_members(self):
#FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
d = defer.Deferred()
ids = []
def doit():
self._get_friend_list().addCallbacks(got_list, d.errback)
def got_list(userrefs):
dbg("Finished getting friend IDs for %s", self.name)
users = self._handleUserRefs(userrefs)
#FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
self._fetch_user_info(users)
#FIXME: 1) show the_user only if it really has joined the channel
#FIXME: 2) check if the_user is on the list used as input, and don't include it,
# to avoid duplicate entries on the list
users = [self.proto.the_user, self.proto.passerd_bot]+users
d.callback(users)
doit()
return d
class FriendIDsMixIn:
"""MixIn that can be used when the friend list is just a list of IDs"""
def _user_object(self, id):
return self.proto.get_twitter_user(int(id), watch=True)
#TODO: make mentions appear on #twitter, if configured to do so
class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
"""The #twitter channel"""
def topic(self):
return "Passerd -- Twitter home timeline channel"
def _createFeeds(self):
return [HomeTimelineFeed(self.proto)]
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
params=params, page_delegate=page_delegate)
def inviteUser(self, nickname):
#TODO: send a better error message if user is already being followed
user_ids = []
def doit():
self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id, watch=True)
self.notifyJoin(u)
def done(*args):
if not user_ids:
self.proto.notice("follow: got reply but no user info!?")
return
self.proto.dbg("follow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to follow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def kickUser(self, sender, nickname):
#TODO: send a better error message if the user is not being followed
user_ids = []
def doit():
self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
def got_user_info(u):
user_ids.append(u.id)
self.proto.global_twuser_cache.got_api_user_info(u)
u = self.proto.get_twitter_user(u.id)
self.notifyKick(sender, u)
def done(*args):
if not user_ids:
self.proto.notice("unfollow: got reply but no user info!?")
return
self.proto.dbg("unfollow request for %s done" % (nickname))
def error(e):
self.proto.notice('error when trying to unfollow user: %s' % (e.value))
self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
doit()
def _fetch_user_info(self, users):
self.proto.dbg("Now will fetch user info")
return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
class MentionsChannel(TwitterChannel):
"""The #mentions channel"""
def topic(self):
return "Passerd -- @mentions"
def _createFeeds(self):
return [MentionsFeed(self.proto)]
class ListChannel(FriendlistMixIn, TwitterChannel):
def __init__(self, proto, list_user, list_name):
self.list_user = list_user
self.list_name = list_name
TwitterChannel.__init__(self, proto, self._channelName())
def _createFeeds(self):
return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
def _channelName(self):
return "#@%s/%s" % (self.list_user, self.list_name)
def topic(self):
return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
def _friendList(self, delegate, params={}, page_delegate=None):
return self.proto.api.list_members(delegate, self.list_user,
self.list_name, params=params, page_delegate=page_delegate)
class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
def __init__(self, proto, user):
self.user = user
TwitterChannel.__init__(self, proto, self._channelName())
def _channelName(self):
return "#@%s" % (self.user)
def _createFeeds(self):
return [UserTimelineFeed(self.proto, self.user)]
def topic(self):
return "User timeline -- %s" % (self.user)
def _friendList(self, delegate, params={}, page_delegate=None):
#TODO: include the user on the list of channel members, too
# (the user whose timeline is being followed, not the Passerd
# authenticated user)
return self.proto.api.friends_ids(delegate, self.user, params=params,
page_delegate=page_delegate)
def _fetch_user_info(self, users):
return self.proto.twitter_users.fetch_friend_info(self.user, users)
class ProtoDialog:
"""A simple mixin to set a 'proto' attribute on dialog_init()"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
class ConfigCommands(ProtoDialog, CommandDialog):
shorthelp_set = 'Change a config option'
def command_set(self, args):
#FIXME: implement me
self.message('Sorry, this is not implemented yet')
class BeCommands(CommandDialog):
"""The 'be' command handler"""
def dialog_init(self, proto, *args, **kwargs):
self.proto = proto
self.add_alias('paranoid', 'careful')
help_header = 'Shortcut for many common config settings'
def command_happy(self, args):
self.message(':)')
def unknown_command(self, cmd, args):
self.message('Be what?')
shorthelp_careful = "Don't post channel messages to Twitter directly"
def command_careful(self, args):
self.message('I will. From now on, Twitter updates can '
'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
self.proto.set_user_cfg_var('careful', True)
shorthelp_brave = "Post channel messages to Twitter directly"
def command_brave(self, args):
self.message('So you are! Channel messages will be posted directly to Twitter')
self.proto.set_user_cfg_var('careful', False)
def show_help(self, prefix, args):
self.message(self.parent.cmd_syntax_str('be', '<flag>'))
self.message("Available flags:")
for imp,t in self.help_topics():
self.message(" %s - %s" % (t, self._short_help(t)))
class PasserdCommands(CommandHelpMixin, CommandDialog):
def dialog_init(self, proto, chan=None, *args, **kwargs):
self.proto = proto
self.chan = chan
#self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
self.add_subdialog('be', BeCommands(proto, parent=self))
self.add_alias('s', 'post')
self.add_alias('twit', 'post')
self.add_alias('tw', 'post')
self.add_alias('update', 'post')
shorthelp_login = 'Log into Passerd/Twitter'
def help_login(self, args):
self.cmd_syntax('login', 'twitter-login password')
self.message("If you don't have an account yet, join the #new-user-setup channel")
def command_login(self, args):
if not args:
return self.help_login(None)
parts = args.split(' ', 1)
if len(parts) <> 2:
return self.help_login(None)
login,password = parts
def doit():
self.proto._do_auth(login, password).addCallback(done).addErrback(error)
def done(u):
self.message("Welcome to Passerd, %s" % (u.screen_name))
self.proto.welcome_user()
def error(e):
self.message("Error while authenticating: %s" % (e.value))
if e.check(MissingOAuthRegistration):
self.proto.redirect_to_new_user_setup()
doit()
shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
importance_gc = dialogs.CMD_IMP_DEBUGGING
def command_gc(self, args):
self.message("Object counts: %r" % (gc.get_count(),))
r = gc.collect()
self.message("Garbage collection run. %d objects freed" % (r))
self.message("New object counts: %r" % (gc.get_count(),))
shorthelp_rate = 'Show Twitter API rate-limit info'
importance_rate = dialogs.CMD_IMP_ADVANCED
def command_rate(self, args):
api = self.proto.api
if api is None:
self.message('You are not logged in. No rate limit info is available')
return
self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
shorthelp_post = 'Post an update to Twitter'
def help_post(self, args):
self.cmd_syntax('post', 'text')
self.message("Post an update to Twitter")
def command_post(self, args):
if not args:
self.help_post(None)
return
def doit():
# if there is an associated channel, use it as context for the
# Twitter post. Otherwise, just use the general send_twitter_post()
# method
ch = self.chan
if ch:
d = ch.send_twitter_post(args)
else:
d = self.proto.send_twitter_post(args)
return d
def done(*args):
self.message("Done. Twitter update posted")
def error(e):
self.message("Error while posting: %s" % (e.value))
return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
class PasserdBot(IrcUser):
"""The Passerd IRC bot, that is used for Passerd messages on the channel"""
def __init__(self, proto, nick):
IrcUser.__init__(self, proto)
self.proto = proto
self.nick = nick
self.dialog = d = PasserdCommands(proto, None)
attach_dialog_to_bot(d, proto, proto.the_user, self)
real_name = 'Passerd Bot'
username = 'passerd'
hostname = MYHOST
class NewUserDialog(ProtoDialog, Dialog):
def begin(self, *args):
def bm(msg):
self.message(msg)
def welcome():
bm('Welcome!')
bm('On this channel, we will set up an account for you.')
bm("We will use the OAuth authentication method on Twitter,")
bm("so you don't even need to give me your Twitter password. :)")
|
ehabkost/passerd
|
58ef5af4aa8b5825482e58db0120915b60694531
|
experimental post-age check on replies
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..5ff47da
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+*.pyc
+tags
+docs/html/*.html
+.*.swp
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..dc777ce
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "third-party/twitty-twister"]
+ path = third-party/twitty-twister
+ url = git://github.com/ehabkost/twitty-twister.git
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..caa1ecf
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,48 @@
+Passerd copyright and license:
+
+Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+
+========================
+
+PBKDF2 module copyright and license:
+
+Copyright (C) 2007, 2008 Dwayne C. Litzenberger <dlitz@dlitz.net>
+All rights reserved.
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+provided that the above copyright notice appear in all copies and that
+both that copyright notice and this permission notice appear in
+supporting documentation.
+
+THE AUTHOR PROVIDES THIS SOFTWARE ``AS IS'' AND ANY EXPRESSED OR·
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES·
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.··
+IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,·
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,·
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY·
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT·
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE·
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+Country of origin: Canada
diff --git a/CREDITS.markdown b/CREDITS.markdown
new file mode 100644
index 0000000..2df9c61
--- /dev/null
+++ b/CREDITS.markdown
@@ -0,0 +1,18 @@
+Credits
+-------
+
+* Passerd was written by:
+ * [Eduardo Habkost](http://twitter.com/ehabkost) (<ehabkost@raisama.net>)
+* With contributions from:
+ * [Bogdano Arendartchuk](http://twitter.com/bhdn)
+* Early testing and ideas from:
+ * [Caio Begotti](http://twitter.com/caio1982)
+ * [Alexandre Possebom](http://twitter.com/possebom)
+ * [Felipe Arruda](http://twitter.com/felipemiguel)
+ * [Olavo Junior](http://twitter.com/olavojunior)
+ * [Tiago Salem Herrmann](http://twitter.com/tiagosh)
+* Some feature ideas were shamelessly borrowed from [tircd][tircd]
+
+
+[tircd]: http://code.google.com/p/tircd/
+
diff --git a/INSTALL.markdown b/INSTALL.markdown
new file mode 100644
index 0000000..68c47cf
--- /dev/null
+++ b/INSTALL.markdown
@@ -0,0 +1,52 @@
+What do I need, to use Passerd?
+-------------------------------
+
+_Passerd_ is written in Python. You need Python (of course!), and the following
+Python modules:
+
+* twisted (and its 'twisted.words' module)
+* sqlite
+* sqlalchemy
+* oauth
+* A patched version of twitty-twister -- but don't worry: it is automatically fetched by `git submodule` and `./run.sh` (see run instructions below)
+
+
+Below you'll find instructions to easily get the dependencies on some operating
+systems:
+
+### On Fedora
+
+To install the dependencies on a Fedora machine, run:
+
+ yum install python-twisted python-twisted-words python-sqlalchemy python-oauth
+
+
+### On Mandriva
+
+These dependencies currently match the 2010.0 release but should be ok for others:
+
+ urpmi python-twisted-words python-sqlite python-sqlalchemy python-oauth
+
+
+How do I run it?
+----------------
+
+Right now the recommended way to run Passerd is to check out the source
+directly from the git repository.
+
+### From the git repository:
+
+* Check out the [git repository][gitrepo]
+ * `git clone git://github.com/ehabkost/passerd.git`
+ * `cd passerd`
+* Run `git submodule init`
+* Run `git submodule update`
+* Run `./run.sh`
+* Point your IRC client to server `localhost`, port `6667`
+* Join the `#new-user-setup` channel on the server
+* Follow the instructions from `passerd-bot`
+* Have fun!
+
+See the `USERGUIDE` file for more information.
+
+[gitrepo]: http://github.com/ehabkost/passerd
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..78e3504
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,21 @@
+HTML_DOC_SOURCES = README USERGUIDE INSTALL NEWS CREDITS
+
+docs/html/%.html: %.markdown Makefile
+ mkdir -p docs/html
+ ( \
+ echo "<html>"; \
+ echo "<head><title>Passerd -" $* "</title></title>"; \
+ echo "</head><body>"; \
+ for f in $(HTML_DOC_SOURCES);do \
+ echo "<a href=\"$$f.html\">$$f</a>"; \
+ done; \
+ echo "<a href=\"http://github.com/ehabkost/passerd\">CODE</a>"; \
+ echo "<hl/>"; \
+ markdown2 $<; \
+ echo "</body>"; \
+ ) > "$@"
+
+html-docs: $(patsubst %,docs/html/%.html,$(HTML_DOC_SOURCES))
+
+upload-page: html-docs
+ rsync -vaP docs/html/ passerd.raisama.net:passerd.raisama.net/
diff --git a/NEWS.markdown b/NEWS.markdown
new file mode 100644
index 0000000..83b4b3a
--- /dev/null
+++ b/NEWS.markdown
@@ -0,0 +1,71 @@
+### Current development version:
+
+* Add a simple scheduling algorithm that will make sure Passerd don't
+ kill the Twitter API rate-limit if the user joins too many Passerd
+ channels.
+
+ With this in place, Passerd will never make more than 80 requests per hour,
+ even if many feeds are being followed at the same time (not taking the
+ channel-join-time and login-time requests into account, though).
+
+* Fix auto-`@` of nickname replies when nicknames have digits on it
+
+* Set timeout on API calls to avoid getting stuck if HTTP requests take too
+ long to reply
+
+
+### Passerd 0.0.5 - 6 Jan 2010
+
+* Don't continue refreshing feeds if rate-limit is hit. This is a temporary
+ solution until a true rate-limit-adjusting scheduler is written
+* Unify `passerd-bot` commands and implementation of `!command` on `#twitter`
+ * Including a help system
+* Add a `!post` command (aliases: `!tw`, `!twit`, `!update`)
+* Paranoid mode: if you are afraid of posting by mistake when typing on
+ your IRC client, you can enable a "paranoid" mode using the `!be paranoid`
+ command.
+ When in this mode, you can only post to twitter using `!post` (or the aliases
+ above)
+
+
+### Passerd 0.0.4.2 - 28 Dec 2009
+
+* Updated twitty-twister version. On 0.0.4, I forgot to update the
+ twitty-twister git commit reference, and broke twitter posting.
+
+
+### Passerd 0.0.4.1 - 28 Dec 2009
+
+* Fix a problem on the OAuth access token request method. A POST
+ request with no Content-Length may case a 411 Length Required
+ error (probably on some proxy servers).
+ * Thanks to Bogdano Arendartchuk for the fix.
+
+
+### Passerd 0.0.4 - 27 Dec 2009
+
+* Ability to follow lists using `#@username/list` channels
+* Ability to get updates from a single user using `#@username` channels
+* Implement #mentions channel, for mentions of `@username`
+* OAuth support! Now you don't need to give your Twitter password to
+ Passerd (and you'll get a nice "from Passerd" note on your Twits. :)
+* Optional nickserv-style authentication support
+* Better error messages (using a `passerd-bot` IRC user)
+* Now with a real (but still a bit ugly) web page at [passerd.raisama.net](http://passerd.raisama.net/)
+
+
+### Passerd 0.0.3 - 18 Dec 2009
+
+* Ability to send updates to Twitter
+* Fetch detailed user info from Twitter on-demand, only if necessary
+* Basic command-line option support
+* Implement Twitter follow/unfollow as IRCK KICK/INVITE
+
+### Passerd 0.0.2 - 15 Dec 2009
+
+* List Twitter friends as IRC contacts
+
+
+### Passerd 0.0.1 - 14 Dec 2009
+
+* Basic Twitter reading ability
diff --git a/README.markdown b/README.markdown
new file mode 100644
index 0000000..b21d39d
--- /dev/null
+++ b/README.markdown
@@ -0,0 +1,30 @@
+Passerd - A Twitter-IRC gateway
+===============================
+
+What is _Passerd_?
+------------------
+
+_Passerd_ is a Twitter client that runs an IRC server. Just run it and point an
+IRC client to it, and you'll see your Twitter friends as IRC contacts, and
+tweets appearing as messages on an IRC channel.
+
+Does it work?
+-------------
+
+Yes! You can read posts from the people you follow, post new updates to
+Twitter, and follow/unfollow people easily using just IRC commands.
+
+See the `USERGUIDE` file for more information.
+
+
+
+Install instructions
+--------------------
+
+See the `INSTALL` file.
+
+
+Credits
+-------
+
+See the `CREDITS` file.
diff --git a/USERGUIDE.markdown b/USERGUIDE.markdown
new file mode 100644
index 0000000..f5baa18
--- /dev/null
+++ b/USERGUIDE.markdown
@@ -0,0 +1,60 @@
+Passerd User Guide
+==================
+
+Running
+-------
+
+After starting _Passerd_, just point your favorit IRC client to it. If you are
+running it locally, just use server `localhost`, port `6667`
+
+
+Initial User Setup
+------------------
+
+The first time you connect to Passerd, you will be asked to join the
+`#new-user-setup` channel. Follow the instructions from `passerd-bot` at that
+channel to authorize Passerd to post to your account.
+
+You don't even need to give Passerd your Twitter password, if you don't want
+to. On the other hand, if you don't want to create a new password just for
+Passerd, you can simply use your Twitter password when logging in.
+
+After you set up your account, you can just set up your client to use the
+password when connecting, or use a _nickserv-style_ command to authenticate
+after connecting: `/MSG PASSERD-BOT LOGIN username password`.
+
+
+Basic Operation
+---------------
+
+Once you authenticate and join the `#twitter` channel on the server, the
+following features are available:
+
+* Sending new updates to Twitter is as simple as sending a message to the channel
+* Your friends timeline will appear as IRC messages on the channel
+* You can follow/unfollow people using the IRC `/kick` and `/invite` commands
+
+Other available features:
+
+* Direct Messages sent/received as simple IRC private messages
+* Following public lists, by joining any `#@username/listname` channel
+* Reading messages from individual users without following them on Twitter,
+ by joining any `#@username` channel
+* Querying Twitter user information using the IRC `/WHOIS` command
+
+
+### Special commands
+
+You can type some special commands on the IRC channel:
+
+* `!` - force the Twitter timeline to be fetched immediately
+* `!!` - force the Twitter timeline to be fetched, _including older posts_
+* `!rate` - query the Twitter API rate limit stats
+* `!be paranoid` - enable "paranoid mode", to avoid accidentaly posting to Twitter
+* `!help` or `/msg passerd-bot help` - Show help and other commands
+
+
+I need help!
+------------
+
+Feel free to contact the author at: [ehabkost@raisama.net](mailto:ehabkost@raisama.net).
diff --git a/bin/passerd b/bin/passerd
new file mode 100755
index 0000000..ba4e6b3
--- /dev/null
+++ b/bin/passerd
@@ -0,0 +1,3 @@
+#!/usr/bin/env python
+import passerd.ircd
+passerd.ircd.run()
diff --git a/docs/logo.png b/docs/logo.png
new file mode 100644
index 0000000..c9cd6f0
Binary files /dev/null and b/docs/logo.png differ
diff --git a/docs/logo.txt b/docs/logo.txt
new file mode 100644
index 0000000..84879c4
--- /dev/null
+++ b/docs/logo.txt
@@ -0,0 +1,5 @@
+ ,,,
+<° ) ,
+ (<_)
+ ""
+
diff --git a/docs/logo.xcf b/docs/logo.xcf
new file mode 100644
index 0000000..10ec01c
Binary files /dev/null and b/docs/logo.xcf differ
diff --git a/passerd/PBKDF2.py b/passerd/PBKDF2.py
new file mode 100644
index 0000000..2ca11d3
--- /dev/null
+++ b/passerd/PBKDF2.py
@@ -0,0 +1,354 @@
+#!/usr/bin/python
+# -*- coding: ascii -*-
+###########################################################################
+# PBKDF2.py - PKCS#5 v2.0 Password-Based Key Derivation
+#
+# Copyright (C) 2007, 2008 Dwayne C. Litzenberger <dlitz@dlitz.net>
+# All rights reserved.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose and without fee is hereby granted,
+# provided that the above copyright notice appear in all copies and that
+# both that copyright notice and this permission notice appear in
+# supporting documentation.
+#
+# THE AUTHOR PROVIDES THIS SOFTWARE ``AS IS'' AND ANY EXPRESSED OR
+# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# Country of origin: Canada
+#
+###########################################################################
+# Sample PBKDF2 usage:
+# from Crypto.Cipher import AES
+# from PBKDF2 import PBKDF2
+# import os
+#
+# salt = os.urandom(8) # 64-bit salt
+# key = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit key
+# iv = os.urandom(16) # 128-bit IV
+# cipher = AES.new(key, AES.MODE_CBC, iv)
+# ...
+#
+# Sample crypt() usage:
+# from PBKDF2 import crypt
+# pwhash = crypt("secret")
+# alleged_pw = raw_input("Enter password: ")
+# if pwhash == crypt(alleged_pw, pwhash):
+# print "Password good"
+# else:
+# print "Invalid password"
+#
+###########################################################################
+# History:
+#
+# 2007-07-27 Dwayne C. Litzenberger <dlitz@dlitz.net>
+# - Initial Release (v1.0)
+#
+# 2007-07-31 Dwayne C. Litzenberger <dlitz@dlitz.net>
+# - Bugfix release (v1.1)
+# - SECURITY: The PyCrypto XOR cipher (used, if available, in the _strxor
+# function in the previous release) silently truncates all keys to 64
+# bytes. The way it was used in the previous release, this would only be
+# problem if the pseudorandom function that returned values larger than
+# 64 bytes (so SHA1, SHA256 and SHA512 are fine), but I don't like
+# anything that silently reduces the security margin from what is
+# expected.
+#
+# 2008-06-17 Dwayne C. Litzenberger <dlitz@dlitz.net>
+# - Compatibility release (v1.2)
+# - Add support for older versions of Python (2.2 and 2.3).
+#
+###########################################################################
+
+__version__ = "1.2"
+
+from struct import pack
+from binascii import b2a_hex
+from random import randint
+import string
+
+try:
+ # Use PyCrypto (if available)
+ from Crypto.Hash import HMAC, SHA as SHA1
+
+except ImportError:
+ # PyCrypto not available. Use the Python standard library.
+ import hmac as HMAC
+ import sha as SHA1
+
+def strxor(a, b):
+ return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)])
+
+def b64encode(data, chars="+/"):
+ tt = string.maketrans("+/", chars)
+ return data.encode('base64').replace("\n", "").translate(tt)
+
+class PBKDF2(object):
+ """PBKDF2.py : PKCS#5 v2.0 Password-Based Key Derivation
+
+ This implementation takes a passphrase and a salt (and optionally an
+ iteration count, a digest module, and a MAC module) and provides a
+ file-like object from which an arbitrarily-sized key can be read.
+
+ If the passphrase and/or salt are unicode objects, they are encoded as
+ UTF-8 before they are processed.
+
+ The idea behind PBKDF2 is to derive a cryptographic key from a
+ passphrase and a salt.
+
+ PBKDF2 may also be used as a strong salted password hash. The
+ 'crypt' function is provided for that purpose.
+
+ Remember: Keys generated using PBKDF2 are only as strong as the
+ passphrases they are derived from.
+ """
+
+ def __init__(self, passphrase, salt, iterations=1000,
+ digestmodule=SHA1, macmodule=HMAC):
+ self.__macmodule = macmodule
+ self.__digestmodule = digestmodule
+ self._setup(passphrase, salt, iterations, self._pseudorandom)
+
+ def _pseudorandom(self, key, msg):
+ """Pseudorandom function. e.g. HMAC-SHA1"""
+ return self.__macmodule.new(key=key, msg=msg,
+ digestmod=self.__digestmodule).digest()
+
+ def read(self, bytes):
+ """Read the specified number of key bytes."""
+ if self.closed:
+ raise ValueError("file-like object is closed")
+
+ size = len(self.__buf)
+ blocks = [self.__buf]
+ i = self.__blockNum
+ while size < bytes:
+ i += 1
+ if i > 0xffffffffL or i < 1:
+ # We could return "" here, but
+ raise OverflowError("derived key too long")
+ block = self.__f(i)
+ blocks.append(block)
+ size += len(block)
+ buf = "".join(blocks)
+ retval = buf[:bytes]
+ self.__buf = buf[bytes:]
+ self.__blockNum = i
+ return retval
+
+ def __f(self, i):
+ # i must fit within 32 bits
+ assert 1 <= i <= 0xffffffffL
+ U = self.__prf(self.__passphrase, self.__salt + pack("!L", i))
+ result = U
+ for j in xrange(2, 1+self.__iterations):
+ U = self.__prf(self.__passphrase, U)
+ result = strxor(result, U)
+ return result
+
+ def hexread(self, octets):
+ """Read the specified number of octets. Return them as hexadecimal.
+
+ Note that len(obj.hexread(n)) == 2*n.
+ """
+ return b2a_hex(self.read(octets))
+
+ def _setup(self, passphrase, salt, iterations, prf):
+ # Sanity checks:
+
+ # passphrase and salt must be str or unicode (in the latter
+ # case, we convert to UTF-8)
+ if isinstance(passphrase, unicode):
+ passphrase = passphrase.encode("UTF-8")
+ if not isinstance(passphrase, str):
+ raise TypeError("passphrase must be str or unicode")
+ if isinstance(salt, unicode):
+ salt = salt.encode("UTF-8")
+ if not isinstance(salt, str):
+ raise TypeError("salt must be str or unicode")
+
+ # iterations must be an integer >= 1
+ if not isinstance(iterations, (int, long)):
+ raise TypeError("iterations must be an integer")
+ if iterations < 1:
+ raise ValueError("iterations must be at least 1")
+
+ # prf must be callable
+ if not callable(prf):
+ raise TypeError("prf must be callable")
+
+ self.__passphrase = passphrase
+ self.__salt = salt
+ self.__iterations = iterations
+ self.__prf = prf
+ self.__blockNum = 0
+ self.__buf = ""
+ self.closed = False
+
+ def close(self):
+ """Close the stream."""
+ if not self.closed:
+ del self.__passphrase
+ del self.__salt
+ del self.__iterations
+ del self.__prf
+ del self.__blockNum
+ del self.__buf
+ self.closed = True
+
+def crypt(word, salt=None, iterations=None):
+ """PBKDF2-based unix crypt(3) replacement.
+
+ The number of iterations specified in the salt overrides the 'iterations'
+ parameter.
+
+ The effective hash length is 192 bits.
+ """
+
+ # Generate a (pseudo-)random salt if the user hasn't provided one.
+ if salt is None:
+ salt = _makesalt()
+
+ # salt must be a string or the us-ascii subset of unicode
+ if isinstance(salt, unicode):
+ salt = salt.encode("us-ascii")
+ if not isinstance(salt, str):
+ raise TypeError("salt must be a string")
+
+ # word must be a string or unicode (in the latter case, we convert to UTF-8)
+ if isinstance(word, unicode):
+ word = word.encode("UTF-8")
+ if not isinstance(word, str):
+ raise TypeError("word must be a string or unicode")
+
+ # Try to extract the real salt and iteration count from the salt
+ if salt.startswith("$p5k2$"):
+ (iterations, salt, dummy) = salt.split("$")[2:5]
+ if iterations == "":
+ iterations = 400
+ else:
+ converted = int(iterations, 16)
+ if iterations != "%x" % converted: # lowercase hex, minimum digits
+ raise ValueError("Invalid salt")
+ iterations = converted
+ if not (iterations >= 1):
+ raise ValueError("Invalid salt")
+
+ # Make sure the salt matches the allowed character set
+ allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./"
+ for ch in salt:
+ if ch not in allowed:
+ raise ValueError("Illegal character %r in salt" % (ch,))
+
+ if iterations is None or iterations == 400:
+ iterations = 400
+ salt = "$p5k2$$" + salt
+ else:
+ salt = "$p5k2$%x$%s" % (iterations, salt)
+ rawhash = PBKDF2(word, salt, iterations).read(24)
+ return salt + "$" + b64encode(rawhash, "./")
+
+# Add crypt as a static method of the PBKDF2 class
+# This makes it easier to do "from PBKDF2 import PBKDF2" and still use
+# crypt.
+PBKDF2.crypt = staticmethod(crypt)
+
+def _makesalt():
+ """Return a 48-bit pseudorandom salt for crypt().
+
+ This function is not suitable for generating cryptographic secrets.
+ """
+ binarysalt = "".join([pack("@H", randint(0, 0xffff)) for i in range(3)])
+ return b64encode(binarysalt, "./")
+
+def test_pbkdf2():
+ """Module self-test"""
+ from binascii import a2b_hex
+
+ #
+ # Test vectors from RFC 3962
+ #
+
+ # Test 1
+ result = PBKDF2("password", "ATHENA.MIT.EDUraeburn", 1).read(16)
+ expected = a2b_hex("cdedb5281bb2f801565a1122b2563515")
+ if result != expected:
+ raise RuntimeError("self-test failed")
+
+ # Test 2
+ result = PBKDF2("password", "ATHENA.MIT.EDUraeburn", 1200).hexread(32)
+ expected = ("5c08eb61fdf71e4e4ec3cf6ba1f5512b"
+ "a7e52ddbc5e5142f708a31e2e62b1e13")
+ if result != expected:
+ raise RuntimeError("self-test failed")
+
+ # Test 3
+ result = PBKDF2("X"*64, "pass phrase equals block size", 1200).hexread(32)
+ expected = ("139c30c0966bc32ba55fdbf212530ac9"
+ "c5ec59f1a452f5cc9ad940fea0598ed1")
+ if result != expected:
+ raise RuntimeError("self-test failed")
+
+ # Test 4
+ result = PBKDF2("X"*65, "pass phrase exceeds block size", 1200).hexread(32)
+ expected = ("9ccad6d468770cd51b10e6a68721be61"
+ "1a8b4d282601db3b36be9246915ec82a")
+ if result != expected:
+ raise RuntimeError("self-test failed")
+
+ #
+ # Other test vectors
+ #
+
+ # Chunked read
+ f = PBKDF2("kickstart", "workbench", 256)
+ result = f.read(17)
+ result += f.read(17)
+ result += f.read(1)
+ result += f.read(2)
+ result += f.read(3)
+ expected = PBKDF2("kickstart", "workbench", 256).read(40)
+ if result != expected:
+ raise RuntimeError("self-test failed")
+
+ #
+ # crypt() test vectors
+ #
+
+ # crypt 1
+ result = crypt("cloadm", "exec")
+ expected = '$p5k2$$exec$r1EWMCMk7Rlv3L/RNcFXviDefYa0hlql'
+ if result != expected:
+ raise RuntimeError("self-test failed")
+
+ # crypt 2
+ result = crypt("gnu", '$p5k2$c$u9HvcT4d$.....')
+ expected = '$p5k2$c$u9HvcT4d$Sd1gwSVCLZYAuqZ25piRnbBEoAesaa/g'
+ if result != expected:
+ raise RuntimeError("self-test failed")
+
+ # crypt 3
+ result = crypt("dcl", "tUsch7fU", iterations=13)
+ expected = "$p5k2$d$tUsch7fU$nqDkaxMDOFBeJsTSfABsyn.PYUXilHwL"
+ if result != expected:
+ raise RuntimeError("self-test failed")
+
+ # crypt 4 (unicode)
+ result = crypt(u'\u0399\u03c9\u03b1\u03bd\u03bd\u03b7\u03c2',
+ '$p5k2$$KosHgqNo$9mjN8gqjt02hDoP0c2J0ABtLIwtot8cQ')
+ expected = '$p5k2$$KosHgqNo$9mjN8gqjt02hDoP0c2J0ABtLIwtot8cQ'
+ if result != expected:
+ raise RuntimeError("self-test failed")
+
+if __name__ == '__main__':
+ test_pbkdf2()
+
+# vim:set ts=4 sw=4 sts=4 expandtab:
diff --git a/passerd/__init__.py b/passerd/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/passerd/callbacks.py b/passerd/callbacks.py
new file mode 100644
index 0000000..0cd0c78
--- /dev/null
+++ b/passerd/callbacks.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+#
+# 'callback list' code
+#
+# Author: Eduardo Habkost <ehabkost@raisama.net>
+#
+# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+import traceback
+
+
+# maybe Twisted has something equivalent to this, already?
+class CallbackList:
+ def __init__(self, ignore_exceptions=True, print_exceptions=True):
+ self._cbs = []
+ self._ignore_exceptions = ignore_exceptions
+ self._print_exceptions = print_exceptions
+
+ def _doCall(self, cb, cbargs, cbkwargs, *args, **kwargs):
+ a = []
+ a.extend(args)
+ a.extend(cbargs)
+
+ kw = {}
+ kw.update(kwargs)
+ kw.update(cbkwargs)
+ return cb(*a, **kw)
+
+ def addCallback(self, cb, *args, **kwargs):
+ self._cbs.append( (cb, args, kwargs) )
+
+ def callback(self, *args, **kwargs):
+ for cb, ca, ckw in self._cbs:
+ try:
+ self._doCall(cb, ca, ckw, *args, **kwargs)
+ except:
+ if not self._ignore_exceptions:
+ raise
+ elif self._print_exceptions:
+ traceback.print_exc()
+
+
+__all__ = ['CallbackList']
diff --git a/passerd/data.py b/passerd/data.py
new file mode 100644
index 0000000..2ba1e34
--- /dev/null
+++ b/passerd/data.py
@@ -0,0 +1,227 @@
+#!/usr/bin/env python
+#
+# Passerd - An IRC server as a gateway to Twitter
+#
+# Persistent state & settings module
+#
+# Author: Eduardo Habkost <ehabkost@raisama.net>
+#
+# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+import logging
+
+from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, ForeignKey, UniqueConstraint
+from sqlalchemy.exc import OperationalError
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import relation, backref, sessionmaker
+from sqlalchemy.orm.exc import NoResultFound
+
+import PBKDF2
+
+logger = logging.getLogger('passerd.data')
+
+Base = declarative_base()
+
+
+# poor-man sqlalchemy migration system:
+# (I don't want to depend on the availability of the python-migration package)
+class DataMigration(Base):
+ __tablename__ = 'data_migrations'
+ id = Column(Integer, primary_key=True)
+ name = Column(String, unique=True)
+
+
+class User(Base):
+ __tablename__ = 'users'
+ id = Column(Integer, primary_key=True)
+ twitter_id = Column(Integer, unique=True)
+ twitter_login = Column(String, unique=True) # legacy field
+ oauth_token = Column(String)
+ oauth_token_secret = Column(String)
+ password_crypt = Column(String)
+
+ def set_password(self, password):
+ self.password_crypt = PBKDF2.crypt(password)
+
+ def password_valid(self, password):
+ return PBKDF2.crypt(password, self.password_crypt) == self.password_crypt
+
+class UserVar(Base):
+ __tablename__ = 'user_vars'
+ __table_args__ = (
+ UniqueConstraint('user_id','name'),
+ {}
+ )
+ id = Column(Integer, primary_key=True)
+ user_id = Column(Integer, ForeignKey('users.id'))
+ user = relation(User, backref='variables')
+ name = Column(String)
+ value = Column(String)
+
+class TwitterUserData(Base):
+ """Cache of twitter user information"""
+ __tablename__ = 'twitter_users'
+ twitter_id = Column(Integer, primary_key=True)
+ twitter_screen_name = Column(String)
+ twitter_name = Column(String)
+
+
+
+MIGRATIONS = []
+
+class Migration:
+ def __init__(self, name, func):
+ self.name = name
+ self.func = func
+
+ def _run(self, session):
+ logger.info("running data migration %s", self.name)
+ self.func(session)
+
+ def check(self, smaker):
+ s = smaker()
+ r = s.query(DataMigration).filter_by(name=self.name).first()
+ if r is None:
+ self._run(s)
+ s.add(DataMigration(name=self.name))
+ s.commit()
+
+# decorator:
+def migration(name):
+ def wrap(func):
+ m = Migration(name, func)
+ MIGRATIONS.append(m)
+ return m
+ return wrap
+
+
+def add_column(session, table, column, type):
+ """Helper function to easily add a new table column"""
+ md = MetaData(bind=session.connection())
+ md.reflect(only=[table])
+
+ tb = md.tables[table]
+ if tb.columns.has_key(column):
+ logger.info("Good: column %s.%s already exists", table, column)
+ return
+
+ session.execute('alter table "%s" add column "%s" %s' % (table, column, type))
+ session.commit()
+
+## migrations functions:
+
+# (please keep them in the right order)
+
+@migration('twitter_id_col')
+def twitter_id_col(s):
+ add_column(s, 'users', 'twitter_id', 'INTEGER')
+
+@migration('user_oauth_columns')
+def add_oauth_columns(s):
+ add_column(s, 'users', 'oauth_token', 'VARCHAR')
+ add_column(s, 'users', 'oauth_token_secret', 'VARCHAR')
+
+@migration('user_password_crypt_column')
+def add_oauth_columns(s):
+ add_column(s, 'users', 'password_crypt', 'VARCHAR')
+
+## end of migration functions
+
+
+def run_migrations(engine):
+ smaker = sessionmaker(bind=engine)
+ for m in MIGRATIONS:
+ m.check(smaker)
+
+class DataStore:
+ def __init__(self, url):
+ self.engine = create_engine(url)
+ self.session = sessionmaker(bind=self.engine)()
+
+ def create_tables(self):
+ Base.metadata.create_all(self.engine)
+ run_migrations(self.engine)
+
+
+ def query(self, *args, **kwargs):
+ return self.session.query(*args, **kwargs)
+
+ def new_user(self, twitter_id, screen_name):
+ u = User(twitter_id=twitter_id, twitter_login=screen_name)
+ self.session.add(u)
+ self.session.commit()
+ return u
+
+ def get_user(self, twitter_id, screen_name, create=False):
+ if twitter_id is not None:
+ u = self.session.query(User).filter_by(twitter_id=twitter_id).first()
+ if u is not None:
+ return u
+
+ # look for old screen_name-based data:
+ u = self.session.query(User).filter_by(twitter_login=screen_name).first()
+ if u is not None:
+ if twitter_id is not None:
+ logger.info("Converting old user data: screen_name: %s, id: %d" % (screen_name, twitter_id))
+ # old data. update it to use the Twitter user ID
+ u.twitter_id = twitter_id
+ self.session.commit()
+ return u
+
+ # not found:
+ if not create:
+ return None
+ return self.new_user(twitter_id, screen_name)
+
+ def _var(self, user, var):
+ return self.session.query(UserVar).filter_by(user_id=user.id, name=var).scalar()
+
+ def get_var(self, user, var):
+ v = self._var(user, var)
+ if v is None:
+ return None
+ return v.value
+
+ def set_var(self, user, var, value):
+ v = self._var(user, var)
+ if v is None:
+ v = UserVar(user_id=user.id, name=var, value=value)
+ self.session.add(v)
+ else:
+ v.value = value
+ self.session.commit()
+
+ def commit(self):
+ self.session.commit()
+
+__all__ = ['DataStore', 'TwitterUserData']
+
+if __name__ == '__main__':
+ import logging, sys
+ #logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
+ s = DataStore('sqlite:///%s' % (sys.argv[1]))
+ s.create_tables()
+ u = s.get_user('foo', create=True)
+ print 'bar1:',s.get_var(u, 'bar')
+ s.set_var(u, 'bar', 'baz')
+ print 'bar2:',s.get_var(u, 'bar')
+ s.set_var(u, 'bar', 'baz2')
+ print 'bar3:',s.get_var(u, 'bar')
diff --git a/passerd/dialogs.py b/passerd/dialogs.py
new file mode 100644
index 0000000..79fcafb
--- /dev/null
+++ b/passerd/dialogs.py
@@ -0,0 +1,289 @@
+import re
+
+class Dialog:
+ """An abstract interface to "user dialogs"
+ """
+ def __init__(self, *args, **kwargs):
+ self.patterns = []
+ self.message_func = None
+ self.parent = kwargs.get('parent', None)
+ self.dialog_init(*args, **kwargs)
+
+ def set_message_func(self, fn):
+ self.message_func = fn
+
+ def dialog_init(self, *args, **kwargs):
+ """Initialize the Dialog object"""
+ pass
+
+ def begin(self):
+ """Start the dialog"""
+ pass
+
+ def wait_for(self, regexp, func, flags=re.I, strip=True):
+ if strip:
+ filter = (lambda s: s.strip())
+ else:
+ filter = (lambda s: s)
+
+ self.patterns.insert(0, (filter, re.compile(regexp, flags), func) )
+
+ def unknown_message(self, msg):
+ self.message("Sorry, I don't know what you mean")
+
+ def error_reply(self, msg, e):
+ self.message("An error has occurred. Sorry. -- %s" % (e))
+
+ def recv_message(self, msg):
+ for filter,expr,func in self.patterns:
+ s = filter(msg)
+ m = expr.search(s)
+ if m:
+ try:
+ return func(msg, m)
+ except Exception,e:
+ return self.error_reply(msg, e)
+ return self.unknown_message(msg)
+
+ def message(self, msg):
+ """Send a message to the user"""
+ if self.message_func is None:
+ raise NotImplementedError("Dialog.message: not message_func set")
+ return self.message_func(msg)
+
+
+# command "importance", to order help system
+CMD_IMP_IMPORTANT = 0 # important commands
+CMD_IMP_COMMON = 2 # commonly-used commands
+CMD_IMP_INTERESTING = 5 # interesting-to-know commands
+CMD_IMP_UNIMPORTANT = 6 # usual but not important commands
+CMD_IMP_ADVANCED = 8 # advanced commands
+CMD_IMP_DEBUGGING = 8 # debugging/development commands
+
+CMD_IMP_ALIAS = 7
+CMD_IMP_DEFAULT = CMD_IMP_INTERESTING
+
+class CommandDialog(Dialog):
+ """A dialog for simple 'command args' commands"""
+ def __init__(self, *args, **kwargs):
+ self.subdialogs = []
+ self.commands = {}
+ self.cmd_prefix = ''
+ Dialog.__init__(self, *args, **kwargs)
+ self.add_alias('?', 'help')
+
+ def _set_subdialog_prefix(self, cmd, dialog):
+ dialog.set_cmd_prefix('%s%s ' % (self.cmd_prefix, cmd.upper()))
+
+ def set_cmd_prefix(self, prefix):
+ """Set prefix for command examples on help messages
+
+ Useful for the "!command" format or for subdialogs
+ """
+ self.cmd_prefix = prefix
+ for cmd,sd in self.subdialogs:
+ self._set_subdialog_prefix(cmd, sd)
+
+ def unknown_command(self, cmd, args):
+ #TODO: show help
+ self.message("Sorry, I don't get it. Type '%sHELP' for available commands" % (self.cmd_prefix))
+
+ def add_command(self, cmd, fn):
+ self.commands[cmd.lower()] = fn
+
+ def add_alias(self, alias, cmd, imp=CMD_IMP_ALIAS):
+ self.add_command(alias, self._command_fn(cmd))
+ sh = self._short_help(cmd)
+ if sh:
+ setattr(self, 'shorthelp_%s' % (alias.lower()), 'Synonym to `%s`: %s' % (cmd, sh))
+ setattr(self, 'importance_%s' % (alias.lower()), imp)
+
+ def _command_fn(self, cmd):
+ fn = getattr(self, 'command_%s' % (cmd.lower()), None)
+ if fn is None:
+ fn = self.commands.get(cmd.lower())
+ return fn
+
+ def add_subdialog(self, cmd, dialog, short_help=None):
+ def show_help(args):
+ dialog.show_help('%s: ' % (cmd.upper()), args)
+
+ def handle_cmd(args):
+ if not args:
+ args = ''
+ dialog.recv_message(args)
+
+ self.subdialogs.append( (cmd, dialog) )
+
+ dialog.set_message_func(self.message)
+ self._set_subdialog_prefix(cmd, dialog)
+ self.add_command(cmd, handle_cmd)
+ setattr(self, 'help_%s' % (cmd.lower()), show_help)
+ if short_help is None:
+ short_help = dialog.get_help_header()
+ if short_help:
+ setattr(self, 'shorthelp_%s' % (cmd.lower()), short_help)
+
+ def split_args(self, s):
+ s = s.lstrip()
+ parts = s.split(' ',1)
+ cmd = parts[0]
+ if len(parts) > 1:
+ args = parts[1]
+ else:
+ args = None
+ return cmd,args
+
+ def _short_help(self, cmd):
+ return getattr(self, 'shorthelp_%s' % (cmd.lower()), None)
+
+ def short_help(self, cmd):
+ sh = self._short_help(cmd)
+ if sh is None:
+ return None
+
+ # command get a full prefix
+ if self._command_fn(cmd):
+ prefix = self.cmd_prefix
+ else:
+ prefix = ''
+ return '%s%s - %s' % (prefix, cmd.upper(), sh)
+
+ def _long_help(self, cmd, args):
+ fn = getattr(self, 'help_%s' % (cmd.lower()), None)
+ if fn:
+ return fn(args)
+ sh = self.short_help(cmd)
+ if sh:
+ self.message(sh)
+ return
+ self.message("Unknown help topic: %s" % (cmd))
+
+ def get_help_header(self):
+ return getattr(self, 'help_header', None)
+
+ def show_help_header(self, args):
+ h = self.get_help_header()
+ if h:
+ self.message(h)
+
+ def _topic_importance(self, t):
+ r = getattr(self, 'importance_%s' % (t.lower()), None)
+ if r is None:
+ return CMD_IMP_DEFAULT
+ else:
+ return r
+
+ def help_topics(self):
+ r = []
+ for a in dir(self):
+ if a.startswith('shorthelp_'):
+ _,t = a.split('_',1)
+ imp = self._topic_importance(t)
+ r.append( (imp, t) )
+ r.sort()
+ return r
+
+ def show_help(self, prefix, args):
+ if args:
+ cmd,rest = self.split_args(args)
+ return self._long_help(cmd, rest)
+
+ topics = []
+ commands = []
+ for imp,t in self.help_topics():
+ if self._command_fn(t):
+ commands.append( (imp,t) )
+ else:
+ topics.append( (imp,t) )
+
+ self.show_help_header(args)
+ if commands:
+ main = []
+ rest = []
+ for imp,c in commands:
+ if imp <= CMD_IMP_INTERESTING:
+ main.append(c)
+ else:
+ rest.append(c)
+ if main:
+ self.message('%sAvailable commands:' % (prefix))
+ for c in main:
+ self.message(self.short_help(c))
+ if rest:
+ if main: name='Other commands'
+ else: name='Available commands'
+ pref = self.cmd_prefix
+ clist = ' '.join(['%s%s' % (pref,c.upper()) for c in rest])
+ self.message("%s: %s" % (name, clist))
+ if topics:
+ self.message('Other help topics:' % (prefix))
+ for t in topics:
+ self.message(self.short_help(t))
+ self.show_help_footer(args)
+
+ def show_help_footer(self, args):
+ pass
+
+ def cmd_syntax_str(self, cmd, args):
+ if args: suffix = ' %s' % (args)
+ else: suffix = ''
+ return 'Usage: %s%s%s' % (self.cmd_prefix, cmd.upper(), suffix)
+
+ def cmd_syntax(self, cmd, args):
+ self.message(self.cmd_syntax_str(cmd, args))
+
+ def help_help(self, args):
+ self.cmd_syntax('help', 'command-or-topic')
+ def command_help(self, args):
+ self.show_help('', args)
+
+ def try_msg(self, msg, unknown_fn=None):
+ cmd,args = self.split_args(msg)
+ fn = self._command_fn(cmd)
+ if fn is None:
+ return False,(cmd,args)
+ return True,fn(args)
+
+ def recv_message(self, msg):
+ worked,r = self.try_msg(msg)
+ if worked:
+ return r
+ else:
+ cmd,args = r
+ return self.unknown_command(cmd, args)
+
+
+class CommandHelpMixin:
+ shorthelp_help = 'Show help'
+ importance_help = CMD_IMP_UNIMPORTANT
+
+
+def attach_dialog_to_channel(dialog, chan, bot_user):
+ def doit():
+ chan.add_msg_notifier(got_chan_msg)
+ dialog.set_message_func(send_message)
+
+ def got_chan_msg(ch, sender, msg):
+ assert ch is chan
+ dialog.recv_message(msg)
+
+ def send_message(msg):
+ chan.send_message(bot_user, msg)
+
+ doit()
+
+def attach_dialog_to_bot(dialog, proto, real_user, bot):
+ def doit():
+ bot.add_msg_notifier(got_msg)
+ dialog.set_message_func(send_message)
+
+ def got_msg(u, sender, msg):
+ assert u is bot
+ dialog.recv_message(msg)
+
+ def send_message(msg):
+ proto.send_notice(bot, real_user, msg)
+
+ doit()
+
diff --git a/passerd/feeds.py b/passerd/feeds.py
new file mode 100644
index 0000000..e342ad8
--- /dev/null
+++ b/passerd/feeds.py
@@ -0,0 +1,206 @@
+#!/usr/bin/env python
+#
+# Passerd - An IRC server as a gateway to Twitter
+#
+# Code for continuously-updating feeds
+#
+# Author: Eduardo Habkost <ehabkost@raisama.net>
+#
+# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+import time
+import logging
+
+from twisted.internet import reactor, defer
+
+from passerd.callbacks import CallbackList
+
+# 'count' paremeter for feed queries. It's a bit high, but this shouldn't be a
+# problem as we always use the last_id parameter.
+QUERY_COUNT = 100
+
+logger = logging.getLogger('passerd.feeds')
+dbg = logger.debug
+
+class TwitterFeed:
+
+ def __init__(self, proto):
+ self.proto = proto
+ self.updater = None
+ self.callbacks = CallbackList()
+ self.errbacks = CallbackList()
+ self.continue_refreshing = False
+ self.next_refresh = None
+ self.loading = False
+ self._last_id = None
+
+ def _last_id_var(self):
+ return self.LAST_ID_VAR
+
+ def update_last_id(self, last_id):
+ self._last_id = last_id
+ self.proto.set_user_var(self._last_id_var(), last_id)
+
+ @property
+ def last_id(self):
+ if self._last_id is None:
+ self._last_id = self.proto.user_var(self._last_id_var())
+ return self._last_id
+
+ def addCallback(self, *args, **kwargs):
+ """Add a callback for new entries"""
+ self.callbacks.addCallback(*args, **kwargs)
+
+ def addErrback(self, *args, **kwargs):
+ """Add a callbck for loading errors"""
+ self.errbacks.addCallback(*args, **kwargs)
+
+ @property
+ def api(self):
+ return self.proto.api
+
+ @property
+ def scheduler(self):
+ return self.proto.scheduler
+
+ def refresh_resched(self):
+ if self.updater is not None:
+ self.updater.resched()
+
+ def _refresh(self, last_id=None):
+ if last_id is None:
+ last_id = self.last_id
+
+ entries = []
+ d = defer.Deferred()
+
+ def doit():
+ args = {}
+ if last_id:
+ args['since_id'] = last_id
+ args['count'] = str(QUERY_COUNT)
+ self._timeline(got_entry, args).addCallbacks(finished, error)
+ dbg("_refresh returning")
+
+ def error(*args):
+ dbg("_refresh error %r" % (args,))
+ d.errback(*args)
+ self.errbacks.callback(*args)
+
+ # store the entries and then show them in chronological order:
+ def got_entry(e):
+ dbg("got an entry")
+ entries.insert(0, e)
+
+ def finished(*args):
+ dbg("finished loading %r" % (args,))
+ for e in entries:
+ self.callbacks.callback(e)
+ if self.last_id is None or int(e.id) > int(self.last_id):
+ self.update_last_id(e.id)
+ d.callback(len(entries))
+
+ doit()
+ return d
+
+ def refresh(self):
+ def doit():
+ if self.loading:
+ dbg("Won't refresh now. Still loading...")
+ return
+
+ self.loading = True
+ self._refresh().addCallbacks(done, error).addBoth(resched)
+
+ def error(*args):
+ dbg("ERROR while refreshing")
+
+ def done(num_entries):
+ dbg("got %d entries." % (num_entries))
+
+ def resched(*args):
+ self.loading = False
+ dbg("rescheduling...")
+ self.refresh_resched()
+
+ return doit()
+
+ def stop_refreshing(self):
+ if self.updater is not None:
+ self.updater.destroy()
+ self.updater = None
+
+ def start_refreshing(self):
+ if self.updater is None:
+ self.updater = self.scheduler.new_updater(self.refresh)
+ # yes, this is cheating, but I don't want to make the user wait for
+ # too long
+ #FIXME: just add support for 'one-shot lower-latency' calls on
+ # the scheduler, instead of cheating
+ self.refresh()
+
+class ListTimelineFeed(TwitterFeed):
+
+ def __init__(self, proto, list_user, list_name):
+ TwitterFeed.__init__(self, proto)
+ self.list_user = list_user
+ self.list_name = list_name
+
+ def _last_id_var(self):
+ return "last_status_id_@%s/%s" % (self.list_user, self.list_name)
+
+ def _timeline(self, delegate, args):
+ return self.api.list_timeline(delegate, self.list_user,
+ self.list_name, args)
+
+
+class HomeTimelineFeed(TwitterFeed):
+ LAST_ID_VAR = 'home_last_status_id'
+
+ def _timeline(self, delegate, args):
+ dbg("will try to use the API:")
+ return self.api.home_timeline(delegate, args)
+
+
+class UserTimelineFeed(TwitterFeed):
+
+ def __init__(self, proto, user):
+ TwitterFeed.__init__(self, proto)
+ self.user = user
+
+ def _last_id_var(self):
+ return "last_status_id_@%s" % (self.user)
+
+ def _timeline(self, delegate, args):
+ return self.api.user_timeline(delegate, self.user, args)
+
+
+class MentionsFeed(TwitterFeed):
+ LAST_ID_VAR = 'mentions_last_status_id'
+
+ def _timeline(self, delegate, args):
+ return self.api.mentions(delegate, args)
+
+class DirectMessagesFeed(TwitterFeed):
+ LAST_ID_VAR = 'direct_messages_last_id'
+
+ def _timeline(self, delegate, args):
+ return self.api.direct_messages(delegate, args)
diff --git a/passerd/irc.py b/passerd/irc.py
new file mode 100644
index 0000000..2209d8c
--- /dev/null
+++ b/passerd/irc.py
@@ -0,0 +1,293 @@
+#!/usr/bin/env python
+#
+# Passerd - An IRC server as a gateway to Twitter
+#
+# Basic IRC protocol abstraction classes
+#
+# Author: Eduardo Habkost <ehabkost@raisama.net>
+#
+# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+import logging
+
+from twisted.words.protocols import irc
+from twisted.internet import defer
+from passerd.util import hooks
+
+logger = logging.getLogger("passerd.irc")
+dbg = logger.debug
+pinfo = logger.info
+perror = logger.error
+
+
+class IrcTarget:
+ """Common class for IRC channels and users
+
+ This may contain some common operations that work for both users and
+ channels.
+ """
+ def __init__(self, proto):
+ self.proto = proto
+ self.msg_notifiers = []
+
+ def add_msg_notifier(self, func):
+ self.msg_notifiers.append(func)
+
+ def notify_message(self, sender, msg):
+ for func in self.msg_notifiers:
+ func(self, sender, msg)
+
+ def parseModeSetRequest(self, args):
+ """Parse a mode-change request, generating (flags,params) tuples
+
+ Whoever invented the MODE command syntax is _really_ evil.
+ """
+ i = 0
+ dbg("parsing mode request: %r" % (args))
+ while i < len(args):
+ flags = args[i]
+ i += 1
+ params = []
+ while i < len(args):
+ a = args[i]
+ if a[:1] in '+-':
+ # a new flag set/unset was requested
+ break
+ params.append(a)
+ i += 1
+ dbg("flags: %r, params: %r" % (flags, params))
+ yield flags,params
+
+ def modeFlagQuery(self, flag, params):
+ dbg("mode flag query: %r %r" % (flag, params))
+ # specific mode query/set request:
+ if not flag in self.supported_modes:
+ self.proto.send_reply(irc.ERR_UNKNOWNMODE, 'Mode %s is not known to me' % (flag))
+ return
+ fn = getattr(self, 'mode_query_%s' % (flag))
+ fn(params)
+
+ def flagChangeRequest(self, flag, value, params):
+ dbg("mode change request: %r %s %r" % (flag, value, params))
+ if not flag in self.supported_modes:
+ self.proto.send_reply(irc.ERR_UNKNOWNMODE, flag, ':Mode %s is not known to me' % (flag))
+ return
+ fn = getattr(self, 'mode_set_%s' % (flag))
+ fn(value, params)
+
+ def modeFlagRequest(self, sender, args):
+ for flags,params in self.parseModeSetRequest(args):
+ value = 0
+ for f in flags:
+ if f == '+': value = 1
+ elif f == '-': value = -1
+ else:
+ if value == 0:
+ # no "+" or "-" => simple query
+ self.modeFlagQuery(f, params)
+ else:
+ self.flagChangeRequest(f, value, params)
+
+
+ def modeRequest(self, sender, args):
+ if len(args) == 1:
+ # general mode query
+ self.sendModes()
+ else:
+ self.modeFlagRequest(self, args[1:])
+
+ def ctcp_unknown(self, tag, data):
+ dbg("Unsupported CTCP query: %r %r" % (tag, data))
+
+ def ctcpQueryReceived(self, sender, query):
+ for tag,data in query:
+ m = getattr(self, 'ctcp_%s' % (tag), None)
+ if m is not None:
+ m(data)
+ else:
+ self.ctcp_unknown(tag, data)
+
+ def messageReceived(self, sender, msg):
+ assert (sender is self.proto.the_user)
+ self.notify_message(sender, msg)
+
+
+class IrcUser(IrcTarget):
+ supported_modes = ''
+
+ def __cmp__(self, o):
+ return cmp(self.nick, o.nick)
+
+ def target_name(self):
+ return self.nick
+
+ def is_away(self):
+ return False
+
+ def away_char(self):
+ if self.is_away(): return '-'
+ else: return '+'
+
+ def userhost(self):
+ return '%s@%s' % (self.username, self.hostname)
+
+ def full_id(self):
+ return '%s!%s@%s' % (self.nick, self.username, self.hostname)
+
+ def notifyNickChange(self, new_nick):
+ """Must be called before self.nick value changes, so the sender ID is correct"""
+ self.proto.send_message(self, 'NICK', new_nick)
+
+ def force_nick(self, new_nick):
+ if self.nick != new_nick:
+ self.notifyNickChange(new_nick)
+ self.nick = new_nick
+
+class IrcChannel(IrcTarget):
+ supported_modes = 'b'
+
+ def __init__(self, proto, name):
+ IrcTarget.__init__(self, proto)
+ self.name = name
+
+ def target_name(self):
+ return self.name
+
+ def ban_masks(self, params):
+ return []
+
+ def list_members(self):
+ #FIXME: include the_user only if the user already joined
+ return [self.proto.the_user]
+
+ def mode_query_b(self, params):
+ """Query ban list"""
+ dbg("checking the ban list for %s" % (self.name))
+ for m in self.ban_masks(params):
+ self.proto.send_reply(irc.RPL_BANLIST, self.name, m)
+ self.proto.send_reply(irc.RPL_ENDOFBANLIST, self.name, ":End of channel ban list")
+
+ def mode_set_b(self, value, params):
+ dbg("ban mode set request: %r %r" % (value, params))
+ if len(params) == 0:
+ # no params means this is a mode query
+ return self.mode_query_b(params)
+
+ raise NotImplementedError("Ban setting is not implemented")
+
+ def send_message(self, sender, msg):
+ self.proto.send_privmsg(sender, self, msg)
+
+ def typeChar(self):
+ """Return '@', '*', or '=', for RPL_NAMREPLY"""
+ return '=' # show channel as public by default
+
+ def userModeChar(self, user):
+ """Retuern '', '@', or '+', depending on user mode"""
+ return ''
+
+ def fullModeSpec(self):
+ # return no modes, by default
+ return ''
+
+ def notifyJoin(self, who):
+ self.proto.send_message(who, 'JOIN', self.name)
+ def notifyKick(self, kicker, kicked):
+ self.proto.send_message(kicker, 'KICK', self.name, kicked.nick)
+ def notifyPart(self, who, reason):
+ if reason is not None:
+ self.proto.send_message(who, 'PART', self.name, reason)
+ else:
+ self.proto.send_message(who, 'PART', self.name)
+ def notifyTopic(self):
+ self.proto.send_reply(irc.RPL_TOPIC, self.name, ':%s' % (self.topic()))
+ def sendModes(self):
+ self.proto.send_reply(irc.RPL_CHANNELMODEIS, self.name, self.fullModeSpec())
+
+ def _sendNames(self, members):
+ namelist = []
+ def flush():
+ names = ' '.join(namelist)
+ self.proto.send_reply(irc.RPL_NAMREPLY, '=', self.name, ':%s' % (names))
+ namelist[:] = []
+
+ for m in members:
+ namelist.append('%s%s' % (self.userModeChar(m), m.nick))
+ if len(namelist) > 30:
+ flush()
+ flush()
+ self.proto.send_reply(irc.RPL_ENDOFNAMES, self.name, ':End of NAMES list')
+
+ def sendNames(self):
+ def doit():
+ d = defer.maybeDeferred(self.list_members)
+ d.addCallback(send_names).addErrback(error)
+
+ def send_names(members):
+ dbg("got member list: %d members" % (len(members)))
+ self._sendNames(members)
+
+ def error(e):
+ self.proto.notice("ERROR: failure getting member names for %s -- %s" % (self.name, e.value))
+ #FIXME: include the_user only if the user already joined
+ self._sendNames([self.proto.the_user])
+
+ doit()
+
+ @hooks
+ def userJoined(self, user):
+ self.notifyJoin(user)
+ self.notifyTopic()
+ self.sendNames()
+
+ @hooks
+ def userLeft(self, user, reason):
+ self.notifyPart(user, reason)
+
+ @hooks
+ def userQuit(self, user, reason):
+ pass
+
+ def topic(self):
+ return "[no topic set]"
+
+ def kickUser(self, sender, nickname):
+ return NotImplementedError("Can't kick users from %s" % (self.name))
+
+ def inviteUser(self, nickname):
+ return NotImplementedError("Can't invite users to %s" % (self.name))
+
+ def kickUsers(self, sender, users):
+ for u in users:
+ self.kickUser(sender, u)
+
+
+class IrcServer(IrcTarget):
+ """An IrcTarget used for server messages"""
+ def __init__(self, proto, name):
+ IrcTarget.__init__(self, proto)
+ self.name = name
+
+ def full_id(self):
+ return self.name
+
+
+
diff --git a/passerd/ircd.py b/passerd/ircd.py
new file mode 100644
index 0000000..a2a7dd0
--- /dev/null
+++ b/passerd/ircd.py
@@ -0,0 +1,1955 @@
+#!/usr/bin/env python
+#
+# Passerd - An IRC server as a gateway to Twitter
+#
+# Author: Eduardo Habkost <ehabkost@raisama.net>
+#
+# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+import sys, logging, time, re, random
+import gc
+import optparse
+import rfc822 # for date/time parsing
+
+from twisted.words.protocols import irc
+from twisted.words.protocols.irc import IRC
+from twisted.internet.protocol import Factory
+from twisted.internet import reactor, defer
+import twisted.web.error
+
+
+from twittytwister.twitter import Twitter, TwitterClientInfo
+
+from passerd.data import DataStore, TwitterUserData
+from passerd.callbacks import CallbackList
+from passerd.utils import full_entity_decode
+from passerd.feeds import HomeTimelineFeed, ListTimelineFeed, UserTimelineFeed, MentionsFeed, DirectMessagesFeed
+from passerd.scheduler import ApiScheduler
+from passerd import dialogs
+from passerd.dialogs import Dialog, CommandDialog, CommandHelpMixin, attach_dialog_to_channel, attach_dialog_to_bot
+from passerd.util import try_unicode, to_str
+from passerd.irc import IrcUser, IrcChannel, IrcServer
+from passerd.poauth import OAuthClient, oauth_consumer
+import oauth.oauth as oauth
+
+from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
+
+
+
+# client/user-agent info:
+####
+
+MYNAME = 'Passerd'
+VERSION = '0.0.5'
+MYAGENT = '%s/%s' % (MYNAME, VERSION)
+#FIXME: use a real hostname?
+MYHOST = 'passerd.server'
+MYURL = 'http://passerd.raisama.net/'
+CLIENT_INFO = TwitterClientInfo(MYNAME, VERSION, MYURL)
+
+
+# IRC protocol stuff:
+####
+
+# the only mode supported, right now:
+SUPPORTED_CHAN_MODES = 'b'
+# No user mode is supported, by now:
+SUPPORTED_USER_MODES = '0'
+IRC_ENCODING = 'utf-8'
+
+
+# Twitter protocol stuff:
+####
+
+BASE_URL = 'https://twitter.com'
+TWITTER_ENCODING = 'utf-8'
+LENGTH_LIMIT = 140
+
+
+
+
+# Some limits:
+####
+
+
+# keep latest 100 post on each channel, to create in_reply_to field.
+REPLY_HISTORY_SIZE = 100
+
+# if more than MAX_USER_INFO_FETCH users are unknown, use /statuses/friends to fetch user info.
+# otherwise, just fetch individual user info
+
+MAX_USER_INFO_FETCH = 0 # individual fetch is not implemented yet...
+
+# the maximum number of sequential friend list page requests:
+MAX_FRIEND_PAGE_REQS = 10
+
+
+
+
+
+# IRC protocol constants:
+####
+
+# Other error codes we may use:
+ERR_NEEDREGGEDNICK = '477'
+
+
+
+# logging helpers:
+####
+
+logger = logging.getLogger("passerd")
+
+dbg = logger.debug
+pinfo = logger.info
+perror = logger.error
+
+
+
+class ErrorReply(Exception):
+ """Special exception class used to generate IRC numeric replies"""
+ def __init__(self, command, *args):
+ self.command = command
+ self.args = args
+
+class MissingOAuthRegistration(Exception):
+ pass
+
+class MessageTooLong(Exception):
+ def __init__(self, text, length):
+ self.text = text
+ self.length = length
+ Exception.__init__(self, 'message too long (%d characters)' % (length))
+
+
+
+class TwitterUserInfo:
+ """Just carries simple data for a Twitter user
+ """
+ def from_data(self, d):
+ self.screen_name = d.twitter_screen_name
+ self.name = d.twitter_name
+ return self
+
+ def to_data(self, d):
+ d.twitter_screen_name = self.screen_name
+ d.twitter_name = self.name
+ return self
+
+ def __repr__(self):
+ return 'TwitterUserInfo(%r, %r)' % (self.screen_name, self.name)
+
+class TwitterUserCache:
+ """Caches information about Twitter users
+
+ This is server-global, and is just an interface to the twitter_users database
+ table.
+ """
+ def __init__(self, proto):
+ self.proto = proto
+ self.callbacks = CallbackList()
+
+ def addCallback(self, cb, *args, **kwargs):
+ """Add a new callback function
+
+ Callback function is called with arguments: (twitter_user, old_info, new_info)
+ old_info may be None, if it's a new user
+ """
+ self.callbacks.addCallback(cb, *args, **kwargs)
+
+ def _change_data(self, d, old_info, new_info):
+ # callbacks must becalled _before_ updating the data:
+ self.callbacks.callback(d.twitter_id, old_info, new_info)
+
+ new_info.to_data(d)
+
+ def _new_user(self, id, info):
+ d = TwitterUserData(twitter_id=id)
+
+ self._change_data(d, None, info)
+ #FIXME: encapsulate the following session operations, somehow:
+ self.proto.data.session.add(d)
+ self.proto.data.session.commit()
+ return d
+
+ def _update_user_info(self, id, new_info):
+ d = self.lookup_id(id)
+ if d is None:
+ return self._new_user(id, new_info)
+
+ old_info = TwitterUserInfo().from_data(d)
+ self._change_data(d, old_info, new_info)
+ #FIXME: encapsulate the following session operation, somehow:
+ self.proto.data.session.commit()
+ return d
+
+ def update_user_info(self, id, screen_name, name):
+ id = int(id)
+ i = TwitterUserInfo()
+ i.screen_name = screen_name
+ i.name = name
+ return self._update_user_info(id, i)
+
+ def got_api_user_info(self, u):
+ self.update_user_info(u.id, u.screen_name, u.name)
+
+ def lookup_id(self, id):
+ id = int(id)
+ #FIXME: encapsulate the following session operations, somehow:
+ d = self.proto.data.query(TwitterUserData).get(id)
+ if d is None:
+ return None
+
+ return d
+
+ def lookup_screen_name(self, name):
+ # not
+ try:
+ u = self.proto.data.query(TwitterUserData).filter_by(twitter_screen_name=name).one()
+ except MultipleResultsFound:
+ # multiple matches are possible if screen_names are reused.
+ # if that happens, be on the safe side: don't return anything
+ u = None
+ except NoResultFound:
+ u = None
+ return u
+
+
+
+class TwitterIrcUser(IrcUser):
+ """Common class for multiple methods of contacting IRC users"""
+ def _target_params(self, params):
+ """Must return a dictionary containing user_id or screen_name, depending on
+ how much information we already have about the user.
+ """
+ raise NotImplementedError("_target_params not implemented")
+
+ def send_direct_message(self, text):
+ d = defer.Deferred()
+ ok = []
+
+ def got_msg(msg):
+ ok.append(msg)
+ d.callback(msg)
+
+ def done(*args):
+ if not ok:
+ self.proto.notice("ERROR: Didn't get direct message info back when sending DM")
+
+ self.proto.api.send_direct_message(text, delegate=got_msg, params=self._target_params()).addCallbacks(done, d.errback)
+ return d
+
+ def messageReceived(self, sender, msg):
+ assert (sender is self.proto.the_user)
+
+ msg = try_unicode(msg, IRC_ENCODING)
+ if len(msg) > LENGTH_LIMIT:
+ #TODO: maybe there's a better error code for this?
+ raise ErrorReply(irc.RPL_AWAY, self.nick, ':message too long (%d characters), not sent.' % (len(msg)))
+
+ def doit():
+ self.send_direct_message(msg).addCallbacks(done, error)
+
+ def done(msg):
+ self.proto.notice("Direct Message to %s sent. ID: %s" % (self.nick, msg.id))
+
+ def error(e):
+ self.proto.send_reply(irc.RPL_AWAY, self.nick, ":Error sending Direct Message: %s" % (e.value))
+
+ doit()
+
+
+class UnavailableTwitterData:
+ """Fake TwitterUserData object for unavailable info"""
+ def __init__(self, id):
+ self.twitter_id = id
+
+ twitter_screen_name = property(lambda self: 'user-id-%s' % (self.twitter_id))
+ twitter_name = property(lambda self: 'Twitter User (info not fetched yet)')
+
+
+class CachedTwitterIrcUser(TwitterIrcUser):
+ """An IrcUser object for cached Twitter user info
+
+ Objects of this class may be short-lived, just to return info of a random
+ Twitter user for which we don't have much data.
+ """
+ def __init__(self, proto, cache, id):
+ IrcUser.__init__(self, proto)
+ self._twitter_id = id
+ self.cache = cache
+ self._data = None
+
+ def _target_params(self):
+ return {'user_id':self._twitter_id}
+
+ def data_changed(self, old_info, new_info):
+ dbg("CachedTwitterIrcUser.data_changed! %r %r" % (old_info, new_info))
+ if (old_info is None) or (old_info.screen_name != new_info.screen_name):
+ self.notifyNickChange(str(new_info.screen_name))
+
+ def __get_data(self):
+ if self._data is None:
+ self._data = self.cache.lookup_id(self._twitter_id)
+ return self._data
+
+ def _get_data(self):
+ d = self.__get_data()
+ if d is None:
+ return UnavailableTwitterData(self._twitter_id)
+
+ return d
+
+ def has_data(self):
+ """Checks if the Twitter user info is known"""
+ return (self.__get_data() is not None)
+
+ data = property(_get_data)
+ nick = property(lambda self: str(self.data.twitter_screen_name))
+ username = property(lambda self: str(self.data.twitter_screen_name))
+ real_name = property(lambda self: self.data.twitter_name.encode('utf-8'))
+ hostname = property(lambda self: 'twitter.com')
+
+
+class UnknownTwitterUser(TwitterIrcUser):
+ """An IrcUser object for an user we don't know anything about, but may be a valid Twitter user"""
+ def __init__(self, proto, nickname):
+ self.proto = proto
+ self.nick = nickname
+ self.username = nickname
+
+ real_name = 'Unknown User'
+ hostname = 'twitter.com'
+
+ def _target_params(self):
+ return {'screen_name':self.nick}
+
+
+
+class TwitterIrcUserCache:
+ """Cache of CachedTwitterIrcUser objects
+
+ A TwitterIrcUserCache is client-specific (not server-global), and takes
+ care of creating CachedTwitterIrcUser objects for some queries.
+ """
+ def __init__(self, proto, cache):
+ self.proto = proto
+ self.cache = cache
+ self.cache.addCallback(self._user_changed)
+ self._watched_ids = {}
+
+ def _user_changed(self, id, old_info, new_info):
+ dbg("user_changed: %r, %r, %r" % (id, old_info, new_info))
+ if id in self._watched_ids:
+ dbg("user_changed (%s): is being watched." % (id))
+ u = self._get_user(id).data_changed(old_info, new_info)
+
+ def _get_user(self, id):
+ u = CachedTwitterIrcUser(self.proto, self.cache, id)
+ return u
+
+ def watch_user_id(self, id):
+ """Start watching user ID for changes"""
+ self._watched_ids[id] = True
+
+ def watch_user_ids(self, ids):
+ for id in ids:
+ self.watch_user_id(id)
+
+ def watch_user(self, u):
+ self.watch_user_id(u._twitter_id)
+
+ def get_user(self, id):
+ return self._get_user(id)
+
+
+ def fetch_individual_user_info(self, unknown_users):
+ #TODO: implement me
+ pass
+
+ def fetch_all_friend_info(self, user, unknown_users):
+ #TODO: unify this paging code with the one on FriendlistMixIn
+ reqs = []
+ def request_cursor(cursor):
+ self.proto.dbg("requesting a page from the friend list: %s" % (str(cursor)))
+ reqs.append(cursor)
+ self.proto.api.list_friends(got_user, user=user, params={'cursor':cursor},
+ page_delegate=end_page).addCallbacks(done, error)
+
+ def got_user(u):
+ self.proto.global_twuser_cache.got_api_user_info(u)
+
+ def end_page(next, prev):
+ unk = [u for u in unknown_users if not u.has_data()]
+ num = len(unk)
+
+ if num == 0:
+ self.proto.notice("I know all friends of %s, now!" % (user))
+ return
+
+ self.proto.dbg("%d users are still unknown" % (num))
+
+ if not next or next == '0':
+ self.proto.dbg("yay! that was the last page!")
+ if num > 0:
+ self.proto.notice("something seems to be wrong: I fetched all pages and I still don't know all of your friends")
+ return
+
+ if len(reqs) > MAX_FRIEND_PAGE_REQS:
+ self.proto.notice("I already fetched %d pages of detailed friend info. I won't fetch more, sorry.")
+ return
+
+ request_cursor(next)
+
+ def done(*args):
+ self.proto.dbg("list_friends api request finished")
+
+ def error(e):
+ self.proto.dbg("list_friends error: %s" % (e))
+
+ request_cursor('-1')
+
+ def fetch_friend_info(self, user, friends):
+ dbg("fetch_friend_info: begin:")
+ unknown_users = [u for u in friends if not u.has_data()]
+ dbg("fetch_friend_info: got unknown friends...")
+ if len(unknown_users) == 0:
+ self.proto.notice("I already know all friends of %s. cool!" % (user))
+ return
+
+ dbg("%d unknown users..." % (len(unknown_users)))
+ self.proto.notice("There are %d users I don't know about. I will fetch the detailed friend list" % (len(unknown_users)))
+
+ if len(unknown_users) < MAX_USER_INFO_FETCH:
+ self.fetch_individual_user_info(unknown_users)
+ else:
+ self.fetch_all_friend_info(user, unknown_users)
+
+
+REPLY_RE = re.compile(r'(@?)([a-zA-Z0-9_]+)([:, ])')
+
+class TwitterChannel(IrcChannel):
+ def __init__(self, proto, name):
+ IrcChannel.__init__(self, proto, name)
+
+ # REPLY_HISTORY_SIZE recent posts
+ self.recent_posts = []
+ # last post by each user ID
+ self.recent_by_user = {}
+
+ self.feeds = self._createFeeds()
+ for f in self.feeds:
+ f.addCallback(self.got_entry)
+ f.addErrback(self.refresh_error)
+
+ self.cmd_dialog = PasserdCommands(proto, self)
+ self.cmd_dialog.set_message_func(self.bot_msg)
+ self.cmd_dialog.set_cmd_prefix('!')
+
+ def _createFeeds(self):
+ raise NotImplementedError("_createFeeds not implemented on %s" % (self.name))
+
+ def userModeChar(self, u):
+ if u == self.proto.the_user:
+ return '@'
+ if u == self.proto.passerd_bot:
+ return '@'
+ return ''
+
+ def printEntry(self, entry):
+ u = self.proto.get_twitter_user(entry.user.id)
+ dbg("entry id: %r" % (entry.id))
+ text = entry.text
+ dbg('entry text: %r' % (text))
+ self.proto.send_text(u, self, text)
+
+ def _drop_one_old_entry(self):
+ #FIXME: Claudio reported a memory leak, I think it's here.
+
+ # remove from two lists:
+ # - recent_posts
+ # - last_post_by_user
+ drop = self.recent_posts.pop(0)
+ uid = int(drop.user.id)
+
+ # check if it is on the recent_by_user list, too:
+ urec = self.recent_by_user.get(uid, [])
+ if len(urec) > 0:
+ # we always remove entries from recent_by_user, so
+ # it should be the first on the list:
+ if int(urec[0].id) == int(drop.id):
+ urec.pop(0)
+
+ def _add_to_history(self, e):
+ self.recent_posts.append(e)
+ if self.recent_posts > REPLY_HISTORY_SIZE:
+ self._drop_one_old_entry()
+ uid = int(e.user.id)
+ self.recent_by_user.setdefault(uid, []).append(e)
+
+ def recent_post(self, nick, substring=None, min_age=None):
+ u = self.proto.global_twuser_cache.lookup_screen_name(nick)
+ if u is None:
+ # nickname not found
+ return None
+ uid = u.twitter_id
+ recent = self.recent_by_user.get(uid, [])
+ if len(recent) < 1:
+ return None
+ r = recent[-1]
+
+ if min_age:
+ #FIXME: add date parsing support to twitty-twister
+ #FIXME: show a list of alternatives to the user
+ # (how to do that for replies?)
+ t = rfc822.mktime_tz(rfc822.parsedate_tz(r.created_at))
+ if t > time.time() - min_age:
+ raise Exception("latest post by %s is too recent" % (nick))
+
+ return r
+
+ def last_post_id(self, nick):
+ r = self.recent_post(nick)
+ if r is None:
+ return None
+ return int(r.id)
+
+ def got_entry(self, e):
+ dbg("#twitter got_entry. id: %s", e.id)
+ u = e.user
+ self.proto.global_twuser_cache.got_api_user_info(u)
+ self._add_to_history(e)
+ self.printEntry(e)
+
+ def bot_msg(self, msg):
+ self.proto.send_privmsg(self.proto.passerd_bot, self, msg)
+
+ def bot_notice(self, msg):
+ self.proto.send_notice(self.proto.passerd_bot, self, msg)
+
+ def refresh_error(self, e):
+ dbg("#twitter refresh error")
+ #FIXME: stop showing repeated errors and just let the user know when service is back
+ if e.check(twisted.web.error.Error):
+ if str(e.value.status) == '503':
+ self.bot_notice("Look! A flying whale! -- %s" % (e.value))
+ return
+ remaining = self.proto.api.rate_limit_remaining
+ # note that it will not wait when remaining is None, which is
+ # intended
+ if e.value.status == '400' and remaining == 0:
+ self.wait_rate_limit()
+
+ self.bot_notice("error refreshing feed: %s" % (e.value))
+
+ def wait_rate_limit(self):
+ reset = time.ctime(self.proto.api.rate_limit_reset)
+ self.bot_msg('Ouch, the limit of requests per hour has been '
+ 'reached. I will wait until %s to start checking the '
+ 'Twitter timeline again.' % (reset))
+ self.bot_msg('You still can force the check by sending `!`. Also '
+ 'you can check the rate limit by sending `!rate`.')
+ self.proto.scheduler.wait_rate_limit()
+
+ def start(self):
+ for f in self.feeds:
+ f.start_refreshing()
+
+ def stop(self):
+ dbg("stopping refresh of %s channel", self.name)
+ for f in self.feeds:
+ f.stop_refreshing()
+
+ def beforeUserJoined(self, user):
+ if not self.proto.is_authenticated():
+ # use the same numeric that Freenode uses
+ raise ErrorReply(ERR_NEEDREGGEDNICK, self.name, ':You need to be identified to join that channel')
+
+ def afterUserJoined(self, user):
+ dbg("user %s has joined!" % (user.full_id()))
+ self.start()
+
+ def beforeUserLeft(self, user, reason):
+ self.stop()
+
+ def beforeUserQuit(self, user, reason):
+ self.stop()
+
+ def forceRefresh(self, last):
+ def doit(f):
+ f._refresh(last_id=last).addCallback(done)
+
+ def done(num_args):
+ if num_args == 0:
+ #FIXME: we are sending notice as if it was from the user, here
+ self.bot_msg('people are quiet...')
+
+ for f in self.feeds:
+ doit(f)
+
+ def commandReceived(self, cmd):
+ """Handle lines starting with '!'
+ """
+ if cmd == '' or cmd == '!':
+ last = None
+ if cmd == '!':
+ last = 0
+ return self.forceRefresh(last)
+
+ self.cmd_dialog.recv_message(cmd)
+
+ def messageReceived(self, sender, msg):
+ if msg.startswith('!'):
+ return self.commandReceived(msg[1:])
+
+ # careful mode?
+ if not self.proto.user_cfg_var_b('careful'):
+ # simply post directly
+ self.do_send_twitter_post(msg)
+ else:
+ # careful mode: check if it's a valid command
+ r,_ = self.cmd_dialog.try_msg(msg)
+ if not r:
+ self.bot_msg("I Can't Hear You! Use !tw to post, or disable careful mode using `!be brave`")
+
+ def ctcp_ACTION(self, arg):
+ dbg("ACTION: %r" % (arg))
+ #TODO: make the behavior of "/me" messages configurable
+ self.do_send_twitter_post('/me %s' % (arg))
+
+ def do_send_twitter_post(self, msg):
+ def doit():
+ return self.send_twitter_post(msg)
+
+ def done(*args):
+ #FIXME: remove this notice once we update the channel topic. we don't need it.
+ self.bot_notice("Twitter update posted!!")
+
+ def error(e):
+ if e.check(MessageTooLong):
+ # message-too-long errors
+ self.proto.send_reply(irc.ERR_CANNOTSENDTOCHAN, self.name, ':%s' % (str(e.value)))
+ return
+ self.bot_msg("%s: error while posting: %s" % (self.proto.the_user.nick, e.value))
+
+ return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
+
+ def _add_in_reply_to(self, msg, args):
+ m = REPLY_RE.match(msg)
+ if m is None:
+ return msg
+
+ at = m.group(1)
+ nick = m.group(2)
+ end = m.group(3)
+
+ # just "username " at the beginning won't be considered
+ # a reply. User must use either "@username", "username:", or "username,"
+ if at != '@' and end == ' ':
+ return msg
+
+ #TODO: have some timing check, just in case the
+ # last post is too recent to be replied to (e.g. 0.1 second ago)
+
+ last_post = self.last_post_id(nick)
+ if last_post:
+ args['in_reply_to_status_id'] = str(last_post)
+ if not msg.startswith("@"):
+ msg = "@"+msg
+
+ #TODO: add "@" for users that are on the channel, but haven't posted recently?
+
+ return msg
+
+ def send_twitter_post(self, msg):
+ args = {}
+ msg = self._add_in_reply_to(msg, args)
+ dbg("msg: %r. args: %r", msg, args)
+ return self.proto.send_twitter_post(msg, args)
+
+
+class FriendlistMixIn:
+ """An extension to TwitterChannel to handle list of friends/members"""
+
+ def _friendList(self, delegate, params={}, page_delegate=None):
+ raise NotImplementedError("_friendList not implemented")
+
+ def _handleUserRefs(self, userrefs):
+ users = []
+ for u in userrefs:
+ users.append(self._user_object(u))
+ return users
+
+ def _fetch_user_info(self, users):
+ """Can be used to trigger fetching of complete user info, if needed"""
+ pass
+
+ def _user_object(self, tu):
+ """Can be overriden when get_friend_list() contains only user IDs"""
+ self.proto.global_twuser_cache.got_api_user_info(tu)
+ return self.proto.get_twitter_user(tu.id, watch=True)
+
+ def _get_friend_list(self):
+ d = defer.Deferred()
+ friends = set()
+
+ def got_page(next, prev):
+ self.proto.dbg("%s user list: got page: %s<-%s" % (self.name, next, prev))
+ self.proto.dbg("%s friends so far: %d" % (self.name, len(friends)))
+ if not next or next == "0":
+ self.proto.dbg("%s user list: this was the last page" % (self.name))
+ d.callback(friends)
+ return
+ doit(next)
+
+ def doit(cursor):
+ params = {"cursor": cursor}
+ self._friendList(got_friend, params, page_delegate=got_page).addErrback(d.errback)
+
+ def got_friend(ref):
+ friends.add(ref)
+
+ self.proto.dbg("I will fetch the list of users for %s" % (self.name))
+ doit("-1")
+ return d
+
+ def list_members(self):
+ #FIXME: return a empty (or almost-empty) list, if the user is not authenticated yet
+ d = defer.Deferred()
+ ids = []
+
+ def doit():
+ self._get_friend_list().addCallbacks(got_list, d.errback)
+
+ def got_list(userrefs):
+ dbg("Finished getting friend IDs for %s", self.name)
+ users = self._handleUserRefs(userrefs)
+
+ #FIXME: call _fetch_user_info() on JOIN time, not on list_members() time
+ self._fetch_user_info(users)
+
+ #FIXME: 1) show the_user only if it really has joined the channel
+ #FIXME: 2) check if the_user is on the list used as input, and don't include it,
+ # to avoid duplicate entries on the list
+ users = [self.proto.the_user, self.proto.passerd_bot]+users
+ d.callback(users)
+
+ doit()
+ return d
+
+class FriendIDsMixIn:
+ """MixIn that can be used when the friend list is just a list of IDs"""
+ def _user_object(self, id):
+ return self.proto.get_twitter_user(int(id), watch=True)
+
+
+#TODO: make mentions appear on #twitter, if configured to do so
+
+class MainChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
+ """The #twitter channel"""
+
+ def topic(self):
+ return "Passerd -- Twitter home timeline channel"
+
+ def _createFeeds(self):
+ return [HomeTimelineFeed(self.proto)]
+
+ def _friendList(self, delegate, params={}, page_delegate=None):
+ return self.proto.api.friends_ids(delegate, str(self.proto.authenticated_user.screen_name),
+ params=params, page_delegate=page_delegate)
+
+ def inviteUser(self, nickname):
+ #TODO: send a better error message if user is already being followed
+
+ user_ids = []
+ def doit():
+ self.proto.api.follow_user(nickname, got_user_info).addCallbacks(done, error)
+ self.proto.send_reply(irc.RPL_INVITING, nickname, self.name)
+
+ def got_user_info(u):
+ user_ids.append(u.id)
+ self.proto.global_twuser_cache.got_api_user_info(u)
+ u = self.proto.get_twitter_user(u.id, watch=True)
+ self.notifyJoin(u)
+
+ def done(*args):
+ if not user_ids:
+ self.proto.notice("follow: got reply but no user info!?")
+ return
+ self.proto.dbg("follow request for %s done" % (nickname))
+
+ def error(e):
+ self.proto.notice('error when trying to follow user: %s' % (e.value))
+ self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
+
+ doit()
+
+ def kickUser(self, sender, nickname):
+ #TODO: send a better error message if the user is not being followed
+
+ user_ids = []
+ def doit():
+ self.proto.api.unfollow_user(nickname, got_user_info).addCallbacks(done, error)
+
+ def got_user_info(u):
+ user_ids.append(u.id)
+ self.proto.global_twuser_cache.got_api_user_info(u)
+ u = self.proto.get_twitter_user(u.id)
+ self.notifyKick(sender, u)
+
+ def done(*args):
+ if not user_ids:
+ self.proto.notice("unfollow: got reply but no user info!?")
+ return
+ self.proto.dbg("unfollow request for %s done" % (nickname))
+
+ def error(e):
+ self.proto.notice('error when trying to unfollow user: %s' % (e.value))
+ self.proto.send_reply(irc.ERR_UNAVAILRESOURCE, nickname, ':Nick/channel is temporarily unavailable')
+
+ doit()
+
+ def _fetch_user_info(self, users):
+ self.proto.dbg("Now will fetch user info")
+ return self.proto.twitter_users.fetch_friend_info(str(self.proto.authenticated_user.screen_name), users)
+
+
+class MentionsChannel(TwitterChannel):
+ """The #mentions channel"""
+ def topic(self):
+ return "Passerd -- @mentions"
+
+ def _createFeeds(self):
+ return [MentionsFeed(self.proto)]
+
+
+class ListChannel(FriendlistMixIn, TwitterChannel):
+
+ def __init__(self, proto, list_user, list_name):
+ self.list_user = list_user
+ self.list_name = list_name
+ TwitterChannel.__init__(self, proto, self._channelName())
+
+ def _createFeeds(self):
+ return [ListTimelineFeed(self.proto, self.list_user, self.list_name)]
+
+ def _channelName(self):
+ return "#@%s/%s" % (self.list_user, self.list_name)
+
+ def topic(self):
+ return "Passerd -- @%s/%s" % (self.list_user, self.list_name)
+
+ def _friendList(self, delegate, params={}, page_delegate=None):
+ return self.proto.api.list_members(delegate, self.list_user,
+ self.list_name, params=params, page_delegate=page_delegate)
+
+
+class UserChannel(FriendIDsMixIn, FriendlistMixIn, TwitterChannel):
+
+ def __init__(self, proto, user):
+ self.user = user
+ TwitterChannel.__init__(self, proto, self._channelName())
+
+ def _channelName(self):
+ return "#@%s" % (self.user)
+
+ def _createFeeds(self):
+ return [UserTimelineFeed(self.proto, self.user)]
+
+ def topic(self):
+ return "User timeline -- %s" % (self.user)
+
+ def _friendList(self, delegate, params={}, page_delegate=None):
+ #TODO: include the user on the list of channel members, too
+ # (the user whose timeline is being followed, not the Passerd
+ # authenticated user)
+ return self.proto.api.friends_ids(delegate, self.user, params=params,
+ page_delegate=page_delegate)
+
+ def _fetch_user_info(self, users):
+ return self.proto.twitter_users.fetch_friend_info(self.user, users)
+
+
+class ProtoDialog:
+ """A simple mixin to set a 'proto' attribute on dialog_init()"""
+ def dialog_init(self, proto, *args, **kwargs):
+ self.proto = proto
+
+
+class ConfigCommands(ProtoDialog, CommandDialog):
+ shorthelp_set = 'Change a config option'
+ def command_set(self, args):
+ #FIXME: implement me
+ self.message('Sorry, this is not implemented yet')
+
+
+class BeCommands(CommandDialog):
+ """The 'be' command handler"""
+ def dialog_init(self, proto, *args, **kwargs):
+ self.proto = proto
+ self.add_alias('paranoid', 'careful')
+
+ help_header = 'Shortcut for many common config settings'
+ def command_happy(self, args):
+ self.message(':)')
+
+ def unknown_command(self, cmd, args):
+ self.message('Be what?')
+
+ shorthelp_careful = "Don't post channel messages to Twitter directly"
+ def command_careful(self, args):
+ self.message('I will. From now on, Twitter updates can '
+ 'only be sent with `%stw <message>`' % (self.parent.cmd_prefix))
+ self.message('You can disable this setting using: `%sbe brave`' % (self.parent.cmd_prefix))
+ self.proto.set_user_cfg_var('careful', True)
+
+ shorthelp_brave = "Post channel messages to Twitter directly"
+ def command_brave(self, args):
+ self.message('So you are! Channel messages will be posted directly to Twitter')
+ self.proto.set_user_cfg_var('careful', False)
+
+ def show_help(self, prefix, args):
+ self.message(self.parent.cmd_syntax_str('be', '<flag>'))
+ self.message("Available flags:")
+ for imp,t in self.help_topics():
+ self.message(" %s - %s" % (t, self._short_help(t)))
+
+
+class PasserdCommands(CommandHelpMixin, CommandDialog):
+ def dialog_init(self, proto, chan=None, *args, **kwargs):
+ self.proto = proto
+ self.chan = chan
+ #self.add_subdialog('config', ConfigCommands(proto), 'Query and change config settings')
+ self.add_subdialog('be', BeCommands(proto, parent=self))
+
+ self.add_alias('s', 'post')
+ self.add_alias('twit', 'post')
+ self.add_alias('tw', 'post')
+ self.add_alias('update', 'post')
+
+ shorthelp_login = 'Log into Passerd/Twitter'
+ def help_login(self, args):
+ self.cmd_syntax('login', 'twitter-login password')
+ self.message("If you don't have an account yet, join the #new-user-setup channel")
+
+ def command_login(self, args):
+ if not args:
+ return self.help_login(None)
+
+ parts = args.split(' ', 1)
+ if len(parts) <> 2:
+ return self.help_login(None)
+
+ login,password = parts
+
+ def doit():
+ self.proto._do_auth(login, password).addCallback(done).addErrback(error)
+
+ def done(u):
+ self.message("Welcome to Passerd, %s" % (u.screen_name))
+ self.proto.welcome_user()
+
+ def error(e):
+ self.message("Error while authenticating: %s" % (e.value))
+ if e.check(MissingOAuthRegistration):
+ self.proto.redirect_to_new_user_setup()
+
+ doit()
+
+ shorthelp_gc = 'Run Python garbage collection (debugging/testing command)'
+ importance_gc = dialogs.CMD_IMP_DEBUGGING
+ def command_gc(self, args):
+ self.message("Object counts: %r" % (gc.get_count(),))
+ r = gc.collect()
+ self.message("Garbage collection run. %d objects freed" % (r))
+ self.message("New object counts: %r" % (gc.get_count(),))
+
+ shorthelp_rate = 'Show Twitter API rate-limit info'
+ importance_rate = dialogs.CMD_IMP_ADVANCED
+ def command_rate(self, args):
+ api = self.proto.api
+ if api is None:
+ self.message('You are not logged in. No rate limit info is available')
+ return
+ self.message('Rate limit: %s. remaining: %s. reset: %s' % (api.rate_limit_limit, api.rate_limit_remaining, time.ctime(api.rate_limit_reset)))
+
+ shorthelp_post = 'Post an update to Twitter'
+ def help_post(self, args):
+ self.cmd_syntax('post', 'text')
+ self.message("Post an update to Twitter")
+
+ def command_post(self, args):
+ if not args:
+ self.help_post(None)
+ return
+
+ def doit():
+ # if there is an associated channel, use it as context for the
+ # Twitter post. Otherwise, just use the general send_twitter_post()
+ # method
+ ch = self.chan
+ if ch:
+ d = ch.send_twitter_post(args)
+ else:
+ d = self.proto.send_twitter_post(args)
+ return d
+
+ def done(*args):
+ self.message("Done. Twitter update posted")
+
+ def error(e):
+ self.message("Error while posting: %s" % (e.value))
+
+ return defer.maybeDeferred(doit).addCallback(done).addErrback(error)
+
+
+
+
+
+class PasserdBot(IrcUser):
+ """The Passerd IRC bot, that is used for Passerd messages on the channel"""
+ def __init__(self, proto, nick):
+ IrcUser.__init__(self, proto)
+ self.proto = proto
+ self.nick = nick
+
+ self.dialog = d = PasserdCommands(proto, None)
+ attach_dialog_to_bot(d, proto, proto.the_user, self)
+
+ real_name = 'Passerd Bot'
+ username = 'passerd'
+ hostname = MYHOST
+
+
+class NewUserDialog(ProtoDialog, Dialog):
+ def begin(self, *args):
+ def bm(msg):
+ self.message(msg)
+
+ def welcome():
+ bm('Welcome!')
+ bm('On this channel, we will set up an account for you.')
+ bm("We will use the OAuth authentication method on Twitter,")
+ bm("so you don't even need to give me your Twitter password. :)")
+ bm("Please tell me when you are ready, and we'll start the process")
+ bm("Are you ready? (yes/no)")
+ self.wait_for(r'^ *(y|yes|ok|start|restart) *$', start)
+ self.wait_for(r'^ *n|no', lambda *a: bm("no problem..."))
+
+ def ask_restart():
+ bm("Do you want to restart?")
+ self.wait_for('^ *y|yes', start)
+
+ def start(msg, m):
+ bm("OK, let's do it:")
+ bm("(Note: at any moment, you can type 'restart', and the process will be restarted)")
+ consumer = OAuthClient(url_cb=lambda url: show_url(consumer, url), progress_cb=show_progress)
+ consumer.get_oauth_token().addErrback(error_get_token)
+
+ def error_get_token(e):
+ bm("Error while trying to get an OAuth token: %s" % (e.value))
+ ask_restart()
+
+ def show_progress(msg):
+ bm("oauth progress: %s" % (msg))
+
+ def show_url(consumer, url):
+ bm("Now, go to: %s" % (url))
+ bm("After authorizing Passerd to access your account, you'll get a PIN")
+ bm("Please paste the PIN here")
+ self.wait_for('[0-9][0-9][0-9]+', lambda msg,m: got_pin(consumer, m))
+
+ def got_pin(consumer, m):
+ pin = m.group(0)
+ bm("Got it. Thanks!")
+ bm("PIN: %r" % (pin))
+ consumer.got_verifier(pin).addCallback(pin_worked).addErrback(pin_error)
+
+ def pin_error(e):
+ bm("The PIN didn't work. I got this error: %s" % (e.value))
+ ask_restart()
+
+ def pin_worked(token):
+ bm('The PIN worked!')
+ bm("Now I will check if I can access your account...")
+ self.proto.test_oauth_token(token).addCallback(token_works).addErrback(token_error)
+
+ def token_error(e):
+ bm("The OAuth authentication didn't work. Sorry :(")
+ bm("Error message: %s" % (e.value))
+ ask_restart()
+
+ def token_works(args):
+ token,api,u = args
+ bm("OAuth authentication worked!")
+
+ # change the user nickname to Twitter screen_name
+ nick = str(u.screen_name)
+ self.proto.the_user.force_nick(nick)
+ bm("Welcome to Passerd, %s" % (nick))
+
+ self.user_data = self.proto.set_user_token(u, token)
+ self.twitter_user = u
+ bm("Now Passerd can post to your account, but you still need to authenticate when connecting to Passerd")
+
+ bm("You have two authentication options:")
+ bm("1) Local password (recommended): Set a password just for Passerd, then you'll never need to reveal your Twitter password")
+ bm("2) Twitter password: Just use your Twitter password when connecting to Passerd")
+ bm("Which option do you want to use? (twitter/local)")
+ self.wait_for(r'^ *loc|^ *1 *$', setup_password)
+ self.wait_for(r'^ *twi|^ *2 *$', all_set)
+
+ def all_set(msg,m):
+ bm("OK, so you are all set")
+ bye_twpass()
+ self.wait_for('.*', bye_twpass)
+
+ def bye_twpass(*args):
+ bm("Just reconnect to Passerd using your Twitter password,")
+ bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
+
+ def setup_password(msg,m):
+ bm("OK. Send your password as a message to the channel, and I will set it")
+ bm("Alternatively, I can generate a random password for you, just type 'generate' and I will do it")
+ bm("What will be your password?")
+ self.wait_for('.+', got_password)
+ self.wait_for('^ *generate *$', gen_password)
+
+ def got_password(msg,m):
+ pw = msg
+ if len(pw) < 6:
+ bm("This is a short password! Are you sure you want to use it?")
+ self.wait_for('.*', setup_password)
+ self.wait_for('^ *y|yes', lambda msg,m: set_password(pw))
+ else:
+ set_password(pw)
+
+ def gen_password(msg,m):
+ length = 16
+ chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
+ pw = ''.join([random.choice(chars) for i in range(length)])
+ set_password(pw)
+
+ def set_password(pw):
+ self.proto.set_user_password(self.user_data, pw)
+ self.password = pw
+ bm("Password set to: %s" % (pw))
+ bye_pwset()
+ self.wait_for('.*', bye_pwset)
+
+ def bye_pwset(*args):
+ bm("Just reconnect to Passerd using your Passerd password: %s" % (self.password))
+ bm("and your Twitter username (%s) as nickname" % (self.twitter_user.screen_name))
+
+ welcome()
+
+class UserSetupChannel(IrcChannel):
+ def __init__(self, proto, name):
+ IrcChannel.__init__(self, proto, name)
+
+ self.dialog = d = NewUserDialog(proto)
+ attach_dialog_to_channel(d, self, self.proto.passerd_bot)
+
+ # start the dialog automatically if any message is received on
+ # the channel:
+ d.wait_for('.*', lambda *a: d.begin())
+
+ def list_members(self):
+ return [self.proto.the_user, self.proto.passerd_bot]
+
+ def afterUserJoined(self, who):
+ self.dialog.begin()
+
+
+def requires_auth(fn):
+ """A decorator for a generic authentication check before handling certain commands
+
+ This function should die soon. Having command-specific handling of
+ non-authenticated users would be better. Then we could make the commands
+ work as if everything is OK on the server, but without any real Twitter
+ user or channels available.
+ """
+ def wrapper(self, *args, **kwargs):
+ if not self.is_authenticated():
+ raise ErrorReply(irc.ERR_NOPRIVILEGES, ':Sorry, you must authenticate first (%s command)' % (fn.__name__))
+ return fn(self, *args, **kwargs)
+ return wrapper
+
+
+class PasserdProtocol(IRC):
+ def connectionMade(self):
+ self.quit_sent = False
+
+ IRC.connectionMade(self)
+ pinfo("Got connection from %s", self.hostname)
+
+ self.data = self.factory.data
+
+ #FIXME: use real names
+ self.myhost = MYHOST
+ self.password = None
+
+
+ # fields that will be available only after authentication:
+ self.api = None
+ self.scheduler = None
+ self.authenticated_user = None
+ self.user_data = None
+ self.got_user = False
+ self.got_nick = False
+
+ self.global_twuser_cache = self.factory.global_twuser_cache
+ self.twitter_users = TwitterIrcUserCache(self, self.global_twuser_cache)
+
+
+ self.my_irc_server = IrcServer(self, self.myhost)
+
+ u = self.the_user = IrcUser(self)
+ u.nick = 'guest'
+ u.username = 'guest'
+ u.hostname = self.hostname
+ u.real_name = 'Unidentified User'
+
+ self.passerd_bot = PasserdBot(self, 'passerd-bot')
+
+ self.users = [self.the_user, self.passerd_bot]
+
+ predef_chans = [MainChannel(self, '#twitter'), MentionsChannel(self, '#mentions'), UserSetupChannel(self, '#new-user-setup')]
+
+ #TODO: keep a list of the fixed and joined channels,
+ # but use short-lived channel objects for other channel-query
+ # commands
+ self.channels = dict([(c.name, c) for c in predef_chans])
+
+ #FIXME: make the auto-join optional:
+ self.autojoin_channels = ['#twitter', '#mentions']
+ #FIXME: make joined_channels a more efficient list of channels
+ self.joined_channels = []
+
+ self.dm_feed = DirectMessagesFeed(self)
+ self.dm_feed.addCallback(self.gotDirectMessage)
+ self.dm_feed.addErrback(self.dmError)
+
+ dbg("Got new client")
+
+ def welcome_user(self):
+ for ch in self.autojoin_channels:
+ self.join_cname(ch)
+ self.dm_feed.start_refreshing()
+ self.scheduler.start()
+
+ def welcome_anonymous(self):
+ self.notice("Welcome, anonymous user!")
+ self.notice("If you already have a Passerd account set up, identify yourself with the command: /MSG PASSERD-BOT LOGIN username password")
+ self.notice("If your account is not set up yet, please join the #new-user-setup channel to set up your account")
+
+
+ def redirect_to_new_user_setup(self):
+ """Send the user to the OAuth user setup channel"""
+ self.send_notice(self.passerd_bot, self.the_user, "Please join #new-user-setup to set up your account")
+ self.join_cname('#new-user-setup')
+
+ def _set_scheduler(self, scheduler):
+ if self.scheduler:
+ self.scheduler.stop()
+ self.scheduler = None
+ self.scheduler = scheduler
+
+ def _userQuit(self, reason):
+ self.dm_feed.stop_refreshing()
+ for ch in self.joined_channels:
+ self.leave_channel(ch, reason)
+ self._set_scheduler(None)
+ self.quit_sent = True
+
+ def userQuit(self, reason):
+ if not self.quit_sent:
+ self._userQuit(reason)
+ self.quit_sent = True
+
+ def gotDirectMessage(self, msg):
+ self.global_twuser_cache.got_api_user_info(msg.sender)
+ sender = self.get_twitter_user(msg.sender.id, watch=True)
+ self.send_text(sender, self.the_user, msg.text)
+
+ def dmError(self, e):
+ self.notice("Error pulling Direct Messages: %s" % (e.value))
+
+ def send_text(self, sender, target, text):
+ # security:
+ text = full_entity_decode(text)
+ dbg('entities decoded: %r' % (text))
+ text = text.replace('\r', '\n')
+
+ first = True
+ # handle newlines as multiple messages
+ for line in text.split('\n'):
+ if not line:
+ continue
+ if not first:
+ #TODO: find a better way to indicate multi-line posts
+ line = '[...] '+line
+ self.send_privmsg(sender, target, line.encode(IRC_ENCODING))
+ first = False
+
+ def connectionLost(self, reason):
+ pinfo("connection to %s lost: %s", self.hostname, reason.value)
+ self.userQuit(str(reason))
+ IRC.connectionLost(self, reason)
+
+ def user_var(self, var):
+ """Get any user var (config or internal feed state)"""
+ return self.data.get_var(self.user_data, var)
+
+ def set_user_var(self, var, value):
+ return self.data.set_var(self.user_data, var, value)
+
+ def set_user_cfg_var(self, var, value):
+ """Set an user variable
+
+ Note that all vars are strings, and other types
+ are converted before setting the variables.
+ """
+
+ # convert some data types to string
+ t = type(value)
+ if t is bool:
+ if value: value = '1'
+ else: value = '0'
+
+ vname = 'config:%s' % (var)
+ return self.set_user_var(vname, value)
+
+ def user_cfg_var_b(self, var):
+ vname = 'config:%s' % (var)
+ v = self.user_var(vname)
+ true_values = ['true', 't', '1', 'y', 'yes']
+ if v and v in true_values:
+ return True
+ else:
+ return False
+
+ def get_twitter_user(self, id, watch=False):
+ u = self.twitter_users.get_user(id)
+ if watch:
+ self.twitter_users.watch_user_id(id)
+ return u
+
+
+ def dbg(self, msg):
+ self.notice(msg)
+
+
+ ## overwrite some methods of the twisted.words IRC class:
+
+ def sendMessage(self, *args, **kwargs):
+ dbg("sending message: %r %r" % (args, kwargs))
+ return IRC.sendMessage(self, *args, **kwargs)
+
+ def sendLine(self, *args, **kwargs):
+ dbg("sending line: %r %r" % (args, kwargs))
+ return IRC.sendLine(self, *args, **kwargs)
+
+ def _handleCommand(self, command, prefix, params):
+ """Like IRC.handleCommand, but with no exception handling"""
+ method = getattr(self, "irc_%s" % (command), None)
+ if method is not None:
+ return method(prefix, params)
+ else:
+ return self.irc_unknown(prefix, command, params)
+
+ def handleCommand(self, *args, **kwargs):
+ def doit():
+ dbg("got command: %r %r" % (args, kwargs))
+ d = defer.maybeDeferred(self._handleCommand, *args, **kwargs)
+ d.addErrback(error)
+
+ def error(e):
+ ex = e.value
+
+ # ErrorReply exceptions are special: they generate a IRC error reply
+ if e.check(ErrorReply):
+ self.send_reply(ex.command, *ex.args)
+ return
+
+ perror("Got an exception: %s", e.getErrorMessage())
+ logger.exception(ex)
+ self.notice("*** An internal error has occurred. Sorry. -- %s: %s" % (e.type, e.getErrorMessage()))
+
+ doit()
+
+ def send_reply(self, cmd, *params, **kwargs):
+ return self.server_message(cmd, self.the_user.nick, *params, **kwargs)
+
+ def send_message(self, sender, *params):
+ return self.sendMessage(*params, prefix=sender.full_id())
+
+ def server_message(self, cmd, *params):
+ return self.send_message(self.my_irc_server, cmd, *params)
+
+ def server_notice(self, target, msg):
+ self.send_notice(self.my_irc_server, target, msg)
+
+ def send_notice(self, sender, target, msg):
+ self.send_message(sender, 'NOTICE', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
+
+ def send_privmsg(self, sender, target, msg):
+ self.send_message(sender, 'PRIVMSG', target.target_name(), ':%s' % (to_str(msg, IRC_ENCODING)))
+
+ def notice(self, msg):
+ self.server_notice(self.the_user, msg)
+
+ def join_channel(self, chan):
+ if not (chan in self.joined_channels):
+ chan.userJoined(self.the_user)
+ self.joined_channels.append(chan)
+
+ def leave_channel(self, chan, reason):
+ if chan in self.joined_channels:
+ chan.userLeft(self.the_user, reason)
+ self.joined_channels.remove(chan)
+
+ def leave_cname(self, cname, reason):
+ channel = self.get_channel(cname)
+ if channel is not None:
+ self.leave_channel(channel, reason)
+
+ def join_cname(self, cname):
+ channel = self.get_channel(cname)
+ if channel is None:
+ channel = self.create_channel(cname)
+ dbg("get_channel %r" % (channel))
+ if channel is not None:
+ self.join_channel(channel)
+
+ def irc_PING(self, prefix, args):
+ self.server_message('PONG', args[0])
+
+ def irc_JOIN(self, prefix, params):
+ dbg("JOIN! %r %r" % (prefix, params))
+ cnames = params[0]
+ for c in cnames.split(','):
+ self.join_cname(c)
+
+ def irc_PART(self, prefix, params):
+ chans = params[0]
+ reason = None
+ if len(params) > 1:
+ reason = params[1]
+ for c in chans.split(','):
+ self.leave_cname(c, reason)
+
+ @requires_auth
+ def irc_INVITE(self, prefix, params):
+ nick = params[0]
+ cname = params[1]
+ chan = self.get_channel(cname)
+ if chan is not None:
+ chan.inviteUser(nick)
+
+ @requires_auth
+ def irc_KICK(self, prefix, params):
+ chans = params[0].split(',')
+ users = params[1].split(',')
+ for cname in chans:
+ chan = self.get_channel(cname)
+ if chan is not None:
+ chan.kickUsers(self.the_user, users)
+
+ def irc_QUIT(self, pref, params):
+ reason = None
+ if len(params) > 0:
+ reason = params[0]
+
+ self.userQuit(reason)
+ self.sendMessage('ERROR', ':Quit command received')
+ self.transport.loseConnection()
+
+ def irc_WHO(self, p, args):
+ for m in self.who_matches(args[0]):
+ self.send_reply(irc.RPL_WHOREPLY, *m)
+ self.send_reply(irc.RPL_ENDOFWHO, ':End of WHO list')
+
+ @requires_auth
+ def irc_WHOIS(self, p, args):
+ if len(args) > 2:
+ # invalid command
+ return
+ elif len(args) == 2:
+ # ignore server part
+ masks = args[1]
+ else:
+ masks = args[0]
+
+ masks = masks.split(',')
+ for m in masks:
+ self.whois_mask(m)
+
+ def irc_MODE(self, p, args):
+ tname = args[0]
+ target = self.get_target(tname)
+ if target is None:
+ self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
+ return
+ target.modeRequest(self.the_user, args)
+
+ def irc_USERHOST(self, p, args):
+ if len(args) > 5:
+ args = args[:5]
+ r = []
+ for a in args:
+ u = self.get_user(a)
+ if u:
+ r.append('%s=%s%s' % (u.nick, u.away_char(), u.userhost()))
+ if r:
+ self.send_reply(irc.RPL_USERHOST, ':%s' % (' '.join(r)))
+
+ def irc_PRIVMSG(self, prefix, args):
+ tname = args[0]
+ msg = args[1]
+
+ sender = self.the_user
+ target = self.get_target(tname)
+ if target is None:
+ self.send_reply(irc.ERR_NOSUCHNICK, tname, ':No such nick/channel')
+ return
+
+ # CTCP data:
+ if msg[0]==irc.X_DELIM:
+ m = irc.ctcpExtract(msg)
+ if m['extended']:
+ target.ctcpQueryReceived(sender, m['extended'])
+ # I won't handle the m['normal'] part. I don't trust this level of
+ # crazyness on the protocol
+ else:
+ target.messageReceived(sender, msg)
+
+ def irc_unknown(self, prefix, cmd, params):
+ dbg("CMD! %r %r %r" % (prefix, cmd, params))
+ self.dbg("Got unknown command: %r %r %r" % (prefix, cmd, params))
+ self.send_reply(irc.ERR_UNKNOWNCOMMAND, cmd, ':Unknown command')
+
+ ### authentication code:
+
+ def check_credentials(self, api, method):
+ d = defer.Deferred()
+
+ ok = []
+ def doit():
+ self.notice("Checking Twitter credentials using %s..." % (method))
+ api.verify_credentials(got_user).addCallback(done).addErrback(error)
+
+ def got_user(u):
+ self.notice("%s authentication OK! Your Twitter user ID: %s. screen_name: %s" % (method, u.id, u.screen_name))
+ ok.append(u)
+
+ def done(*args):
+ if not ok:
+ d.errback(Exception("I got a reply from the Twitter server but no user info. This shouldn't have happened. :("))
+ else:
+ d.callback(ok[0])
+
+ def error(e):
+ d.errback(e)
+
+ doit()
+ return d
+
+ def is_authenticated(self):
+ return (self.authenticated_user is not None)
+
+ def _send_welcome_replies(self):
+ """Send standard IRC numeric replies after registration"""
+ self.send_reply(irc.RPL_WELCOME, ":Welcome to the Internet Relay Network %s!%s@%s" % (self.the_user.nick, self.the_user.username, self.the_user.hostname))
+ self.send_reply(irc.RPL_YOURHOST, ":Your host is %s, running version %s" % (self.myhost, VERSION))
+ self.send_reply(irc.RPL_CREATED, ":This server was created by the Flying Spaghetti Monster")
+ self.send_reply(irc.RPL_MYINFO, self.myhost, VERSION, SUPPORTED_USER_MODES, SUPPORTED_CHAN_MODES)
+
+ #TODO: send a MOTD with useful information
+
+
+ def set_authenticated_user(self, u):
+ self.authenticated_user = u
+ self.user_data = self.data.get_user(int(u.id), u.screen_name, create=True)
+
+
+ def _twitter_api(self, *args, **kwargs):
+ """Create a Twitter API object"""
+ api = Twitter(*args, timeout=self.factory.opts.api_timeout, **kwargs)
+ #FIXME; patch twitty-twister to accept agent=foobar
+ api.agent = MYAGENT
+ return api
+
+ def _check_basic_auth(self, username, password):
+ """Run verify_credentials API call using basic auth
+
+ On success, pass a (api,auth_user) pair to the deferred callback
+ """
+ api = self._twitter_api(username, password, base_url=BASE_URL) #, client_info=CLIENT_INFO)
+ def doit():
+ return self.check_credentials(api, 'password').addCallback(done)
+
+ def done(u):
+ return (api, u)
+
+ return doit()
+
+ def test_oauth_token(self, token):
+ """Check of the oauth token works
+
+ On success, pass a (token, api, auth_user) pair to the deferred callback
+ """
+ api = self._twitter_api(consumer=oauth_consumer, token=token)
+ def doit():
+ return self.check_credentials(api, 'OAuth').addCallback(done)
+
+ def done(u):
+ return (token, api, u)
+
+ return doit()
+
+ def set_user_token(self, u, token):
+ udata = self.data.get_user(int(u.id), u.screen_name, create=True)
+ udata.oauth_token = token.key
+ udata.oauth_token_secret = token.secret
+ self.data.commit()
+ return udata
+
+ def set_user_password(self, udata, pw):
+ udata.set_password(pw)
+ assert udata.password_valid(pw) # sanity check
+ self.data.commit()
+
+ def _do_auth(self, username, password):
+ """Authenticate username and password
+ """
+ d = defer.Deferred()
+ def try_local_password():
+ """Try to validate the password as a Passerd-only password"""
+ udata = self.data.get_user(None, username)
+ if udata is None:
+ return None
+ if not udata.password_valid(password):
+ return None
+
+ return udata
+
+ def doit():
+ # first, try the passerd-only passowrd:
+ udata = try_local_password()
+ if udata is not None:
+ self.notice("Your local Passerd password is valid")
+ return got_user(udata)
+
+ # if Passerd password doesn't work, try Twitter basic auth password:
+ self._check_basic_auth(username, password).addCallback(basic_auth_ok).addErrback(d.errback)
+
+ def basic_auth_ok(args):
+ api,u = args
+ udata = self.data.get_user(int(u.id), u.screen_name)
+ if udata is None:
+ return no_oauth_setup()
+ if not udata.oauth_token or not udata.oauth_token_secret:
+ return no_oauth_setup()
+
+ got_user(udata)
+
+ def no_oauth_setup():
+ d.errback(MissingOAuthRegistration("OAuth registration not done yet"))
+
+ def got_user(udata):
+ token = oauth.OAuthToken(udata.oauth_token, udata.oauth_token_secret)
+ self.test_oauth_token(token).addCallbacks(oauth_works, oauth_error).addErrback(d.errback)
+
+ def oauth_works(args):
+ token,api,u = args
+
+ # authentication worked. set up variables:
+ self.api = api
+ self._set_scheduler(ApiScheduler(api))
+ self.set_authenticated_user(u)
+ d.callback(u)
+
+ def oauth_error(e):
+ if e.check(twisted.web.error.Error):
+ if str(e.value.status) == '401':
+ d.errback(MissingOAuthRegistration("OAuth token rejected by Twitter"))
+ return
+
+ d.errback(e)
+
+ doit()
+ return d
+
+ def _early_auth(self):
+ """Run early password-authentication
+
+ This should be used only on the early registration stages.
+ """
+ def doit():
+ self._do_auth(self.the_user.nick, self.password).addCallback(auth_ok).addErrback(error)
+
+ def auth_ok(u):
+ self._send_welcome_replies()
+ self.welcome_user()
+
+ def error(e):
+ if e.check(MissingOAuthRegistration):
+ self.notice("Error while authenticating - %s" % (e.value))
+ self.notice("Your connection will be considered anonymous, by now")
+ self._send_welcome_replies()
+ self.welcome_anonymous()
+ self.redirect_to_new_user_setup()
+ else:
+ self.send_reply(irc.ERR_PASSWDMISMATCH, ":Error while authenticating - %s" % (e.value))
+ # on the other cases, drop the connection
+ self.transport.loseConnection()
+
+
+ doit()
+
+ def try_early_auth(self):
+ """Try password-authentication on Twitter, if already got enough info"""
+ if self.api is not None:
+ # already set up authentication
+ return
+
+ if self.password is not None and self.got_user and self.got_nick:
+ self._early_auth()
+
+ def irc_NICK(self, prefix, params):
+ dbg("NICK %r" % (params))
+ nick = params[0]
+ if self.got_nick:
+ self.the_user.force_nick(nick)
+ else:
+ self.the_user.nick = nick
+ self.got_nick = True
+ self.try_early_auth()
+
+ def irc_PASS(self, p, args):
+ self.password = args[0]
+ self.try_early_auth()
+
+ def irc_USER(self, prefix, params):
+ dbg("USER %r" % (params))
+ username,_,_,real_name = params[0:4]
+ self.the_user.username = username
+ self.the_user.real_name = real_name
+ self.got_user = True
+
+ #TODO: accept connections without password, and allow a nickserv-style method of authentication
+
+ if self.password is not None:
+ # password set, try early authentication
+ self.try_early_auth()
+ else:
+ # not-authenticated-yet connection
+ self._send_welcome_replies()
+ self.welcome_anonymous()
+
+
+ def send_twitter_post(self, msg, args={}):
+ msg = try_unicode(msg, IRC_ENCODING)
+ if len(msg) > LENGTH_LIMIT:
+ return defer.fail(MessageTooLong(msg, len(msg)))
+
+ return self.api.update(msg, params=args)
+
+
+ def get_user(self, nick):
+ #FIXME; index by nickname
+ for u in self.users:
+ if nick.lower() == u.nick.lower():
+ return u
+
+ # No Twitter user is available, if not authenticated yet
+ if not self.is_authenticated():
+ return None
+
+ #TODO: use cache lookup_screen_name() method before returning UnknownTwitterUser()
+
+ # if not found, consider it's a potential Twitter user we don't know yet
+ return UnknownTwitterUser(self, nick)
+
+ def create_channel(self, name):
+ #TODO make it generic to allow more types of channels
+ #TODO: make it possible to create a short-lived channel object for
+ # channel-query commands
+ dbg("about to join channel: %s" % (name))
+ channel = None
+ if name.startswith("#@"):
+ rawname = name[2:]
+ try:
+ user, list_name = rawname.split('/', 1)
+ except ValueError:
+ # user channel:
+ user = rawname
+ if user:
+ channel = UserChannel(self, user)
+ else:
+ perror('invalid twitter user spec: %r' % (user))
+ else:
+ # list channel:
+ if not user or not list_name:
+ perror('invalid twitter list spec: %r' % (name))
+ else:
+ channel = ListChannel(self, user, list_name)
+ if channel:
+ self.channels[name] = channel
+ return channel
+
+ def get_channel(self, name):
+ return self.channels.get(name)
+
+ def get_target(self, name):
+ if name.startswith('#'):
+ return self.get_channel(name)
+ else:
+ return self.get_user(name)
+
+ def mask_matches(self, mask):
+ #FIXME: match wildcards?
+ u = self.get_user(mask)
+ if u:
+ yield u
+
+ def who_matches(self, mask):
+ #TODO: make WHO list channel users
+ for u in self.mask_matches(mask):
+ #XXX: WTF do "H" and "G" mean?
+ yield ('*', u.username, u.hostname, self.myhost, u.nick, 'H', ':0', u.real_name)
+
+ def whois_twitter_user(self, u, tu):
+ self.send_reply(irc.RPL_WHOISUSER, u.nick, u.username, u.hostname, '*', ':%s' % (u.real_name))
+ #FIXME: find a better way to send user information, instead of RPL_AWAY
+ # - maybe just a pointer to a #!userinfo-nickname channel, where this info is available
+ def oneline(s):
+ return full_entity_decode(s).encode(IRC_ENCODING).replace('\n', ' ').replace('\r', ' ')
+
+ self.send_reply(irc.RPL_AWAY, u.nick, ':Location: %s' % oneline(tu.location))
+ self.send_reply(irc.RPL_AWAY, u.nick, ':URL: %s' % oneline(tu.url))
+ self.send_reply(irc.RPL_AWAY, u.nick, ':Bio: %s' % oneline(tu.description))
+ self.send_reply(irc.RPL_AWAY, u.nick, ':Last update: %s' % oneline(tu.status.text))
+ self.send_reply(irc.RPL_AWAY, u.nick, ':Twitter URL: http://twitter.com/%s' % oneline(tu.screen_name))
+ self.send_reply(irc.RPL_ENDOFWHOIS, u.nick, ':End of WHOIS')
+
+ def whois_mask(self, mask):
+ def doit():
+ self.dbg("fetching user info for %s" % (mask))
+ self.api.show_user(mask).addCallback(got_user).addErrback(error)
+
+ def got_user(tu):
+ self.dbg("got user info!")
+ self.global_twuser_cache.got_api_user_info(tu)
+ u = self.get_twitter_user(tu.id)
+ self.whois_twitter_user(u, tu)
+
+ def error(e):
+ self.send_reply(irc.ERR_NOSUCHNICK, mask, ':Error fetching user info - %s' % (e.value))
+
+ doit()
+
+class PasserdFactory(Factory):
+ protocol = PasserdProtocol
+
+ def __init__(self, opts):
+ url = 'sqlite:///%s' % (opts.database)
+ self.opts = opts
+ self.data = DataStore(url)
+ self.data.create_tables()
+ self.global_twuser_cache = TwitterUserCache(self)
+
+class PasserdGlobalOptions:
+ def __init__(self):
+ # set the defaults:
+
+ self.listen = ('0.0.0.0', 6667)
+
+ #logging:
+ self.logstream = sys.stderr
+
+ # list of (logger_name, level) pairs
+ # - sqlalchemy is too verbose on the INFO loglevel
+ # - enable oauth debugging, by now
+ self.loglevels = [(None, logging.INFO),
+ ('sqlalchemy', logging.ERROR),
+ ('passerd.oauth',logging.DEBUG),
+ ('passerd.feeds',logging.DEBUG),
+ ('passerd.scheduler',logging.DEBUG)]
+ self.logformat = '%(asctime)s:%(levelname)s:%(name)s:%(message)s'
+
+ self.api_timeout = 60
+
+def parse_cmdline(args, opts):
+ def parse_hostport(option, optstr, value, parser):
+ try:
+ host, rawport = value.rsplit(":", 1)
+ port = int(rawport)
+ except ValueError:
+ parser.error("invalid listen address, expected HOST:PORT")
+ opts.listen = (host, port)
+
+ def set_loglevels(levels):
+ opts.loglevels = levels
+
+ parser = optparse.OptionParser("%prog [options] <database path>")
+ parser.add_option("-l", "--listen", type="string",
+ action="callback", callback=parse_hostport,
+ metavar="HOST:PORT", help="listen address")
+ parser.add_option("-D", "--debug",
+ action="callback", callback=lambda *args: set_loglevels([(None,logging.DEBUG)]),
+ help="Enable debug logging")
+ parser.add_option("--logformat",
+ metavar="FORMAT", type="string", default=None,
+ help="Set the logging format")
+ _, args = parser.parse_args(args)
+ if not args:
+ parser.error("the database path is needed!")
+ opts.database = args[0]
+ return opts
+
+def setup_logging(opts):
+
+ ch = logging.StreamHandler(opts.logstream)
+ f = logging.Formatter(opts.logformat)
+ ch.setFormatter(f)
+
+ # root logger:
+ r = logging.getLogger()
+ r.addHandler(ch)
+
+ for name,level in opts.loglevels:
+ logging.getLogger(name).setLevel(level)
+
+
+def run():
+ opts = PasserdGlobalOptions()
+ parse_cmdline(sys.argv[1:], opts)
+ setup_logging(opts)
+
+ pinfo("Starting Passerd. Will listen on address %s:%d" % opts.listen)
+ reactor.listenTCP(interface=opts.listen[0], port=opts.listen[1],
+ factory=PasserdFactory(opts))
+ pinfo("Starting Twisted reactor loop.")
+ reactor.run()
+
+__all__ = ['run']
diff --git a/passerd/poauth.py b/passerd/poauth.py
new file mode 100644
index 0000000..f712d99
--- /dev/null
+++ b/passerd/poauth.py
@@ -0,0 +1,148 @@
+
+#!/usr/bin/env python
+#
+# Passerd - An IRC server as a gateway to Twitter
+#
+# OAuth code
+#
+# Author: Eduardo Habkost <ehabkost@raisama.net>
+#
+# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+import logging
+
+from twisted.internet import defer
+from twisted.web import client as twclient
+import oauth.oauth as oauth
+
+
+logger = logging.getLogger('passerd.oauth')
+dbg = logger.debug
+
+
+OAUTH_CONSUMER_KEY='1K2bNGyqs7dtDKTaTlfnQ'
+OAUTH_CONSUMER_SECRET='frpQHgjN21ajybwA0ZQ2utwlu9O6A36r8YLy6PxY5c'
+
+OAUTH_REQUEST_TOKEN_URL='http://twitter.com/oauth/request_token'
+OAUTH_ACCESS_TOKEN_URL='http://twitter.com/oauth/access_token'
+OAUTH_AUTHORIZE_URL='http://twitter.com/oauth/authorize'
+
+OAUTH_SIGN_METHOD=oauth.OAuthSignatureMethod_HMAC_SHA1()
+
+oauth_consumer = oauth.OAuthConsumer(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET)
+
+
+class OAuthClient:
+ def __init__(self, url_cb=None, progress_cb=None):
+ self.verifier_callback = None
+ self.url_callback = url_cb
+ self.progress_cb = progress_cb
+
+ def progress(self, msg):
+ """Can be overwritten, to show a status message"""
+ if self.progress_cb:
+ self.progress_cb(msg)
+
+ def send_to_url(self, url):
+ """Must be overwritten"""
+ if self.url_callback:
+ self.url_callback(url)
+ else:
+ raise NotImplementedError("oauth send_to_url not implemented")
+
+ def got_verifier(self, verifier):
+ """Must be called when the verifier code is received"""
+ if self.verifier_callback:
+ return self.verifier_callback(verifier)
+ else:
+ raise Exception("Not waiting for OAuth verifier")
+
+ def request_token(self):
+ def doit():
+ req = oauth.OAuthRequest.from_consumer_and_token(oauth_consumer, callback='oob', http_url=OAUTH_REQUEST_TOKEN_URL)
+ req.sign_request(OAUTH_SIGN_METHOD, oauth_consumer, None)
+ return twclient.getPage(req.to_url()).addCallback(done)
+
+ def done(data):
+ return oauth.OAuthToken.from_string(data)
+
+ return doit()
+
+ def authorize_url(self, req_token):
+ """Return the URL used for authorization"""
+ req = oauth.OAuthRequest.from_token_and_callback(token=req_token, http_url=OAUTH_AUTHORIZE_URL)
+ return req.to_url()
+
+ def _send_verifier(self, req_token, verifier):
+ def doit():
+ req = oauth.OAuthRequest.from_consumer_and_token(oauth_consumer, http_method='POST', token=req_token, verifier=verifier, http_url=OAUTH_ACCESS_TOKEN_URL)
+ req.sign_request(OAUTH_SIGN_METHOD, oauth_consumer, req_token)
+ postdata = req.to_postdata()
+ dbg("access token url: %r. postdata: %r. token: %s", OAUTH_ACCESS_TOKEN_URL, postdata, req_token)
+ return twclient.getPage(OAUTH_ACCESS_TOKEN_URL, method='POST',
+ postdata=postdata).addCallback(done)
+
+ def done(data):
+ return oauth.OAuthToken.from_string(data)
+
+ return doit()
+
+ def get_oauth_token(self):
+ """Request a new oauth token
+
+ It returns a deferred, but you should use the returned Deferred only if
+ got_verifier() is called only once. If you are going to allow the user
+ to retry, use the Deferred returned by got_verifier()
+ """
+ d = defer.Deferred()
+ def doit():
+ self.progress("getting a request token...")
+ self.request_token().addCallbacks(got_req_token, d.errback)
+
+ def got_req_token(req_token):
+ self.progress("got request token.")
+
+ # now we will wait for the PIN:
+ self.verifier_callback = lambda pin: got_pin(req_token, pin)
+ self.send_to_url(self.authorize_url(req_token))
+
+ def got_pin(req_token, pin):
+ self.progress("getting access token...")
+ return self._send_verifier(req_token, pin).addCallback(got_access_token).addErrback(error)
+
+ def got_access_token(token):
+ self.progress("got the access token")
+ # the get_oauth_token() deferred works only once.
+ if not d.called:
+ d.callback(token)
+ return token
+
+ def error(e):
+ if not d.called:
+ # the get_oauth_token() deferred works only once.
+ d.errback(e)
+ return e
+
+ doit()
+ return d
+
+
+
diff --git a/passerd/scheduler.py b/passerd/scheduler.py
new file mode 100644
index 0000000..39aa60b
--- /dev/null
+++ b/passerd/scheduler.py
@@ -0,0 +1,154 @@
+#!/usr/bin/env python
+#
+# Passerd - An IRC server as a gateway to Twitter
+#
+# Rate-limiting scheduler code
+#
+# Author: Eduardo Habkost <ehabkost@raisama.net>
+#
+# Copyright (c) 2009 Eduardo Pereira Habkost <ehabkost@raisama.net>
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+import logging, time
+from twisted.internet import reactor, defer
+
+logger = logging.getLogger('passerd.scheduler')
+dbg = logger.debug
+
+# refresh delay in seconds. This is multiplied by the number of feeds running,
+# so we don't hit the rate-limit if the user is following too many feeds.
+# Twitter default rate limit is 150 requests/hour. REFRESH_DELAY=45 should
+# result on 80 requets per hour
+
+MAX_REQS_PER_HOUR = 80
+REFRESH_DELAY = int(3600/MAX_REQS_PER_HOUR)
+
+class RefreshUpdater:
+ def __init__(self, scheduler, fn):
+ self.scheduler = scheduler
+ self.fn = fn
+ self.pending = False
+
+ def call(self):
+ dbg("calling: %r", self.fn)
+ self.pending = False
+ return self.fn()
+
+ def resched(self):
+ dbg("resched %r. pending: %r", self.fn, self.pending)
+ if self.pending:
+ return
+ self.pending = True
+ self.scheduler._resched_updater(self)
+
+ def unsched(self):
+ dbg("unsched %r. pending: %r", self.fn, self.pending)
+ if not self.pending:
+ return
+ self.pending = False
+ self.scheduler._unsched_updater(self)
+
+ def destroy(self):
+ dbg("destroy %r. pending: %r", self.fn, self.pending)
+ self.unsched()
+ self.scheduler._remove_updater(self)
+
+class ApiScheduler:
+ def __init__(self, api):
+ self.api = api
+ self.updaters = {}
+ self.pending_queue = []
+ self.next_call = None
+ self.running = False
+ self.shots_available = 0
+
+ def new_updater(self, fn, active=True):
+ u = RefreshUpdater(self, fn)
+ self.updaters[id(u)] = u
+ if active:
+ u.resched()
+ return u
+
+ def _remove_updater(self, u):
+ del self.updaters[id(u)]
+
+ def _resched_updater(self, u):
+ self.pending_queue.append(u)
+ self._run_shots()
+
+ def _unsched_updater(self, u):
+ self.pending_queue.remove(u)
+
+ def _run_shots(self):
+ while self.shots_available > 0 and self.pending_queue:
+ self.shots_available -= 1
+ u = self.pending_queue.pop(0)
+ u.call()
+
+ def _run_next(self):
+ # we will run all pending refreshs at the same time to give a better
+ # user experience: all content will be fetched at the same time
+ # (DMs, home timeline, mentions, other feeds), avoiding
+ # bugging the user multiple times
+ dbg("_run_next called")
+ updater_count = len(self.updaters)
+
+ self.shots_available = updater_count
+ self._run_shots()
+
+ if self.shots_available > 0:
+ dbg("still have %d shots available", self.shots_available)
+
+ delay = REFRESH_DELAY*updater_count
+ dbg("%d updaters are running. delay for the next update: %d seconds", updater_count, delay)
+ self._sched_next(delay)
+
+
+ def _sched_next(self, delay):
+ dbg("scheduling next call for %d seconds", delay)
+ self.next_call = reactor.callLater(delay, self._run_next)
+
+ def _cancel_next(self):
+ dbg("cancelling next call")
+ if self.next_call is not None:
+ if self.next_call.active():
+ self.next_call.cancel()
+ self.next_call = None
+
+ def start(self):
+ if not self.running:
+ self.running = True
+ self._run_next()
+
+ def stop(self):
+ self.running = False
+ self._cancel_next()
+
+ def wait_rate_limit(self):
+ delay = int(self.api.rate_limit_reset - time.time())
+ reset = time.ctime(self.api.rate_limit_reset)
+ if delay > REFRESH_DELAY:
+ dbg("Rescheduling the next feed refresh to %s (%s seconds),"
+ " as the rate limit was exhausted." % (reset, delay))
+ self._cancel_next()
+ self._sched_next(delay)
+ else:
+ dbg("No need to resched to wait for rate-limit, as the "
+ "delay is only %s seconds" % (delay))
diff --git a/passerd/tests/__init__.py b/passerd/tests/__init__.py
new file mode 100644
index 0000000..4be696b
--- /dev/null
+++ b/passerd/tests/__init__.py
@@ -0,0 +1,22 @@
+import unittest, doctest
+
+modules = 'dialogs'.split()
+docmodules = []
+
+def suite():
+ suite = unittest.TestSuite()
+ loader = unittest.TestLoader()
+
+ for n in modules:
+ passerd = __import__('passerd.tests.%s' % (n))
+ module = getattr(passerd.tests, n)
+ tests = loader.loadTestsFromModule(module)
+ suite.addTests(tests)
+
+ for dm in docmodules:
+ suite.addTest(doctest.DocTestSuite(dm))
+
+ return suite
+
+if __name__ == '__main__':
+ unittest.TextTestRunner().run(suite())
diff --git a/passerd/tests/dialogs.py b/passerd/tests/dialogs.py
new file mode 100644
index 0000000..207164f
--- /dev/null
+++ b/passerd/tests/dialogs.py
@@ -0,0 +1,129 @@
+import re
+
+from passerd.dialogs import *
+
+from unittest import TestCase
+
+class DialogLogger:
+ def __init__(self, d):
+ self.msgs = []
+ d.set_message_func(self.got_msg)
+
+ def got_msg(self, msg):
+ self.msgs.append(msg)
+
+class DialogTestMixin:
+ def assertMsgs(self, *args):
+ self.assertEquals(self.log.msgs, list(args))
+
+ def assertSomeMsg(self, msg):
+ self.assertTrue(msg in self.log.msgs, '%r is not among the replies' % (msg))
+
+ def _hasSomeRe(self, pat, flags=0):
+ r = re.compile(pat, flags)
+ for m in self.log.msgs:
+ if r.search(m):
+ return True
+ return False
+
+ def assertSomeRe(self, pat, flags=0):
+ self.assertTrue(self._hasSomeRe(pat, flags), '%r is not a match on any reply' % (pat))
+
+ def msgs(self, *args):
+ for a in args:
+ self.d.message(a)
+
+ def rcv(self, msg):
+ self.d.recv_message(msg)
+
+ def wait(self, pattern, *args):
+ replies = list(args)
+ self.d.wait_for(pattern, lambda msg,m: self.msgs(*args))
+
+
+class SimpleDialogTest(DialogTestMixin, TestCase):
+ def setUp(self):
+ self.d = d = Dialog()
+ self.log = DialogLogger(d)
+
+ def testSimple(self):
+ self.wait('hi', 'hi!')
+ self.rcv('hi')
+ self.assertMsgs('hi!')
+ self.assertFalse(self._hasSomeRe('nononono'))
+
+ def testMulti(self):
+ self.wait('bye', 'bye', 'see you later')
+ self.wait('hi', 'hi!', 'how are you?')
+ self.rcv('hi!')
+ self.rcv('bye')
+ self.assertMsgs('hi!', 'how are you?', 'bye', 'see you later')
+
+ def testNoMatch(self):
+ self.d.unknown_message = lambda msg: self.msgs('what?')
+ self.wait('hello', 'hello world')
+ self.rcv('hi')
+ self.assertMsgs('what?')
+
+
+ def testOverride(self):
+ self.wait('hi', 'first hi')
+ self.wait('hi1', 'hi1 reply')
+ self.rcv('hi')
+ self.rcv('hi1')
+ self.assertMsgs('first hi', 'hi1 reply')
+ self.wait('hi', 'second hi')
+ self.rcv('hi1')
+ self.assertMsgs('first hi', 'hi1 reply', 'second hi')
+
+ def testException(self):
+ def err(msg, m):
+ raise Exception('[error: %s - %s]' % (msg, m.group(1)))
+
+ self.d.wait_for('explode (.*)', err)
+ self.rcv('explode now')
+ self.assertEquals(len(self.log.msgs), 1)
+ # check just if the exception message is inside the received reply:
+ self.assertTrue('[error: explode now - now]' in self.log.msgs[0], 'no exception text on error reply')
+
+
+class _TestCommands(CommandDialog):
+ shorthelp_hi = 'say hi'
+ def command_hi(self, args):
+ self.message('hi %s!' % (args))
+
+class TestCommands(DialogTestMixin, TestCase):
+ def setUp(self):
+ self.d = _TestCommands()
+ self.log = DialogLogger(self.d)
+
+ def testHi(self):
+ self.rcv('hi you')
+ self.assertMsgs('hi you!')
+
+ def testHelp(self):
+ self.rcv('help')
+ self.assertSomeRe('HI - say hi')
+
+ def testPrefix(self):
+ self.d.set_cmd_prefix('!FOO-')
+ self.rcv('help')
+ self.assertSomeRe('!FOO-HI - say hi')
+
+ def testUnknown(self):
+ self.d.unknown_command = lambda cmd,args: self.d.message('%s-%s' % (cmd,args))
+ self.rcv('nono yesyes no')
+ self.assertMsgs('nono-yesyes no')
+
+ def testAlias(self):
+ self.d.add_alias('hey', 'hi')
+ self.d.add_alias('hello', 'hI', imp=CMD_IMP_COMMON)
+ self.rcv('hello world')
+ self.assertMsgs('hi world!')
+ self.rcv('help')
+ # check even if case matches ("hI" above)
+ self.assertSomeRe('Other commands: .*HEY')
+ self.assertSomeRe('HELLO - Synonym to `hI`: say hi')
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/passerd/util.py b/passerd/util.py
new file mode 100644
index 0000000..b5b3f55
--- /dev/null
+++ b/passerd/util.py
@@ -0,0 +1,41 @@
+
+ENCODINGS = ['utf-8', 'iso-8859-1']
+
+def hooks(fn):
+ """Decorator that call beforeFoo() and afterFoo() methods if available"""
+ name = fn.func_name
+ upname = name[0].upper()+name[1:]
+ before = 'before%s' % (upname)
+ after = 'after%s' % (upname)
+ def call_with_hooks(self, *args, **kwargs):
+ if hasattr(self, before):
+ getattr(self, before)(*args, **kwargs)
+ r = fn(self, *args, **kwargs)
+ if hasattr(self, after):
+ getattr(self, after)(*args, **kwargs)
+ return r
+ return call_with_hooks
+
+
+def try_unicode(s, enc=None):
+ for e in [enc]+ENCODINGS:
+ if not e:
+ continue
+
+ try:
+ return unicode(s, e)
+ except:
+ pass
+
+ # no success:
+ raise Exception("couldn't decode message as unicode")
+
+def to_str(s, enc):
+ if isinstance(s, unicode):
+ return s.encode(enc)
+ elif isinstance(s, str):
+ return s
+ else:
+ raise Exception("%r is not str (type: %r)" % (s, type(s)))
+
+
diff --git a/passerd/utils.py b/passerd/utils.py
new file mode 100644
index 0000000..a40b22c
--- /dev/null
+++ b/passerd/utils.py
@@ -0,0 +1,30 @@
+"""
+Random utility functions
+
+`htmlentitydecode` based on example from:
+ http://wiki.python.org/moin/EscapingHtml
+"""
+
+
+import re
+from htmlentitydefs import name2codepoint
+
+def htmlentitydecode(s):
+ s = re.sub(
+ '&(%s);' % '|'.join(name2codepoint),
+ lambda m: unichr(name2codepoint[m.group(1)]), s)
+ s = re.sub('&#([0-9]+);', lambda m: unichr(int(m.group(1))), s)
+ return s
+
+def undo_xss_escaping(s):
+ # undo the '<' and '>' escaping done by Twitter
+ return s.replace('<', '<').replace('>', '>')
+
+def full_entity_decode(s):
+ """Undo the stupid entity encoding done by Twitter
+
+ '>' and '<' are entity-encoded twice!
+ """
+ return undo_xss_escaping(htmlentitydecode(s))
+
+__all__ = ["htmlentitydecode", "undo_xss_escaping", "full_entity_decode"]
diff --git a/run.sh b/run.sh
new file mode 100755
index 0000000..287632c
--- /dev/null
+++ b/run.sh
@@ -0,0 +1,25 @@
+#!/bin/bash
+
+mydir="$(dirname "$0")"
+
+add_pypath()
+{
+ if [ -n "$PYTHONPATH" ];then
+ PYTHONPATH="$1:$PYTHONPATH"
+ else
+ PYTHONPATH="$1"
+ fi
+}
+
+if [ ! -d "$mydir/third-party/twitty-twister" ];then
+ echo "You need to update the twitty-twister submodule. Run:" >&2
+ echo " git submodule init"
+ echo " git submodule update"
+ exit 1
+fi
+add_pypath "$mydir/third-party/twitty-twister"
+add_pypath "$mydir"
+export PYTHONPATH
+
+mkdir -p "$HOME/.passerd"
+"$mydir/bin/passerd" "$HOME/.passerd/data.sqlite" "$@"
diff --git a/test.sh b/test.sh
new file mode 100755
index 0000000..aa46f18
--- /dev/null
+++ b/test.sh
@@ -0,0 +1,2 @@
+#!/bin/bash
+exec python passerd/tests/__init__.py
diff --git a/third-party/twitty-twister b/third-party/twitty-twister
new file mode 160000
index 0000000..e31461e
--- /dev/null
+++ b/third-party/twitty-twister
@@ -0,0 +1 @@
+Subproject commit e31461ee5ebeb6cc0cf541b740a5de08267e4d6c
|
pjleonhardt/mysql_mirror
|
c85a9afd54d0ae1c34cbe25305e8f98d157d1d17
|
Add accessible mysqldump options hash for override default options. Closes #2
|
diff --git a/lib/mysql_mirror.rb b/lib/mysql_mirror.rb
index 8a7ea40..8dec7e0 100644
--- a/lib/mysql_mirror.rb
+++ b/lib/mysql_mirror.rb
@@ -1,200 +1,210 @@
require 'active_record'
require 'fileutils'
class MysqlMirror
class MysqlMirrorException < Exception; end
class Source < ActiveRecord::Base
end
class Target < ActiveRecord::Base
end
- attr_accessor :tables, :where
+ attr_accessor :tables, :where, :mysqldump_options
def initialize(options = {})
unless ([:source, :target] - options.keys).blank?
# Need to specify a Source and Target database
raise MysqlMirrorException.new("You must specify both Source and Target connections")
end
self.tables = options.delete(:tables)
self.where = options.delete(:where)
overrides = options.delete(:override) || {}
source_override = overrides.delete(:source) || {}
target_override = overrides.delete(:target) || {}
+ # set default mysqldump options
+ self.mysqldump_options = {
+ "compact" => "TRUE",
+ "max_allowed_packet" => 100553296,
+ "extended-insert" => "TRUE",
+ "lock-tables" => "FALSE",
+ "add-locks" => "FALSE",
+ "add-drop-table" => "FALSE"
+ }
+
@source_config = get_configuration(options.delete(:source))
@target_config = get_configuration(options.delete(:target))
@source_config.merge!(source_override)
@target_config.merge!(target_override)
# @commands is an array of methods to call
if mirroring_same_host?
@commands = commands_for_local_mirror
else
@commands = commands_for_remote_mirror
end
end
def commands_for_local_mirror
[:local_copy]
end
def commands_for_remote_mirror
[
:remote_mysqldump,
:remote_tmp_file_table_rename,
:remote_insert_command,
:remote_rename_tmp_tables,
:remote_remove_tmp_file
]
end
def mirroring_same_host?
@source_config[:host] == @target_config[:host]
end
def execute!
@start_time = Time.now
@source = connect_to(:source)
@target = connect_to(:target)
@commands.each do |c|
self.send(c)
end
end
def to_s
"Mirroring #{self.tables.join(', ')} from #{@source_config[:host]}.#{@source_config[:database]} to #{@target_config[:host]}.#{@target_config[:database]}"
end
private
# e.g, connect_to(:source)
# => MysqlMirror::Source.establish_connection(@source_config).connection
#
def connect_to(which)
"MysqlMirror::#{which.to_s.classify}".constantize.establish_connection(self.instance_variable_get("@#{which}_config")).connection
end
def local_copy
get_tables.each do |table|
target_db = @target_config[:database]
source_db = @source_config[:database]
- target_table = "#{target_db}.#{table}"
- target_tmp_table = "#{target_db}.#{table}_MirrorTmp"
- target_old_table = "#{target_db}.#{table}_OldMarkedToDelete"
- source_table = "#{source_db}.#{table}"
+ target_table = "`#{target_db}`.`#{table}`"
+ target_tmp_table = "`#{target_db}`.`#{table}_MirrorTmp`"
+ target_old_table = "`#{target_db}`.`#{table}_OldMarkedToDelete`"
+ source_table = "`#{source_db}`.`#{table}`"
prime_statement_1 = "DROP TABLE IF EXISTS #{target_tmp_table}"
prime_statement_2 = "CREATE TABLE IF NOT EXISTS #{target_table} LIKE #{source_table}"
create_statement = "CREATE TABLE #{target_tmp_table} LIKE #{source_table}"
select_clause = "SELECT * FROM #{source_table}"
select_clause << " WHERE #{self.where[table]}" unless (self.where.blank? or self.where[table].blank?)
insert_statement = "INSERT INTO #{target_tmp_table} #{select_clause}"
rename_statement = "RENAME TABLE #{target_table} TO #{target_old_table}, #{target_tmp_table} TO #{target_table}"
cleanup_statement = "DROP TABLE IF EXISTS #{target_old_table}"
staments_to_run = [prime_statement_1, prime_statement_2, create_statement, insert_statement, rename_statement, cleanup_statement]
staments_to_run.each do |statement|
@target.execute(statement)
end
end
end
def mysqldump_command_prefix
- "mysqldump --compact=TRUE --max_allowed_packet=100663296 --extended-insert=TRUE --lock-tables=FALSE --add-locks=FALSE --add-drop-table=FALSE"
+ "mysqldump " << self.mysqldump_options.map {|x| "--#{x[0]}=#{x[1]}" }.join(" ")
end
def remote_mysqldump
@tmp_file_name = "mysql_mirror_#{@start_time.to_i}.sql"
tables = get_tables.map(&:to_s).join(" ")
if self.where.blank?
where = ""
else
where_statement = self.where.values.first
where = "--where=\"#{where_statement}\""
end
config = "-u#{@source_config[:username]} -p'#{@source_config[:password]}' -h #{@source_config[:host]} #{@source_config[:database]}"
the_cmd = "#{mysqldump_command_prefix} #{where} #{config} #{tables} > #{@tmp_file_name}"
puts the_cmd
`#{the_cmd}`
end
def remote_tmp_file_table_rename
create_or_insert_regex = Regexp.new('(^CREATE TABLE|^INSERT INTO)( `)(.+?)(`)(.+)')
new_file_name = @tmp_file_name + ".replaced.sql"
new_file = File.new(new_file_name, "w")
IO.foreach(@tmp_file_name) do |line|
if match_data = line.match(create_or_insert_regex)
table_name = match_data[3]
new_table_name = "#{table_name}_#{@start_time.to_i}"
new_file.puts match_data[1] + match_data[2] + new_table_name + match_data[4]+ match_data[5]
else
new_file.puts line
end
end
new_file.close
# replace dump'd sql file with this gsub'd one
FileUtils.move(new_file_name, @tmp_file_name)
end
def remote_insert_command
config = "-u#{@target_config[:username]} -p'#{@target_config[:password]}' -h #{@target_config[:host]} #{@target_config[:database]}"
the_cmd = "mysql #{config} < #{@tmp_file_name}"
`#{the_cmd}`
end
def remote_rename_tmp_tables
get_tables.each do |table|
tmp_table_name = "#{table}_#{@start_time.to_i}"
old_table_name = "#{table}_OldMarkedToDelete"
@target.transaction do
@target.execute("DROP TABLE IF EXISTS #{old_table_name}")
@target.execute("RENAME TABLE #{table} TO #{old_table_name}, #{tmp_table_name} TO #{table}")
@target.execute("DROP TABLE IF EXISTS #{old_table_name}")
end
end
end
def remote_remove_tmp_file
FileUtils.rm(@tmp_file_name)
end
def get_tables
the_tables = self.tables.blank? ? @source.select_values("SHOW TABLES").map!(&:to_sym) : self.tables
end
def get_configuration(env_or_hash)
config = env_or_hash
if(env_or_hash.is_a? Symbol)
config = ActiveRecord::Base.configurations[env_or_hash.to_s]
end
config.symbolize_keys
end
end
|
pjleonhardt/mysql_mirror
|
64a047e75db0d10ce85b6cf6c15d93e43c2e5f54
|
Revert "perms check"
|
diff --git a/README.rdoc b/README.rdoc
index dbb40b9..79245a5 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -1,44 +1,43 @@
= Mysql Mirror
Use MysqlMirror to mirror data between databases. This can be useful when you want to update your
development or staging environments with real data to work with. Or, if you do some heavy lifting
calculations on another server, you might want to use a seperate database on another host, etc.
-
=== General Approach
- Mirror Across Hosts: performs a mysql_dump to an sql file, then imports file to target host
- Mirror Same Host: uses CREATE TABLE ( SELECT ... ) style for mirroring. Much faster than mysql_dump
Note:
ALL information will be lost in the tables mirrored to the Target Database
== Dependencies
- Active Record
- FileUtils
== Usage
Basic usage, copy production db to development
@m = MysqlMirror.new({
:source => :production,
:target => :development
})
Choose what tables you want to bring over and how you want to scope them...
@m = MysqlMirror.new({
:source => :production,
:target => :development,
:tables => [:users, :widgets],
:where => {:users => "is_admin NOT NULL"},
})
Database information not in your database.yml file? (Or Not Running Rails?) No Problem!
@m = MysqlMirror.new({
:source => { :database => "app_production", :user => ..., :password => ..., :hostname => ...},
:target => {:database => "app_development", :hostname => 'localhost'}
})
Want to use everything in :production environment (user, pass, host) but need to change the database?
@m = MysqlMirror.new({
:source => :production,
:override => {:source => {:database => "heavy_calculations_database"}},
:target => :production
})
|
pjleonhardt/mysql_mirror
|
7db423832f6884615decc7c2ab311c3c29497112
|
Reverting 03b4dafd179364a02a4cef282593e1a5dd61c6f3
|
diff --git a/README.rdoc b/README.rdoc
index 5dab617..0e3de38 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -1,59 +1,34 @@
= Mysql Mirror
Use MysqlMirror to mirror data between databases. This can be useful when you want to update your
development or staging environments with real data to work with. Or, if you do some heavy lifting
calculations on another server, you might want to use a seperate database on another host, etc.
=== General Approach
- Mirror Across Hosts: performs a mysql_dump to an sql file, then imports file to target host
- Mirror Same Host: uses CREATE TABLE ( SELECT ... ) style for mirroring. Much faster than mysql_dump
Note:
ALL information will be lost in the tables mirrored to the Target Database
== Dependencies
- Active Record
- FileUtils
== Usage
-Basic usage, copy production db to development
- @m = MysqlMirror.new({
- :source => :production,
- :target => :development
- })
-
-Choose what tables you want to bring over and how you want to scope them...
- @m = MysqlMirror.new({
- :source => :production,
- :target => :development,
- :tables => [:users, :widgets],
- :where => {:users => "is_admin NOT NULL"},
- })
-
-Database information not in your database.yml file? (Or Not Running Rails?) No Problem!
- @m = MysqlMirror.new({
- :source => { :database => "app_production", :user => ..., :password => ..., :hostname => ...},
- :target => {:database => "app_development", :hostname => 'localhost'}
- })
-
-Want to use everything in :production environment (user, pass, host) but need to change the database?
- @m = MysqlMirror.new({
- :source => :production,
- :override => {:source => {:database => "heavy_calculations_database"}},
- :target => :production
- })
+Run `rake demo` to a bunch of different invocations of the tool
== Advanced Usage
Transfer Method
same_server => Doesn't use the mysqldump binary, instead does everything via raw sql on db.
different_servers => Uses mysqldump to build a file from source then loads this file to the target
Strategy
replace_existing => Drop's target tables that exist in source database
bomb_and_rebuild => Drops all tables on target schema then copies tables from source
atomic_rename => Copies tables to target first to a temp table (*_<timestamp>) then
once all are copied, atomically renames newly built and populated table
and the table being replaced (to *_old)
Specify an alternative mysql configuration
\ No newline at end of file
diff --git a/Rakefile b/Rakefile
index f33b18f..34a2fe9 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,20 +1,67 @@
require 'rubygems'
require 'rake'
begin
require 'jeweler'
Jeweler::Tasks.new do |gemspec|
gemspec.name = "mysql_mirror"
gemspec.summary = "Helps mirror MySql Databases"
gemspec.description = "Will mirror tables / databases between mysql databases and across hosts"
gemspec.email = "peterleonhardt@gmail.com"
gemspec.homepage = "http://github.com/pjleonhardt/mysql_mirror"
gemspec.authors = ["Peter Leonhardt", "Joe Goggins"]
gemspec.files = FileList["[A-Z]*", "lib/mysql_mirror.rb"]
end
Jeweler::GemcutterTasks.new
rescue LoadError
puts "Jeweler not available. Please install the jeweler gem."
end
-Dir["#{File.dirname(__FILE__)}/tasks/*.rake"].sort.each { |ext| load ext }
\ No newline at end of file
+Dir["#{File.dirname(__FILE__)}/tasks/*.rake"].sort.each { |ext| load ext }
+
+
+desc 'Run the demo/test cases'
+task :demo do
+ require 'lib/mysql_mirror'
+ puts 'MySqlMirror Demo'
+ # Basic usage, copy production db to development
+ # @m = MysqlMirror.new({
+ # :source => :production,
+ # :target => :development
+ # })
+ #
+ # Choose what tables you want to bring over and how you want to scope them...
+ # @m = MysqlMirror.new({
+ # :source => :production,
+ # :target => :development,
+ # :tables => [:users, :widgets],
+ # :where => {:users => "is_admin NOT NULL"},
+ # })
+ #
+ # Database information not in your database.yml file? (Or Not Running Rails?) No Problem!
+ # @m = MysqlMirror.new({
+ # :source => { :database => "app_production", :user => ..., :password => ..., :hostname => ...},
+ # :target => {:database => "app_development", :hostname => 'localhost'}
+ # })
+ #
+ # Want to use everything in :production environment (user, pass, host) but need to change the database?
+ # @m = MysqlMirror.new({
+ # :source => :production,
+ # :override => {:source => {:database => "heavy_calculations_database"}},
+ # :target => :production
+ # })
+ require 'ostruct'
+ @demos = []
+ @demos << OpenStruct.new(:name => "Basic usage, copy production db to development",
+ :code => Proc.new {
+ @m = MysqlMirror.new({
+ :source => :production,
+ :target => :development
+ })
+ })
+ @demos.each do |demo|
+ demo.code.call(binding)
+ puts @m.inspect
+ end
+
+end
\ No newline at end of file
diff --git a/demo/README b/demo/README
index 225d442..37ec8ea 100644
--- a/demo/README
+++ b/demo/README
@@ -1 +1,243 @@
-This is the Demo playground for mysql_mirror gem on github
\ No newline at end of file
+== Welcome to Rails
+
+Rails is a web-application framework that includes everything needed to create
+database-backed web applications according to the Model-View-Control pattern.
+
+This pattern splits the view (also called the presentation) into "dumb" templates
+that are primarily responsible for inserting pre-built data in between HTML tags.
+The model contains the "smart" domain objects (such as Account, Product, Person,
+Post) that holds all the business logic and knows how to persist themselves to
+a database. The controller handles the incoming requests (such as Save New Account,
+Update Product, Show Post) by manipulating the model and directing data to the view.
+
+In Rails, the model is handled by what's called an object-relational mapping
+layer entitled Active Record. This layer allows you to present the data from
+database rows as objects and embellish these data objects with business logic
+methods. You can read more about Active Record in
+link:files/vendor/rails/activerecord/README.html.
+
+The controller and view are handled by the Action Pack, which handles both
+layers by its two parts: Action View and Action Controller. These two layers
+are bundled in a single package due to their heavy interdependence. This is
+unlike the relationship between the Active Record and Action Pack that is much
+more separate. Each of these packages can be used independently outside of
+Rails. You can read more about Action Pack in
+link:files/vendor/rails/actionpack/README.html.
+
+
+== Getting Started
+
+1. At the command prompt, start a new Rails application using the <tt>rails</tt> command
+ and your application name. Ex: rails myapp
+2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options)
+3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!"
+4. Follow the guidelines to start developing your application
+
+
+== Web Servers
+
+By default, Rails will try to use Mongrel if it's are installed when started with script/server, otherwise Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails
+with a variety of other web servers.
+
+Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is
+suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
+getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>.
+More info at: http://mongrel.rubyforge.org
+
+Say other Ruby web servers like Thin and Ebb or regular web servers like Apache or LiteSpeed or
+Lighttpd or IIS. The Ruby web servers are run through Rack and the latter can either be setup to use
+FCGI or proxy to a pack of Mongrels/Thin/Ebb servers.
+
+== Apache .htaccess example for FCGI/CGI
+
+# General Apache options
+AddHandler fastcgi-script .fcgi
+AddHandler cgi-script .cgi
+Options +FollowSymLinks +ExecCGI
+
+# If you don't want Rails to look in certain directories,
+# use the following rewrite rules so that Apache won't rewrite certain requests
+#
+# Example:
+# RewriteCond %{REQUEST_URI} ^/notrails.*
+# RewriteRule .* - [L]
+
+# Redirect all requests not available on the filesystem to Rails
+# By default the cgi dispatcher is used which is very slow
+#
+# For better performance replace the dispatcher with the fastcgi one
+#
+# Example:
+# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
+RewriteEngine On
+
+# If your Rails application is accessed via an Alias directive,
+# then you MUST also set the RewriteBase in this htaccess file.
+#
+# Example:
+# Alias /myrailsapp /path/to/myrailsapp/public
+# RewriteBase /myrailsapp
+
+RewriteRule ^$ index.html [QSA]
+RewriteRule ^([^.]+)$ $1.html [QSA]
+RewriteCond %{REQUEST_FILENAME} !-f
+RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
+
+# In case Rails experiences terminal errors
+# Instead of displaying this message you can supply a file here which will be rendered instead
+#
+# Example:
+# ErrorDocument 500 /500.html
+
+ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly"
+
+
+== Debugging Rails
+
+Sometimes your application goes wrong. Fortunately there are a lot of tools that
+will help you debug it and get it back on the rails.
+
+First area to check is the application log files. Have "tail -f" commands running
+on the server.log and development.log. Rails will automatically display debugging
+and runtime information to these files. Debugging info will also be shown in the
+browser on requests from 127.0.0.1.
+
+You can also log your own messages directly into the log file from your code using
+the Ruby logger class from inside your controllers. Example:
+
+ class WeblogController < ActionController::Base
+ def destroy
+ @weblog = Weblog.find(params[:id])
+ @weblog.destroy
+ logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
+ end
+ end
+
+The result will be a message in your log file along the lines of:
+
+ Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1
+
+More information on how to use the logger is at http://www.ruby-doc.org/core/
+
+Also, Ruby documentation can be found at http://www.ruby-lang.org/ including:
+
+* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/
+* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
+
+These two online (and free) books will bring you up to speed on the Ruby language
+and also on programming in general.
+
+
+== Debugger
+
+Debugger support is available through the debugger command when you start your Mongrel or
+Webrick server with --debugger. This means that you can break out of execution at any point
+in the code, investigate and change the model, AND then resume execution!
+You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'
+Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.find(:all)
+ debugger
+ end
+ end
+
+So the controller will accept the action, run the first line, then present you
+with a IRB prompt in the server window. Here you can do things like:
+
+ >> @posts.inspect
+ => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
+ #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
+ >> @posts.first.title = "hello from a debugger"
+ => "hello from a debugger"
+
+...and even better is that you can examine how your runtime objects actually work:
+
+ >> f = @posts.first
+ => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
+ >> f.
+ Display all 152 possibilities? (y or n)
+
+Finally, when you're ready to resume execution, you enter "cont"
+
+
+== Console
+
+You can interact with the domain model by starting the console through <tt>script/console</tt>.
+Here you'll have all parts of the application configured, just like it is when the
+application is running. You can inspect domain models, change values, and save to the
+database. Starting the script without arguments will launch it in the development environment.
+Passing an argument will specify a different environment, like <tt>script/console production</tt>.
+
+To reload your controllers and models after launching the console run <tt>reload!</tt>
+
+== dbconsole
+
+You can go to the command line of your database directly through <tt>script/dbconsole</tt>.
+You would be connected to the database with the credentials defined in database.yml.
+Starting the script without arguments will connect you to the development database. Passing an
+argument will connect you to a different database, like <tt>script/dbconsole production</tt>.
+Currently works for mysql, postgresql and sqlite.
+
+== Description of Contents
+
+app
+ Holds all the code that's specific to this particular application.
+
+app/controllers
+ Holds controllers that should be named like weblogs_controller.rb for
+ automated URL mapping. All controllers should descend from ApplicationController
+ which itself descends from ActionController::Base.
+
+app/models
+ Holds models that should be named like post.rb.
+ Most models will descend from ActiveRecord::Base.
+
+app/views
+ Holds the template files for the view that should be named like
+ weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby
+ syntax.
+
+app/views/layouts
+ Holds the template files for layouts to be used with views. This models the common
+ header/footer method of wrapping views. In your views, define a layout using the
+ <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb,
+ call <% yield %> to render the view using this layout.
+
+app/helpers
+ Holds view helpers that should be named like weblogs_helper.rb. These are generated
+ for you automatically when using script/generate for controllers. Helpers can be used to
+ wrap functionality for your views into methods.
+
+config
+ Configuration files for the Rails environment, the routing map, the database, and other dependencies.
+
+db
+ Contains the database schema in schema.rb. db/migrate contains all
+ the sequence of Migrations for your schema.
+
+doc
+ This directory is where your application documentation will be stored when generated
+ using <tt>rake doc:app</tt>
+
+lib
+ Application specific libraries. Basically, any kind of custom code that doesn't
+ belong under controllers, models, or helpers. This directory is in the load path.
+
+public
+ The directory available for the web server. Contains subdirectories for images, stylesheets,
+ and javascripts. Also contains the dispatchers and the default HTML files. This should be
+ set as the DOCUMENT_ROOT of your web server.
+
+script
+ Helper scripts for automation and generation.
+
+test
+ Unit and functional tests along with fixtures. When using the script/generate scripts, template
+ test files will be generated for you and placed in this directory.
+
+vendor
+ External libraries that the application depends on. Also includes the plugins subdirectory.
+ If the app has frozen rails, those gems also go here, under vendor/rails/.
+ This directory is in the load path.
diff --git a/demo/config/database.yml b/demo/config/database.yml
index b9d9e57..025d62a 100644
--- a/demo/config/database.yml
+++ b/demo/config/database.yml
@@ -1,15 +1,22 @@
# SQLite version 3.x
# gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
- adapter: mysql
- database: mm_demo_local_source
- username: root
- password:
- socket: /tmp/mysql.sock
+ adapter: sqlite3
+ database: db/development.sqlite3
+ pool: 5
+ timeout: 5000
+
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
+# Do not set this db to the same as development or production.
+test:
+ adapter: sqlite3
+ database: db/test.sqlite3
+ pool: 5
+ timeout: 5000
production:
- adapter: mysql
- database: mm_demo_local_source
- username: root
- password:
- socket: /tmp/mysql.sock
\ No newline at end of file
+ adapter: sqlite3
+ database: db/production.sqlite3
+ pool: 5
+ timeout: 5000
diff --git a/demo/db/migrate/20100406015530_create_t1s.rb b/demo/db/migrate/20100406015530_create_t1s.rb
deleted file mode 100644
index c33ddc9..0000000
--- a/demo/db/migrate/20100406015530_create_t1s.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-class CreateT1s < ActiveRecord::Migration
- def self.up
- create_table :t1s do |t|
- t.string :name
-
- t.timestamps
- end
- end
-
- def self.down
- drop_table :t1s
- end
-end
diff --git a/demo/doc/README_FOR_APP b/demo/doc/README_FOR_APP
index 10dbe63..fe41f5c 100644
--- a/demo/doc/README_FOR_APP
+++ b/demo/doc/README_FOR_APP
@@ -1,2 +1,2 @@
-Run rake demo:setup
-Run rake demo:run
\ No newline at end of file
+Use this README file to introduce your application and point to useful places in the API for learning more.
+Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
diff --git a/demo/lib/tasks/demo.rake b/demo/lib/tasks/demo.rake
index f39cc59..ebe0d33 100644
--- a/demo/lib/tasks/demo.rake
+++ b/demo/lib/tasks/demo.rake
@@ -1,75 +1,35 @@
namespace :demo do
desc "requirements for the basic demo"
task :instructions do
s =<<-EOS
---
Setup privileged MySql user accounts and add this to database.yml
- development:
+ demo_local:
adapter: mysql
database: mm_demo_local_source
username: root
password:
socket: /tmp/mysql.sock
- production:
+ demo_remote:
adapter: mysql
- database: mm_demo_remote_target
+ database: mm_demo_remote_source
username: <SOME_PRIVILEGED_ACCOUNT>
password:
host: <SOME_HOST>
---
These users will need root privileges
EOS
end
desc "Setup the demo"
- task :setup => ["demo:instructions", "environment", "db:create","db:migrate","db:fixtures:load"] do
- puts "mkay, you should be able do rake demo:run now"
+ task :setup => ["demo:instructions", "environment"] do
+
end
desc "Run the demo"
- task :run => ['environment'] do
- require '../lib/mysql_mirror'
- puts 'MySqlMirror Demo'
- # Basic usage, copy production db to development
- # @m = MysqlMirror.new({
- # :source => :production,
- # :target => :development
- # })
- #
- # Choose what tables you want to bring over and how you want to scope them...
- # @m = MysqlMirror.new({
- # :source => :production,
- # :target => :development,
- # :tables => [:users, :widgets],
- # :where => {:users => "is_admin NOT NULL"},
- # })
- #
- # Database information not in your database.yml file? (Or Not Running Rails?) No Problem!
- # @m = MysqlMirror.new({
- # :source => { :database => "app_production", :user => ..., :password => ..., :hostname => ...},
- # :target => {:database => "app_development", :hostname => 'localhost'}
- # })
- #
- # Want to use everything in :production environment (user, pass, host) but need to change the database?
- # @m = MysqlMirror.new({
- # :source => :production,
- # :override => {:source => {:database => "heavy_calculations_database"}},
- # :target => :production
- # })
- require 'ostruct'
- @demos = []
- @demos << OpenStruct.new(:name => "Basic usage, copy production db to development",
- :code => Proc.new {
- @m = MysqlMirror.new({
- :source => :production,
- :target => :development
- })
- })
- @demos.each do |demo|
- demo.code.call(binding)
- puts @m.inspect
- end
+ task :run => :environment do
+
end
end
diff --git a/demo/log/development.log b/demo/log/development.log
index 5bb9719..e69de29 100644
--- a/demo/log/development.log
+++ b/demo/log/development.log
@@ -1,17 +0,0 @@
- [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;35;1mSQL (0.3ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (205.3ms)[0m [0;1mCREATE TABLE `schema_migrations` (`version` varchar(255) NOT NULL) ENGINE=InnoDB[0m
- [4;35;1mSQL (141.6ms)[0m [0mCREATE UNIQUE INDEX `unique_schema_migrations` ON `schema_migrations` (`version`)[0m
- [4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
- [4;35;1mSQL (0.2ms)[0m [0mSELECT version FROM schema_migrations[0m
-Migrating to CreateT1s (20100406015530)
- [4;36;1mSQL (117.3ms)[0m [0;1mCREATE TABLE `t1s` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `name` varchar(255), `created_at` datetime, `updated_at` datetime) ENGINE=InnoDB[0m
- [4;35;1mSQL (0.5ms)[0m [0mINSERT INTO schema_migrations (version) VALUES ('20100406015530')[0m
- [4;36;1mSQL (0.4ms)[0m [0;1mSHOW TABLES[0m
- [4;35;1mSQL (0.2ms)[0m [0mSELECT version FROM schema_migrations[0m
- [4;36;1mSQL (0.2ms)[0m [0;1mSHOW TABLES[0m
- [4;35;1mSQL (1.0ms)[0m [0mSHOW FIELDS FROM `t1s`[0m
- [4;36;1mSQL (1.2ms)[0m [0;1mdescribe `t1s`[0m
- [4;35;1mSQL (0.7ms)[0m [0mSHOW KEYS FROM `t1s`[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
diff --git a/lib/mysql_mirror.rb b/lib/mysql_mirror.rb
index 48091c6..9d96ff3 100644
--- a/lib/mysql_mirror.rb
+++ b/lib/mysql_mirror.rb
@@ -1,212 +1,209 @@
require 'active_record'
require 'fileutils'
class MysqlMirror
class MysqlMirrorException < Exception; end
class InvalidStrategy < Exception; end
class InvalidConfiguration < Exception; end
class Source < ActiveRecord::Base
end
class Target < ActiveRecord::Base
end
- attr_accessor :tables, :where, :strategy
+ attr_accessor :tables, :where
def initialize(options = {})
unless ([:source, :target] - options.keys).blank?
# Need to specify a Source and Target database
raise MysqlMirrorException.new("You must specify both Source and Target connections")
end
self.tables = options.delete(:tables)
self.where = options.delete(:where)
overrides = options.delete(:override) || {}
source_override = overrides.delete(:source) || {}
target_override = overrides.delete(:target) || {}
@source_config = get_configuration(options.delete(:source))
@target_config = get_configuration(options.delete(:target))
@source_config.merge!(source_override)
@target_config.merge!(target_override)
# @commands is an array of methods to call
if mirroring_same_host?
@commands = commands_for_local_mirror
else
@commands = commands_for_remote_mirror
end
- debugger
end
def commands_for_local_mirror
case self.strategy
when :atomic_rename
when :bomb_and_rebuild
when :replace_existing
[:local_copy]
else
raise InvalidStrategy.new("Invalid mirror strategy")
end
end
def commands_for_remote_mirror
[
:remote_mysqldump,
:remote_tmp_file_table_rename,
:remote_insert_command,
:remote_rename_tmp_tables,
:remote_remove_tmp_file
]
end
def mirroring_same_host?
@source_config[:host] == @target_config[:host]
end
def execute!
@start_time = Time.now
@source = connect_to(:source)
@target = connect_to(:target)
@commands.each do |c|
self.send(c)
end
end
def to_s
"Mirroring #{self.tables.join(', ')} from #{@source_config[:host]}.#{@source_config[:database]} to #{@target_config[:host]}.#{@target_config[:database]}"
end
private
# e.g, connect_to(:source)
# => MysqlMirror::Source.establish_connection(@source_config).connection
#
def connect_to(which)
"MysqlMirror::#{which.to_s.classify}".constantize.establish_connection(self.instance_variable_get("@#{which}_config")).connection
end
def local_copy
get_tables.each do |table|
target_db = @target_config[:database]
source_db = @source_config[:database]
target_table = "#{target_db}.#{table}"
target_tmp_table = "#{target_db}.#{table}_MirrorTmp"
target_old_table = "#{target_db}.#{table}_OldMarkedToDelete"
source_table = "#{source_db}.#{table}"
prime_statement_1 = "DROP TABLE IF EXISTS #{target_tmp_table}"
prime_statement_2 = "CREATE TABLE IF NOT EXISTS #{target_table} LIKE #{source_table}"
create_statement = "CREATE TABLE #{target_tmp_table} LIKE #{source_table}"
select_clause = "SELECT * FROM #{source_table}"
select_clause << " WHERE #{self.where[table]}" unless (self.where.blank? or self.where[table].blank?)
insert_statement = "INSERT INTO #{target_tmp_table} #{select_clause}"
rename_statement = "RENAME TABLE #{target_table} TO #{target_old_table}, #{target_tmp_table} TO #{target_table}"
cleanup_statement = "DROP TABLE IF EXISTS #{target_old_table}"
staments_to_run = [prime_statement_1, prime_statement_2, create_statement, insert_statement, rename_statement, cleanup_statement]
staments_to_run.each do |statement|
@target.execute(statement)
end
end
end
def mysqldump_command_prefix
"mysqldump --compact=TRUE --max_allowed_packet=100663296 --extended-insert=TRUE --lock-tables=FALSE --add-locks=FALSE --add-drop-table=FALSE"
end
def remote_mysqldump
@tmp_file_name = "mysql_mirror_#{@start_time.to_i}.sql"
tables = get_tables.map(&:to_s).join(" ")
if self.where.blank?
where = ""
else
where_statement = self.where.values.first
where = "--where=\"#{where_statement}\""
end
config = "-u#{@source_config[:username]} -p'#{@source_config[:password]}' -h #{@source_config[:host]} #{@source_config[:database]}"
the_cmd = "#{mysqldump_command_prefix} #{where} #{config} #{tables} > #{@tmp_file_name}"
puts the_cmd
`#{the_cmd}`
end
def remote_tmp_file_table_rename
create_or_insert_regex = Regexp.new('(^CREATE TABLE|^INSERT INTO)( `)(.+?)(`)(.+)')
new_file_name = @tmp_file_name + ".replaced.sql"
new_file = File.new(new_file_name, "w")
IO.foreach(@tmp_file_name) do |line|
if match_data = line.match(create_or_insert_regex)
table_name = match_data[3]
new_table_name = "#{table_name}_#{@start_time.to_i}"
new_file.puts match_data[1] + match_data[2] + new_table_name + match_data[4]+ match_data[5]
else
new_file.puts line
end
end
new_file.close
# replace dump'd sql file with this gsub'd one
FileUtils.move(new_file_name, @tmp_file_name)
end
def remote_insert_command
config = "-u#{@target_config[:username]} -p'#{@target_config[:password]}' -h #{@target_config[:host]} #{@target_config[:database]}"
the_cmd = "mysql #{config} < #{@tmp_file_name}"
`#{the_cmd}`
end
def remote_rename_tmp_tables
get_tables.each do |table|
tmp_table_name = "#{table}_#{@start_time.to_i}"
old_table_name = "#{table}_OldMarkedToDelete"
@target.transaction do
@target.execute("DROP TABLE IF EXISTS #{old_table_name}")
@target.execute("RENAME TABLE #{table} TO #{old_table_name}, #{tmp_table_name} TO #{table}")
@target.execute("DROP TABLE IF EXISTS #{old_table_name}")
end
end
end
def remote_remove_tmp_file
FileUtils.rm(@tmp_file_name)
end
def get_tables
the_tables = self.tables.blank? ? @source.select_values("SHOW TABLES").map!(&:to_sym) : self.tables
end
def get_configuration(env_or_hash)
config = env_or_hash
if(env_or_hash.is_a? Symbol)
config = ActiveRecord::Base.configurations[env_or_hash.to_s]
end
- if config.blank?
- raise InvalidConfiguration.new("Specified configuration, #{env_or_hash.inspect}, does not exist.")
- end
+ raise InvalidConfiguration.new("Specified configuration, #{env_or_hash.inspect}, does not exist.")
config.symbolize_keys
end
end
|
pjleonhardt/mysql_mirror
|
208b9ddb3bdb4c12adb2dcaaf4a13e71ebd9226b
|
Revert "Okay, done for the night, still a bit sloppy, not releaseable yet"
|
diff --git a/demo/app/models/t1.rb b/demo/app/models/t1.rb
deleted file mode 100644
index 8f9a270..0000000
--- a/demo/app/models/t1.rb
+++ /dev/null
@@ -1,2 +0,0 @@
-class T1 < ActiveRecord::Base
-end
diff --git a/demo/config/database.yml b/demo/config/database.yml
index e6092f4..b9d9e57 100644
--- a/demo/config/database.yml
+++ b/demo/config/database.yml
@@ -1,15 +1,15 @@
# SQLite version 3.x
# gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
adapter: mysql
- database: mm_demo_development
+ database: mm_demo_local_source
username: root
password:
socket: /tmp/mysql.sock
production:
adapter: mysql
- database: mm_demo_production
+ database: mm_demo_local_source
username: root
password:
socket: /tmp/mysql.sock
\ No newline at end of file
diff --git a/demo/config/environment.rb b/demo/config/environment.rb
index 834bbb8..029a58b 100644
--- a/demo/config/environment.rb
+++ b/demo/config/environment.rb
@@ -1,43 +1,41 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
-end
-
-load '../lib/mysql_mirror.rb'
\ No newline at end of file
+end
\ No newline at end of file
diff --git a/demo/lib/tasks/demo.rake b/demo/lib/tasks/demo.rake
index 723a529..f39cc59 100644
--- a/demo/lib/tasks/demo.rake
+++ b/demo/lib/tasks/demo.rake
@@ -1,74 +1,75 @@
namespace :demo do
desc "requirements for the basic demo"
task :instructions do
s =<<-EOS
---
Setup privileged MySql user accounts and add this to database.yml
development:
adapter: mysql
database: mm_demo_local_source
username: root
password:
socket: /tmp/mysql.sock
production:
adapter: mysql
database: mm_demo_remote_target
username: <SOME_PRIVILEGED_ACCOUNT>
password:
host: <SOME_HOST>
---
These users will need root privileges
EOS
end
desc "Setup the demo"
task :setup => ["demo:instructions", "environment", "db:create","db:migrate","db:fixtures:load"] do
- puts "mkay, you're good on RAILS_ENV=#{RAILS_ENV}, do it again for the other ones"
+ puts "mkay, you should be able do rake demo:run now"
end
-
desc "Run the demo"
task :run => ['environment'] do
require '../lib/mysql_mirror'
puts 'MySqlMirror Demo'
- # TODO: Move these other guys in...
+ # Basic usage, copy production db to development
+ # @m = MysqlMirror.new({
+ # :source => :production,
+ # :target => :development
+ # })
#
# Choose what tables you want to bring over and how you want to scope them...
# @m = MysqlMirror.new({
# :source => :production,
# :target => :development,
# :tables => [:users, :widgets],
# :where => {:users => "is_admin NOT NULL"},
# })
#
# Database information not in your database.yml file? (Or Not Running Rails?) No Problem!
# @m = MysqlMirror.new({
# :source => { :database => "app_production", :user => ..., :password => ..., :hostname => ...},
# :target => {:database => "app_development", :hostname => 'localhost'}
# })
#
# Want to use everything in :production environment (user, pass, host) but need to change the database?
# @m = MysqlMirror.new({
# :source => :production,
# :override => {:source => {:database => "heavy_calculations_database"}},
# :target => :production
# })
require 'ostruct'
@demos = []
@demos << OpenStruct.new(:name => "Basic usage, copy production db to development",
:code => Proc.new {
@m = MysqlMirror.new({
:source => :production,
:target => :development
})
})
@demos.each do |demo|
demo.code.call(binding)
puts @m.inspect
- puts "CALLING"
- @m.execute!
end
end
end
diff --git a/demo/log/development.log b/demo/log/development.log
index 589ae23..5bb9719 100644
--- a/demo/log/development.log
+++ b/demo/log/development.log
@@ -1,139 +1,17 @@
-# Logfile created on Mon Apr 05 21:59:23 -0500 2010 [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
- [4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
- [4;35;1mSQL (0.2ms)[0m [0mDROP TABLE IF EXISTS mm_demo_local_source.schema_migrations_MirrorTmp[0m
- [4;36;1mSQL (0.0ms)[0m [0;1mMysql::Error: Not unique table/alias: 'schema_migrations': CREATE TABLE IF NOT EXISTS mm_demo_local_source.schema_migrations LIKE mm_demo_local_source.schema_migrations[0m
[4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
- [4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
- [4;35;1mSQL (0.1ms)[0m [0mDROP TABLE IF EXISTS mm_demo_local_source.schema_migrations_MirrorTmp[0m
- [4;36;1mSQL (0.0ms)[0m [0;1mMysql::Error: Not unique table/alias: 'schema_migrations': CREATE TABLE IF NOT EXISTS mm_demo_local_source.schema_migrations LIKE mm_demo_local_source.schema_migrations[0m
- [4;36;1mSQL (0.2ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;35;1mSQL (0.3ms)[0m [0mCREATE DATABASE `mm_demo_development` DEFAULT CHARACTER SET `utf8` COLLATE `utf8_unicode_ci`[0m
[4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
[4;35;1mSQL (0.3ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (73.2ms)[0m [0;1mCREATE TABLE `schema_migrations` (`version` varchar(255) NOT NULL) ENGINE=InnoDB[0m
- [4;35;1mSQL (212.8ms)[0m [0mCREATE UNIQUE INDEX `unique_schema_migrations` ON `schema_migrations` (`version`)[0m
+ [4;36;1mSQL (205.3ms)[0m [0;1mCREATE TABLE `schema_migrations` (`version` varchar(255) NOT NULL) ENGINE=InnoDB[0m
+ [4;35;1mSQL (141.6ms)[0m [0mCREATE UNIQUE INDEX `unique_schema_migrations` ON `schema_migrations` (`version`)[0m
[4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
- [4;35;1mSQL (0.3ms)[0m [0mSELECT version FROM schema_migrations[0m
+ [4;35;1mSQL (0.2ms)[0m [0mSELECT version FROM schema_migrations[0m
Migrating to CreateT1s (20100406015530)
- [4;36;1mSQL (93.6ms)[0m [0;1mCREATE TABLE `t1s` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `name` varchar(255), `created_at` datetime, `updated_at` datetime) ENGINE=InnoDB[0m
+ [4;36;1mSQL (117.3ms)[0m [0;1mCREATE TABLE `t1s` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `name` varchar(255), `created_at` datetime, `updated_at` datetime) ENGINE=InnoDB[0m
[4;35;1mSQL (0.5ms)[0m [0mINSERT INTO schema_migrations (version) VALUES ('20100406015530')[0m
[4;36;1mSQL (0.4ms)[0m [0;1mSHOW TABLES[0m
[4;35;1mSQL (0.2ms)[0m [0mSELECT version FROM schema_migrations[0m
[4;36;1mSQL (0.2ms)[0m [0;1mSHOW TABLES[0m
[4;35;1mSQL (1.0ms)[0m [0mSHOW FIELDS FROM `t1s`[0m
- [4;36;1mSQL (0.9ms)[0m [0;1mdescribe `t1s`[0m
- [4;35;1mSQL (1.9ms)[0m [0mSHOW KEYS FROM `t1s`[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;35;1mSQL (0.4ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.2ms)[0m [0;1mSELECT version FROM schema_migrations[0m
-Migrating to CreateT1s (20100406015530)
- [4;35;1mSQL (0.3ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.2ms)[0m [0;1mSELECT version FROM schema_migrations[0m
- [4;35;1mSQL (0.2ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.9ms)[0m [0;1mSHOW FIELDS FROM `t1s`[0m
- [4;35;1mSQL (1.6ms)[0m [0mdescribe `t1s`[0m
- [4;36;1mSQL (0.4ms)[0m [0;1mSHOW KEYS FROM `t1s`[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;35;1mSQL (0.4ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.2ms)[0m [0;1mSELECT version FROM schema_migrations[0m
-Migrating to CreateT1s (20100406015530)
- [4;35;1mSQL (0.3ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSELECT version FROM schema_migrations[0m
- [4;35;1mSQL (0.2ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.9ms)[0m [0;1mSHOW FIELDS FROM `t1s`[0m
- [4;35;1mSQL (1.6ms)[0m [0mdescribe `t1s`[0m
- [4;36;1mSQL (0.4ms)[0m [0;1mSHOW KEYS FROM `t1s`[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;35;1mSQL (0.4ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.2ms)[0m [0;1mSELECT version FROM schema_migrations[0m
-Migrating to CreateT1s (20100406015530)
- [4;35;1mSQL (0.3ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSELECT version FROM schema_migrations[0m
- [4;35;1mSQL (0.2ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.9ms)[0m [0;1mSHOW FIELDS FROM `t1s`[0m
- [4;35;1mSQL (1.6ms)[0m [0mdescribe `t1s`[0m
- [4;36;1mSQL (0.4ms)[0m [0;1mSHOW KEYS FROM `t1s`[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
- [4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
- [4;35;1mSQL (0.2ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_MirrorTmp[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.schema_migrations LIKE mm_demo_production.schema_migrations[0m
- [4;35;1mSQL (64.0ms)[0m [0mCREATE TABLE mm_demo_development.schema_migrations_MirrorTmp LIKE mm_demo_production.schema_migrations[0m
- [4;36;1mSQL (0.6ms)[0m [0;1mINSERT INTO mm_demo_development.schema_migrations_MirrorTmp SELECT * FROM mm_demo_production.schema_migrations[0m
- [4;35;1mSQL (1.7ms)[0m [0mRENAME TABLE mm_demo_development.schema_migrations TO mm_demo_development.schema_migrations_OldMarkedToDelete, mm_demo_development.schema_migrations_MirrorTmp TO mm_demo_development.schema_migrations[0m
- [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_OldMarkedToDelete[0m
- [4;35;1mSQL (0.1ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.t1s_MirrorTmp[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.t1s LIKE mm_demo_production.t1s[0m
- [4;35;1mSQL (220.4ms)[0m [0mCREATE TABLE mm_demo_development.t1s_MirrorTmp LIKE mm_demo_production.t1s[0m
- [4;36;1mSQL (0.3ms)[0m [0;1mINSERT INTO mm_demo_development.t1s_MirrorTmp SELECT * FROM mm_demo_production.t1s[0m
- [4;35;1mSQL (2.1ms)[0m [0mRENAME TABLE mm_demo_development.t1s TO mm_demo_development.t1s_OldMarkedToDelete, mm_demo_development.t1s_MirrorTmp TO mm_demo_development.t1s[0m
- [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.t1s_OldMarkedToDelete[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;35;1mSQL (0.4ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.3ms)[0m [0;1mSELECT version FROM schema_migrations[0m
-Migrating to CreateT1s (20100406015530)
- [4;35;1mSQL (0.3ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSELECT version FROM schema_migrations[0m
- [4;35;1mSQL (0.2ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.9ms)[0m [0;1mSHOW FIELDS FROM `t1s`[0m
- [4;35;1mSQL (1.6ms)[0m [0mdescribe `t1s`[0m
- [4;36;1mSQL (0.3ms)[0m [0;1mSHOW KEYS FROM `t1s`[0m
+ [4;36;1mSQL (1.2ms)[0m [0;1mdescribe `t1s`[0m
+ [4;35;1mSQL (0.7ms)[0m [0mSHOW KEYS FROM `t1s`[0m
[4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
- [4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
- [4;35;1mSQL (0.2ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_MirrorTmp[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.schema_migrations LIKE mm_demo_production.schema_migrations[0m
- [4;35;1mSQL (77.3ms)[0m [0mCREATE TABLE mm_demo_development.schema_migrations_MirrorTmp LIKE mm_demo_production.schema_migrations[0m
- [4;36;1mSQL (21.2ms)[0m [0;1mINSERT INTO mm_demo_development.schema_migrations_MirrorTmp SELECT * FROM mm_demo_production.schema_migrations[0m
- [4;35;1mSQL (1.7ms)[0m [0mRENAME TABLE mm_demo_development.schema_migrations TO mm_demo_development.schema_migrations_OldMarkedToDelete, mm_demo_development.schema_migrations_MirrorTmp TO mm_demo_development.schema_migrations[0m
- [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_OldMarkedToDelete[0m
- [4;35;1mSQL (0.1ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.t1s_MirrorTmp[0m
- [4;36;1mSQL (0.6ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.t1s LIKE mm_demo_production.t1s[0m
- [4;35;1mSQL (128.8ms)[0m [0mCREATE TABLE mm_demo_development.t1s_MirrorTmp LIKE mm_demo_production.t1s[0m
- [4;36;1mSQL (0.4ms)[0m [0;1mINSERT INTO mm_demo_development.t1s_MirrorTmp SELECT * FROM mm_demo_production.t1s[0m
- [4;35;1mSQL (1.3ms)[0m [0mRENAME TABLE mm_demo_development.t1s TO mm_demo_development.t1s_OldMarkedToDelete, mm_demo_development.t1s_MirrorTmp TO mm_demo_development.t1s[0m
- [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.t1s_OldMarkedToDelete[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
- [4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
- [4;35;1mSQL (0.2ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_MirrorTmp[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.schema_migrations LIKE mm_demo_production.schema_migrations[0m
- [4;35;1mSQL (88.2ms)[0m [0mCREATE TABLE mm_demo_development.schema_migrations_MirrorTmp LIKE mm_demo_production.schema_migrations[0m
- [4;36;1mSQL (21.2ms)[0m [0;1mINSERT INTO mm_demo_development.schema_migrations_MirrorTmp SELECT * FROM mm_demo_production.schema_migrations[0m
- [4;35;1mSQL (1.6ms)[0m [0mRENAME TABLE mm_demo_development.schema_migrations TO mm_demo_development.schema_migrations_OldMarkedToDelete, mm_demo_development.schema_migrations_MirrorTmp TO mm_demo_development.schema_migrations[0m
- [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_OldMarkedToDelete[0m
- [4;35;1mSQL (0.1ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.t1s_MirrorTmp[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.t1s LIKE mm_demo_production.t1s[0m
- [4;35;1mSQL (234.6ms)[0m [0mCREATE TABLE mm_demo_development.t1s_MirrorTmp LIKE mm_demo_production.t1s[0m
- [4;36;1mSQL (0.3ms)[0m [0;1mINSERT INTO mm_demo_development.t1s_MirrorTmp SELECT * FROM mm_demo_production.t1s[0m
- [4;35;1mSQL (1.3ms)[0m [0mRENAME TABLE mm_demo_development.t1s TO mm_demo_development.t1s_OldMarkedToDelete, mm_demo_development.t1s_MirrorTmp TO mm_demo_development.t1s[0m
- [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.t1s_OldMarkedToDelete[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;35;1mSQL (0.4ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.3ms)[0m [0;1mSELECT version FROM schema_migrations[0m
-Migrating to CreateT1s (20100406015530)
- [4;35;1mSQL (0.3ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSELECT version FROM schema_migrations[0m
- [4;35;1mSQL (0.2ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (0.9ms)[0m [0;1mSHOW FIELDS FROM `t1s`[0m
- [4;35;1mSQL (1.6ms)[0m [0mdescribe `t1s`[0m
- [4;36;1mSQL (0.5ms)[0m [0;1mSHOW KEYS FROM `t1s`[0m
- [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
- [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
- [4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
- [4;35;1mSQL (0.2ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_MirrorTmp[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.schema_migrations LIKE mm_demo_production.schema_migrations[0m
- [4;35;1mSQL (55.2ms)[0m [0mCREATE TABLE mm_demo_development.schema_migrations_MirrorTmp LIKE mm_demo_production.schema_migrations[0m
- [4;36;1mSQL (0.7ms)[0m [0;1mINSERT INTO mm_demo_development.schema_migrations_MirrorTmp SELECT * FROM mm_demo_production.schema_migrations[0m
- [4;35;1mSQL (1.4ms)[0m [0mRENAME TABLE mm_demo_development.schema_migrations TO mm_demo_development.schema_migrations_OldMarkedToDelete, mm_demo_development.schema_migrations_MirrorTmp TO mm_demo_development.schema_migrations[0m
- [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_OldMarkedToDelete[0m
- [4;35;1mSQL (0.1ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.t1s_MirrorTmp[0m
- [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.t1s LIKE mm_demo_production.t1s[0m
- [4;35;1mSQL (107.8ms)[0m [0mCREATE TABLE mm_demo_development.t1s_MirrorTmp LIKE mm_demo_production.t1s[0m
- [4;36;1mSQL (14.2ms)[0m [0;1mINSERT INTO mm_demo_development.t1s_MirrorTmp SELECT * FROM mm_demo_production.t1s[0m
- [4;35;1mSQL (1.4ms)[0m [0mRENAME TABLE mm_demo_development.t1s TO mm_demo_development.t1s_OldMarkedToDelete, mm_demo_development.t1s_MirrorTmp TO mm_demo_development.t1s[0m
- [4;36;1mSQL (1.0ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.t1s_OldMarkedToDelete[0m
diff --git a/demo/test/fixtures/t1s.yml b/demo/test/fixtures/t1s.yml
deleted file mode 100644
index 228a2f4..0000000
--- a/demo/test/fixtures/t1s.yml
+++ /dev/null
@@ -1,4 +0,0 @@
-<% 1000.times do |t| %>
-r<%= t%>:
- name: r<%= t%>--<%= rand.to_s %>
-<% end %>
diff --git a/lib/mysql_mirror.rb b/lib/mysql_mirror.rb
index c0703de..48091c6 100644
--- a/lib/mysql_mirror.rb
+++ b/lib/mysql_mirror.rb
@@ -1,249 +1,212 @@
require 'active_record'
require 'fileutils'
-require 'yaml'
+
class MysqlMirror
class MysqlMirrorException < Exception; end
class InvalidStrategy < Exception; end
class InvalidConfiguration < Exception; end
- VALID_STRATEGIES = [:replace_existing, :bomb_and_rebuild, :atomic_rename]
-
class Source < ActiveRecord::Base
end
class Target < ActiveRecord::Base
end
- attr_accessor :tables, :where, :strategy, :config_file_path
+ attr_accessor :tables, :where, :strategy
- attr_reader :config # For MysqlMirror behavior defaults
def initialize(options = {})
- # Need to specify a Source and Target database
unless ([:source, :target] - options.keys).blank?
+ # Need to specify a Source and Target database
raise MysqlMirrorException.new("You must specify both Source and Target connections")
end
- # Optional, a path to a YAML file that configures the tool
- if options[:config_file_path]
- self.config_file_path = 'TODO'
- elsif File.exists?("./mysql_mirror.yml")
- self.config_file_path = 'TODO'
- else
- self.config_file_path = "#{File.dirname(__FILE__)}/mysql_mirror.yml"
- end
- extract_config
-
self.tables = options.delete(:tables)
self.where = options.delete(:where)
overrides = options.delete(:override) || {}
source_override = overrides.delete(:source) || {}
target_override = overrides.delete(:target) || {}
@source_config = get_configuration(options.delete(:source))
@target_config = get_configuration(options.delete(:target))
@source_config.merge!(source_override)
@target_config.merge!(target_override)
-
# @commands is an array of methods to call
if mirroring_same_host?
@commands = commands_for_local_mirror
else
@commands = commands_for_remote_mirror
end
- end
-
-
- # yanks stuff from the mysql mirror config file
- def extract_config
- begin
- @config = YAML.load(File.read(self.config_file_path))
- rescue Exception => e
- puts "Your YAML is totally wacked out, YAML.load couldnt do its thang on #{self.config_file_path}"
- raise e
- end
-
- unless @config.kind_of? Hash
- raise InvalidMysqlMirrorConfigFormat.new("Bunk format in in #{self.config_file_path}, not a hash")
- end
- @config.symbolize_keys!
-
- if VALID_STRATEGIES.map(&:to_s).include?(@config[:strategy])
- self.strategy = @config[:strategy].to_sym
- else
- InvalidStrategy.new("Invalid mirror strategy")
- end
+ debugger
end
def commands_for_local_mirror
case self.strategy
when :atomic_rename
when :bomb_and_rebuild
when :replace_existing
[:local_copy]
+ else
+ raise InvalidStrategy.new("Invalid mirror strategy")
end
end
def commands_for_remote_mirror
- case self.strategy
- when :atomic_rename
- when :bomb_and_rebuild
- when :replace_existing
- [
- :remote_mysqldump,
- :remote_tmp_file_table_rename,
- :remote_insert_command,
- :remote_rename_tmp_tables,
- :remote_remove_tmp_file
- ]
- end
+ [
+ :remote_mysqldump,
+ :remote_tmp_file_table_rename,
+ :remote_insert_command,
+ :remote_rename_tmp_tables,
+ :remote_remove_tmp_file
+ ]
end
def mirroring_same_host?
@source_config[:host] == @target_config[:host]
end
def execute!
@start_time = Time.now
@source = connect_to(:source)
@target = connect_to(:target)
@commands.each do |c|
self.send(c)
end
end
def to_s
"Mirroring #{self.tables.join(', ')} from #{@source_config[:host]}.#{@source_config[:database]} to #{@target_config[:host]}.#{@target_config[:database]}"
end
private
# e.g, connect_to(:source)
# => MysqlMirror::Source.establish_connection(@source_config).connection
#
def connect_to(which)
"MysqlMirror::#{which.to_s.classify}".constantize.establish_connection(self.instance_variable_get("@#{which}_config")).connection
end
def local_copy
get_tables.each do |table|
target_db = @target_config[:database]
source_db = @source_config[:database]
target_table = "#{target_db}.#{table}"
target_tmp_table = "#{target_db}.#{table}_MirrorTmp"
target_old_table = "#{target_db}.#{table}_OldMarkedToDelete"
source_table = "#{source_db}.#{table}"
prime_statement_1 = "DROP TABLE IF EXISTS #{target_tmp_table}"
prime_statement_2 = "CREATE TABLE IF NOT EXISTS #{target_table} LIKE #{source_table}"
create_statement = "CREATE TABLE #{target_tmp_table} LIKE #{source_table}"
select_clause = "SELECT * FROM #{source_table}"
select_clause << " WHERE #{self.where[table]}" unless (self.where.blank? or self.where[table].blank?)
insert_statement = "INSERT INTO #{target_tmp_table} #{select_clause}"
rename_statement = "RENAME TABLE #{target_table} TO #{target_old_table}, #{target_tmp_table} TO #{target_table}"
cleanup_statement = "DROP TABLE IF EXISTS #{target_old_table}"
staments_to_run = [prime_statement_1, prime_statement_2, create_statement, insert_statement, rename_statement, cleanup_statement]
staments_to_run.each do |statement|
@target.execute(statement)
end
end
end
def mysqldump_command_prefix
"mysqldump --compact=TRUE --max_allowed_packet=100663296 --extended-insert=TRUE --lock-tables=FALSE --add-locks=FALSE --add-drop-table=FALSE"
end
def remote_mysqldump
@tmp_file_name = "mysql_mirror_#{@start_time.to_i}.sql"
tables = get_tables.map(&:to_s).join(" ")
if self.where.blank?
where = ""
else
where_statement = self.where.values.first
where = "--where=\"#{where_statement}\""
end
config = "-u#{@source_config[:username]} -p'#{@source_config[:password]}' -h #{@source_config[:host]} #{@source_config[:database]}"
the_cmd = "#{mysqldump_command_prefix} #{where} #{config} #{tables} > #{@tmp_file_name}"
puts the_cmd
`#{the_cmd}`
end
def remote_tmp_file_table_rename
create_or_insert_regex = Regexp.new('(^CREATE TABLE|^INSERT INTO)( `)(.+?)(`)(.+)')
new_file_name = @tmp_file_name + ".replaced.sql"
new_file = File.new(new_file_name, "w")
IO.foreach(@tmp_file_name) do |line|
if match_data = line.match(create_or_insert_regex)
table_name = match_data[3]
new_table_name = "#{table_name}_#{@start_time.to_i}"
new_file.puts match_data[1] + match_data[2] + new_table_name + match_data[4]+ match_data[5]
else
new_file.puts line
end
end
new_file.close
# replace dump'd sql file with this gsub'd one
FileUtils.move(new_file_name, @tmp_file_name)
end
def remote_insert_command
config = "-u#{@target_config[:username]} -p'#{@target_config[:password]}' -h #{@target_config[:host]} #{@target_config[:database]}"
the_cmd = "mysql #{config} < #{@tmp_file_name}"
`#{the_cmd}`
end
def remote_rename_tmp_tables
get_tables.each do |table|
tmp_table_name = "#{table}_#{@start_time.to_i}"
old_table_name = "#{table}_OldMarkedToDelete"
@target.transaction do
@target.execute("DROP TABLE IF EXISTS #{old_table_name}")
@target.execute("RENAME TABLE #{table} TO #{old_table_name}, #{tmp_table_name} TO #{table}")
@target.execute("DROP TABLE IF EXISTS #{old_table_name}")
end
end
end
def remote_remove_tmp_file
FileUtils.rm(@tmp_file_name)
end
def get_tables
the_tables = self.tables.blank? ? @source.select_values("SHOW TABLES").map!(&:to_sym) : self.tables
end
+
def get_configuration(env_or_hash)
config = env_or_hash
if(env_or_hash.is_a? Symbol)
config = ActiveRecord::Base.configurations[env_or_hash.to_s]
end
if config.blank?
raise InvalidConfiguration.new("Specified configuration, #{env_or_hash.inspect}, does not exist.")
end
config.symbolize_keys
end
end
diff --git a/lib/mysql_mirror.yml b/lib/mysql_mirror.yml
deleted file mode 100644
index 810fdc4..0000000
--- a/lib/mysql_mirror.yml
+++ /dev/null
@@ -1 +0,0 @@
-strategy: replace_existing
\ No newline at end of file
|
pjleonhardt/mysql_mirror
|
7ef2722aac16bf3eb18c2476e32d92522365895e
|
Okay, done for the night, still a bit sloppy, not releaseable yet
|
diff --git a/demo/app/models/t1.rb b/demo/app/models/t1.rb
new file mode 100644
index 0000000..8f9a270
--- /dev/null
+++ b/demo/app/models/t1.rb
@@ -0,0 +1,2 @@
+class T1 < ActiveRecord::Base
+end
diff --git a/demo/config/database.yml b/demo/config/database.yml
index b9d9e57..e6092f4 100644
--- a/demo/config/database.yml
+++ b/demo/config/database.yml
@@ -1,15 +1,15 @@
# SQLite version 3.x
# gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
adapter: mysql
- database: mm_demo_local_source
+ database: mm_demo_development
username: root
password:
socket: /tmp/mysql.sock
production:
adapter: mysql
- database: mm_demo_local_source
+ database: mm_demo_production
username: root
password:
socket: /tmp/mysql.sock
\ No newline at end of file
diff --git a/demo/config/environment.rb b/demo/config/environment.rb
index 029a58b..834bbb8 100644
--- a/demo/config/environment.rb
+++ b/demo/config/environment.rb
@@ -1,41 +1,43 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'UTC'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
-end
\ No newline at end of file
+end
+
+load '../lib/mysql_mirror.rb'
\ No newline at end of file
diff --git a/demo/lib/tasks/demo.rake b/demo/lib/tasks/demo.rake
index f39cc59..723a529 100644
--- a/demo/lib/tasks/demo.rake
+++ b/demo/lib/tasks/demo.rake
@@ -1,75 +1,74 @@
namespace :demo do
desc "requirements for the basic demo"
task :instructions do
s =<<-EOS
---
Setup privileged MySql user accounts and add this to database.yml
development:
adapter: mysql
database: mm_demo_local_source
username: root
password:
socket: /tmp/mysql.sock
production:
adapter: mysql
database: mm_demo_remote_target
username: <SOME_PRIVILEGED_ACCOUNT>
password:
host: <SOME_HOST>
---
These users will need root privileges
EOS
end
desc "Setup the demo"
task :setup => ["demo:instructions", "environment", "db:create","db:migrate","db:fixtures:load"] do
- puts "mkay, you should be able do rake demo:run now"
+ puts "mkay, you're good on RAILS_ENV=#{RAILS_ENV}, do it again for the other ones"
end
+
desc "Run the demo"
task :run => ['environment'] do
require '../lib/mysql_mirror'
puts 'MySqlMirror Demo'
- # Basic usage, copy production db to development
- # @m = MysqlMirror.new({
- # :source => :production,
- # :target => :development
- # })
+ # TODO: Move these other guys in...
#
# Choose what tables you want to bring over and how you want to scope them...
# @m = MysqlMirror.new({
# :source => :production,
# :target => :development,
# :tables => [:users, :widgets],
# :where => {:users => "is_admin NOT NULL"},
# })
#
# Database information not in your database.yml file? (Or Not Running Rails?) No Problem!
# @m = MysqlMirror.new({
# :source => { :database => "app_production", :user => ..., :password => ..., :hostname => ...},
# :target => {:database => "app_development", :hostname => 'localhost'}
# })
#
# Want to use everything in :production environment (user, pass, host) but need to change the database?
# @m = MysqlMirror.new({
# :source => :production,
# :override => {:source => {:database => "heavy_calculations_database"}},
# :target => :production
# })
require 'ostruct'
@demos = []
@demos << OpenStruct.new(:name => "Basic usage, copy production db to development",
:code => Proc.new {
@m = MysqlMirror.new({
:source => :production,
:target => :development
})
})
@demos.each do |demo|
demo.code.call(binding)
puts @m.inspect
+ puts "CALLING"
+ @m.execute!
end
end
end
diff --git a/demo/log/development.log b/demo/log/development.log
index 5bb9719..589ae23 100644
--- a/demo/log/development.log
+++ b/demo/log/development.log
@@ -1,17 +1,139 @@
+# Logfile created on Mon Apr 05 21:59:23 -0500 2010 [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
+ [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
+ [4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
+ [4;35;1mSQL (0.2ms)[0m [0mDROP TABLE IF EXISTS mm_demo_local_source.schema_migrations_MirrorTmp[0m
+ [4;36;1mSQL (0.0ms)[0m [0;1mMysql::Error: Not unique table/alias: 'schema_migrations': CREATE TABLE IF NOT EXISTS mm_demo_local_source.schema_migrations LIKE mm_demo_local_source.schema_migrations[0m
[4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
+ [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
+ [4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
+ [4;35;1mSQL (0.1ms)[0m [0mDROP TABLE IF EXISTS mm_demo_local_source.schema_migrations_MirrorTmp[0m
+ [4;36;1mSQL (0.0ms)[0m [0;1mMysql::Error: Not unique table/alias: 'schema_migrations': CREATE TABLE IF NOT EXISTS mm_demo_local_source.schema_migrations LIKE mm_demo_local_source.schema_migrations[0m
+ [4;36;1mSQL (0.2ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
+ [4;35;1mSQL (0.3ms)[0m [0mCREATE DATABASE `mm_demo_development` DEFAULT CHARACTER SET `utf8` COLLATE `utf8_unicode_ci`[0m
[4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
[4;35;1mSQL (0.3ms)[0m [0mSHOW TABLES[0m
- [4;36;1mSQL (205.3ms)[0m [0;1mCREATE TABLE `schema_migrations` (`version` varchar(255) NOT NULL) ENGINE=InnoDB[0m
- [4;35;1mSQL (141.6ms)[0m [0mCREATE UNIQUE INDEX `unique_schema_migrations` ON `schema_migrations` (`version`)[0m
+ [4;36;1mSQL (73.2ms)[0m [0;1mCREATE TABLE `schema_migrations` (`version` varchar(255) NOT NULL) ENGINE=InnoDB[0m
+ [4;35;1mSQL (212.8ms)[0m [0mCREATE UNIQUE INDEX `unique_schema_migrations` ON `schema_migrations` (`version`)[0m
[4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
- [4;35;1mSQL (0.2ms)[0m [0mSELECT version FROM schema_migrations[0m
+ [4;35;1mSQL (0.3ms)[0m [0mSELECT version FROM schema_migrations[0m
Migrating to CreateT1s (20100406015530)
- [4;36;1mSQL (117.3ms)[0m [0;1mCREATE TABLE `t1s` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `name` varchar(255), `created_at` datetime, `updated_at` datetime) ENGINE=InnoDB[0m
+ [4;36;1mSQL (93.6ms)[0m [0;1mCREATE TABLE `t1s` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `name` varchar(255), `created_at` datetime, `updated_at` datetime) ENGINE=InnoDB[0m
[4;35;1mSQL (0.5ms)[0m [0mINSERT INTO schema_migrations (version) VALUES ('20100406015530')[0m
[4;36;1mSQL (0.4ms)[0m [0;1mSHOW TABLES[0m
[4;35;1mSQL (0.2ms)[0m [0mSELECT version FROM schema_migrations[0m
[4;36;1mSQL (0.2ms)[0m [0;1mSHOW TABLES[0m
[4;35;1mSQL (1.0ms)[0m [0mSHOW FIELDS FROM `t1s`[0m
- [4;36;1mSQL (1.2ms)[0m [0;1mdescribe `t1s`[0m
- [4;35;1mSQL (0.7ms)[0m [0mSHOW KEYS FROM `t1s`[0m
+ [4;36;1mSQL (0.9ms)[0m [0;1mdescribe `t1s`[0m
+ [4;35;1mSQL (1.9ms)[0m [0mSHOW KEYS FROM `t1s`[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
+ [4;35;1mSQL (0.4ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.2ms)[0m [0;1mSELECT version FROM schema_migrations[0m
+Migrating to CreateT1s (20100406015530)
+ [4;35;1mSQL (0.3ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.2ms)[0m [0;1mSELECT version FROM schema_migrations[0m
+ [4;35;1mSQL (0.2ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.9ms)[0m [0;1mSHOW FIELDS FROM `t1s`[0m
+ [4;35;1mSQL (1.6ms)[0m [0mdescribe `t1s`[0m
+ [4;36;1mSQL (0.4ms)[0m [0;1mSHOW KEYS FROM `t1s`[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
+ [4;35;1mSQL (0.4ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.2ms)[0m [0;1mSELECT version FROM schema_migrations[0m
+Migrating to CreateT1s (20100406015530)
+ [4;35;1mSQL (0.3ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mSELECT version FROM schema_migrations[0m
+ [4;35;1mSQL (0.2ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.9ms)[0m [0;1mSHOW FIELDS FROM `t1s`[0m
+ [4;35;1mSQL (1.6ms)[0m [0mdescribe `t1s`[0m
+ [4;36;1mSQL (0.4ms)[0m [0;1mSHOW KEYS FROM `t1s`[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
+ [4;35;1mSQL (0.4ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.2ms)[0m [0;1mSELECT version FROM schema_migrations[0m
+Migrating to CreateT1s (20100406015530)
+ [4;35;1mSQL (0.3ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mSELECT version FROM schema_migrations[0m
+ [4;35;1mSQL (0.2ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.9ms)[0m [0;1mSHOW FIELDS FROM `t1s`[0m
+ [4;35;1mSQL (1.6ms)[0m [0mdescribe `t1s`[0m
+ [4;36;1mSQL (0.4ms)[0m [0;1mSHOW KEYS FROM `t1s`[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
+ [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
+ [4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
+ [4;35;1mSQL (0.2ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_MirrorTmp[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.schema_migrations LIKE mm_demo_production.schema_migrations[0m
+ [4;35;1mSQL (64.0ms)[0m [0mCREATE TABLE mm_demo_development.schema_migrations_MirrorTmp LIKE mm_demo_production.schema_migrations[0m
+ [4;36;1mSQL (0.6ms)[0m [0;1mINSERT INTO mm_demo_development.schema_migrations_MirrorTmp SELECT * FROM mm_demo_production.schema_migrations[0m
+ [4;35;1mSQL (1.7ms)[0m [0mRENAME TABLE mm_demo_development.schema_migrations TO mm_demo_development.schema_migrations_OldMarkedToDelete, mm_demo_development.schema_migrations_MirrorTmp TO mm_demo_development.schema_migrations[0m
+ [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_OldMarkedToDelete[0m
+ [4;35;1mSQL (0.1ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.t1s_MirrorTmp[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.t1s LIKE mm_demo_production.t1s[0m
+ [4;35;1mSQL (220.4ms)[0m [0mCREATE TABLE mm_demo_development.t1s_MirrorTmp LIKE mm_demo_production.t1s[0m
+ [4;36;1mSQL (0.3ms)[0m [0;1mINSERT INTO mm_demo_development.t1s_MirrorTmp SELECT * FROM mm_demo_production.t1s[0m
+ [4;35;1mSQL (2.1ms)[0m [0mRENAME TABLE mm_demo_development.t1s TO mm_demo_development.t1s_OldMarkedToDelete, mm_demo_development.t1s_MirrorTmp TO mm_demo_development.t1s[0m
+ [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.t1s_OldMarkedToDelete[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
+ [4;35;1mSQL (0.4ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.3ms)[0m [0;1mSELECT version FROM schema_migrations[0m
+Migrating to CreateT1s (20100406015530)
+ [4;35;1mSQL (0.3ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mSELECT version FROM schema_migrations[0m
+ [4;35;1mSQL (0.2ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.9ms)[0m [0;1mSHOW FIELDS FROM `t1s`[0m
+ [4;35;1mSQL (1.6ms)[0m [0mdescribe `t1s`[0m
+ [4;36;1mSQL (0.3ms)[0m [0;1mSHOW KEYS FROM `t1s`[0m
[4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
+ [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
+ [4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
+ [4;35;1mSQL (0.2ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_MirrorTmp[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.schema_migrations LIKE mm_demo_production.schema_migrations[0m
+ [4;35;1mSQL (77.3ms)[0m [0mCREATE TABLE mm_demo_development.schema_migrations_MirrorTmp LIKE mm_demo_production.schema_migrations[0m
+ [4;36;1mSQL (21.2ms)[0m [0;1mINSERT INTO mm_demo_development.schema_migrations_MirrorTmp SELECT * FROM mm_demo_production.schema_migrations[0m
+ [4;35;1mSQL (1.7ms)[0m [0mRENAME TABLE mm_demo_development.schema_migrations TO mm_demo_development.schema_migrations_OldMarkedToDelete, mm_demo_development.schema_migrations_MirrorTmp TO mm_demo_development.schema_migrations[0m
+ [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_OldMarkedToDelete[0m
+ [4;35;1mSQL (0.1ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.t1s_MirrorTmp[0m
+ [4;36;1mSQL (0.6ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.t1s LIKE mm_demo_production.t1s[0m
+ [4;35;1mSQL (128.8ms)[0m [0mCREATE TABLE mm_demo_development.t1s_MirrorTmp LIKE mm_demo_production.t1s[0m
+ [4;36;1mSQL (0.4ms)[0m [0;1mINSERT INTO mm_demo_development.t1s_MirrorTmp SELECT * FROM mm_demo_production.t1s[0m
+ [4;35;1mSQL (1.3ms)[0m [0mRENAME TABLE mm_demo_development.t1s TO mm_demo_development.t1s_OldMarkedToDelete, mm_demo_development.t1s_MirrorTmp TO mm_demo_development.t1s[0m
+ [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.t1s_OldMarkedToDelete[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
+ [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
+ [4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
+ [4;35;1mSQL (0.2ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_MirrorTmp[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.schema_migrations LIKE mm_demo_production.schema_migrations[0m
+ [4;35;1mSQL (88.2ms)[0m [0mCREATE TABLE mm_demo_development.schema_migrations_MirrorTmp LIKE mm_demo_production.schema_migrations[0m
+ [4;36;1mSQL (21.2ms)[0m [0;1mINSERT INTO mm_demo_development.schema_migrations_MirrorTmp SELECT * FROM mm_demo_production.schema_migrations[0m
+ [4;35;1mSQL (1.6ms)[0m [0mRENAME TABLE mm_demo_development.schema_migrations TO mm_demo_development.schema_migrations_OldMarkedToDelete, mm_demo_development.schema_migrations_MirrorTmp TO mm_demo_development.schema_migrations[0m
+ [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_OldMarkedToDelete[0m
+ [4;35;1mSQL (0.1ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.t1s_MirrorTmp[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.t1s LIKE mm_demo_production.t1s[0m
+ [4;35;1mSQL (234.6ms)[0m [0mCREATE TABLE mm_demo_development.t1s_MirrorTmp LIKE mm_demo_production.t1s[0m
+ [4;36;1mSQL (0.3ms)[0m [0;1mINSERT INTO mm_demo_development.t1s_MirrorTmp SELECT * FROM mm_demo_production.t1s[0m
+ [4;35;1mSQL (1.3ms)[0m [0mRENAME TABLE mm_demo_development.t1s TO mm_demo_development.t1s_OldMarkedToDelete, mm_demo_development.t1s_MirrorTmp TO mm_demo_development.t1s[0m
+ [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.t1s_OldMarkedToDelete[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
+ [4;35;1mSQL (0.4ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.3ms)[0m [0;1mSELECT version FROM schema_migrations[0m
+Migrating to CreateT1s (20100406015530)
+ [4;35;1mSQL (0.3ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mSELECT version FROM schema_migrations[0m
+ [4;35;1mSQL (0.2ms)[0m [0mSHOW TABLES[0m
+ [4;36;1mSQL (0.9ms)[0m [0;1mSHOW FIELDS FROM `t1s`[0m
+ [4;35;1mSQL (1.6ms)[0m [0mdescribe `t1s`[0m
+ [4;36;1mSQL (0.5ms)[0m [0;1mSHOW KEYS FROM `t1s`[0m
+ [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
+ [4;35;1mSQL (0.1ms)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
+ [4;36;1mSQL (0.3ms)[0m [0;1mSHOW TABLES[0m
+ [4;35;1mSQL (0.2ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_MirrorTmp[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.schema_migrations LIKE mm_demo_production.schema_migrations[0m
+ [4;35;1mSQL (55.2ms)[0m [0mCREATE TABLE mm_demo_development.schema_migrations_MirrorTmp LIKE mm_demo_production.schema_migrations[0m
+ [4;36;1mSQL (0.7ms)[0m [0;1mINSERT INTO mm_demo_development.schema_migrations_MirrorTmp SELECT * FROM mm_demo_production.schema_migrations[0m
+ [4;35;1mSQL (1.4ms)[0m [0mRENAME TABLE mm_demo_development.schema_migrations TO mm_demo_development.schema_migrations_OldMarkedToDelete, mm_demo_development.schema_migrations_MirrorTmp TO mm_demo_development.schema_migrations[0m
+ [4;36;1mSQL (0.9ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.schema_migrations_OldMarkedToDelete[0m
+ [4;35;1mSQL (0.1ms)[0m [0mDROP TABLE IF EXISTS mm_demo_development.t1s_MirrorTmp[0m
+ [4;36;1mSQL (0.1ms)[0m [0;1mCREATE TABLE IF NOT EXISTS mm_demo_development.t1s LIKE mm_demo_production.t1s[0m
+ [4;35;1mSQL (107.8ms)[0m [0mCREATE TABLE mm_demo_development.t1s_MirrorTmp LIKE mm_demo_production.t1s[0m
+ [4;36;1mSQL (14.2ms)[0m [0;1mINSERT INTO mm_demo_development.t1s_MirrorTmp SELECT * FROM mm_demo_production.t1s[0m
+ [4;35;1mSQL (1.4ms)[0m [0mRENAME TABLE mm_demo_development.t1s TO mm_demo_development.t1s_OldMarkedToDelete, mm_demo_development.t1s_MirrorTmp TO mm_demo_development.t1s[0m
+ [4;36;1mSQL (1.0ms)[0m [0;1mDROP TABLE IF EXISTS mm_demo_development.t1s_OldMarkedToDelete[0m
diff --git a/demo/test/fixtures/t1s.yml b/demo/test/fixtures/t1s.yml
new file mode 100644
index 0000000..228a2f4
--- /dev/null
+++ b/demo/test/fixtures/t1s.yml
@@ -0,0 +1,4 @@
+<% 1000.times do |t| %>
+r<%= t%>:
+ name: r<%= t%>--<%= rand.to_s %>
+<% end %>
diff --git a/lib/mysql_mirror.rb b/lib/mysql_mirror.rb
index 48091c6..c0703de 100644
--- a/lib/mysql_mirror.rb
+++ b/lib/mysql_mirror.rb
@@ -1,212 +1,249 @@
require 'active_record'
require 'fileutils'
-
+require 'yaml'
class MysqlMirror
class MysqlMirrorException < Exception; end
class InvalidStrategy < Exception; end
class InvalidConfiguration < Exception; end
+ VALID_STRATEGIES = [:replace_existing, :bomb_and_rebuild, :atomic_rename]
+
class Source < ActiveRecord::Base
end
class Target < ActiveRecord::Base
end
- attr_accessor :tables, :where, :strategy
+ attr_accessor :tables, :where, :strategy, :config_file_path
+ attr_reader :config # For MysqlMirror behavior defaults
def initialize(options = {})
+ # Need to specify a Source and Target database
unless ([:source, :target] - options.keys).blank?
- # Need to specify a Source and Target database
raise MysqlMirrorException.new("You must specify both Source and Target connections")
end
+ # Optional, a path to a YAML file that configures the tool
+ if options[:config_file_path]
+ self.config_file_path = 'TODO'
+ elsif File.exists?("./mysql_mirror.yml")
+ self.config_file_path = 'TODO'
+ else
+ self.config_file_path = "#{File.dirname(__FILE__)}/mysql_mirror.yml"
+ end
+ extract_config
+
self.tables = options.delete(:tables)
self.where = options.delete(:where)
overrides = options.delete(:override) || {}
source_override = overrides.delete(:source) || {}
target_override = overrides.delete(:target) || {}
@source_config = get_configuration(options.delete(:source))
@target_config = get_configuration(options.delete(:target))
@source_config.merge!(source_override)
@target_config.merge!(target_override)
+
# @commands is an array of methods to call
if mirroring_same_host?
@commands = commands_for_local_mirror
else
@commands = commands_for_remote_mirror
end
- debugger
+ end
+
+
+ # yanks stuff from the mysql mirror config file
+ def extract_config
+ begin
+ @config = YAML.load(File.read(self.config_file_path))
+ rescue Exception => e
+ puts "Your YAML is totally wacked out, YAML.load couldnt do its thang on #{self.config_file_path}"
+ raise e
+ end
+
+ unless @config.kind_of? Hash
+ raise InvalidMysqlMirrorConfigFormat.new("Bunk format in in #{self.config_file_path}, not a hash")
+ end
+ @config.symbolize_keys!
+
+ if VALID_STRATEGIES.map(&:to_s).include?(@config[:strategy])
+ self.strategy = @config[:strategy].to_sym
+ else
+ InvalidStrategy.new("Invalid mirror strategy")
+ end
end
def commands_for_local_mirror
case self.strategy
when :atomic_rename
when :bomb_and_rebuild
when :replace_existing
[:local_copy]
- else
- raise InvalidStrategy.new("Invalid mirror strategy")
end
end
def commands_for_remote_mirror
- [
- :remote_mysqldump,
- :remote_tmp_file_table_rename,
- :remote_insert_command,
- :remote_rename_tmp_tables,
- :remote_remove_tmp_file
- ]
+ case self.strategy
+ when :atomic_rename
+ when :bomb_and_rebuild
+ when :replace_existing
+ [
+ :remote_mysqldump,
+ :remote_tmp_file_table_rename,
+ :remote_insert_command,
+ :remote_rename_tmp_tables,
+ :remote_remove_tmp_file
+ ]
+ end
end
def mirroring_same_host?
@source_config[:host] == @target_config[:host]
end
def execute!
@start_time = Time.now
@source = connect_to(:source)
@target = connect_to(:target)
@commands.each do |c|
self.send(c)
end
end
def to_s
"Mirroring #{self.tables.join(', ')} from #{@source_config[:host]}.#{@source_config[:database]} to #{@target_config[:host]}.#{@target_config[:database]}"
end
private
# e.g, connect_to(:source)
# => MysqlMirror::Source.establish_connection(@source_config).connection
#
def connect_to(which)
"MysqlMirror::#{which.to_s.classify}".constantize.establish_connection(self.instance_variable_get("@#{which}_config")).connection
end
def local_copy
get_tables.each do |table|
target_db = @target_config[:database]
source_db = @source_config[:database]
target_table = "#{target_db}.#{table}"
target_tmp_table = "#{target_db}.#{table}_MirrorTmp"
target_old_table = "#{target_db}.#{table}_OldMarkedToDelete"
source_table = "#{source_db}.#{table}"
prime_statement_1 = "DROP TABLE IF EXISTS #{target_tmp_table}"
prime_statement_2 = "CREATE TABLE IF NOT EXISTS #{target_table} LIKE #{source_table}"
create_statement = "CREATE TABLE #{target_tmp_table} LIKE #{source_table}"
select_clause = "SELECT * FROM #{source_table}"
select_clause << " WHERE #{self.where[table]}" unless (self.where.blank? or self.where[table].blank?)
insert_statement = "INSERT INTO #{target_tmp_table} #{select_clause}"
rename_statement = "RENAME TABLE #{target_table} TO #{target_old_table}, #{target_tmp_table} TO #{target_table}"
cleanup_statement = "DROP TABLE IF EXISTS #{target_old_table}"
staments_to_run = [prime_statement_1, prime_statement_2, create_statement, insert_statement, rename_statement, cleanup_statement]
staments_to_run.each do |statement|
@target.execute(statement)
end
end
end
def mysqldump_command_prefix
"mysqldump --compact=TRUE --max_allowed_packet=100663296 --extended-insert=TRUE --lock-tables=FALSE --add-locks=FALSE --add-drop-table=FALSE"
end
def remote_mysqldump
@tmp_file_name = "mysql_mirror_#{@start_time.to_i}.sql"
tables = get_tables.map(&:to_s).join(" ")
if self.where.blank?
where = ""
else
where_statement = self.where.values.first
where = "--where=\"#{where_statement}\""
end
config = "-u#{@source_config[:username]} -p'#{@source_config[:password]}' -h #{@source_config[:host]} #{@source_config[:database]}"
the_cmd = "#{mysqldump_command_prefix} #{where} #{config} #{tables} > #{@tmp_file_name}"
puts the_cmd
`#{the_cmd}`
end
def remote_tmp_file_table_rename
create_or_insert_regex = Regexp.new('(^CREATE TABLE|^INSERT INTO)( `)(.+?)(`)(.+)')
new_file_name = @tmp_file_name + ".replaced.sql"
new_file = File.new(new_file_name, "w")
IO.foreach(@tmp_file_name) do |line|
if match_data = line.match(create_or_insert_regex)
table_name = match_data[3]
new_table_name = "#{table_name}_#{@start_time.to_i}"
new_file.puts match_data[1] + match_data[2] + new_table_name + match_data[4]+ match_data[5]
else
new_file.puts line
end
end
new_file.close
# replace dump'd sql file with this gsub'd one
FileUtils.move(new_file_name, @tmp_file_name)
end
def remote_insert_command
config = "-u#{@target_config[:username]} -p'#{@target_config[:password]}' -h #{@target_config[:host]} #{@target_config[:database]}"
the_cmd = "mysql #{config} < #{@tmp_file_name}"
`#{the_cmd}`
end
def remote_rename_tmp_tables
get_tables.each do |table|
tmp_table_name = "#{table}_#{@start_time.to_i}"
old_table_name = "#{table}_OldMarkedToDelete"
@target.transaction do
@target.execute("DROP TABLE IF EXISTS #{old_table_name}")
@target.execute("RENAME TABLE #{table} TO #{old_table_name}, #{tmp_table_name} TO #{table}")
@target.execute("DROP TABLE IF EXISTS #{old_table_name}")
end
end
end
def remote_remove_tmp_file
FileUtils.rm(@tmp_file_name)
end
def get_tables
the_tables = self.tables.blank? ? @source.select_values("SHOW TABLES").map!(&:to_sym) : self.tables
end
-
def get_configuration(env_or_hash)
config = env_or_hash
if(env_or_hash.is_a? Symbol)
config = ActiveRecord::Base.configurations[env_or_hash.to_s]
end
if config.blank?
raise InvalidConfiguration.new("Specified configuration, #{env_or_hash.inspect}, does not exist.")
end
config.symbolize_keys
end
end
diff --git a/lib/mysql_mirror.yml b/lib/mysql_mirror.yml
new file mode 100644
index 0000000..810fdc4
--- /dev/null
+++ b/lib/mysql_mirror.yml
@@ -0,0 +1 @@
+strategy: replace_existing
\ No newline at end of file
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.