repo
string | commit
string | message
string | diff
string |
---|---|---|---|
bohde/seinfeld
|
6f4cd50918a14d0095c29a4400951795269fdcbd
|
Nicer cakefile to build everything.
|
diff --git a/Cakefile b/Cakefile
index 933605b..f731cd9 100644
--- a/Cakefile
+++ b/Cakefile
@@ -1,22 +1,30 @@
fs = require 'fs'
sys = require 'sys'
dir = "build"
task 'build:html', 'compile the jade template files to html', () ->
jade = require 'jade'
jade.renderFile 'jade/index.jade', (err, html) ->
if err
console.log err
else
fs.mkdir "$dir", 0755,() ->
fs.writeFile "$dir/index.html", html
+coffeeFiles = [
+ "coffee/seinfeld.coffee",
+]
+
task 'build:js', 'compile the coffeescript files to js', () ->
- compile: require("child_process").spawn "coffee", ["-c", "-o", "$dir/js", "coffee/seinfeld.coffee"]
+ compile: require("child_process").spawn "coffee", ["-c", "-o", "$dir/js"].concat coffeeFiles
compile.stdout.addListener "data", (data) ->
sys.puts data
compile.stderr.addListener "data", (data) ->
sys.puts data
compile.addListener "exit", (code) ->
- sys.puts "Coffe compile exited with exit code $code."
+ sys.puts "Coffe compile exited with exit code $code." if code != 0
+
+task 'build', 'build everything', () ->
+ invoke 'build:html'
+ invoke 'build:js'
|
bohde/seinfeld
|
86d042a56b66a1d9131e6d037fec9b4ac4561d07
|
Added build for coffeescript.
|
diff --git a/Cakefile b/Cakefile
index 7de52c6..933605b 100644
--- a/Cakefile
+++ b/Cakefile
@@ -1,13 +1,22 @@
fs = require 'fs'
+sys = require 'sys'
dir = "build"
task 'build:html', 'compile the jade template files to html', () ->
jade = require 'jade'
jade.renderFile 'jade/index.jade', (err, html) ->
if err
console.log err
else
fs.mkdir "$dir", 0755,() ->
fs.writeFile "$dir/index.html", html
+task 'build:js', 'compile the coffeescript files to js', () ->
+ compile: require("child_process").spawn "coffee", ["-c", "-o", "$dir/js", "coffee/seinfeld.coffee"]
+ compile.stdout.addListener "data", (data) ->
+ sys.puts data
+ compile.stderr.addListener "data", (data) ->
+ sys.puts data
+ compile.addListener "exit", (code) ->
+ sys.puts "Coffe compile exited with exit code $code."
|
bohde/seinfeld
|
4ec7f7a95e6542ead21c1905501b795b1db9a88b
|
Added some basic code.
|
diff --git a/coffee/seinfeld.coffee b/coffee/seinfeld.coffee
new file mode 100644
index 0000000..b2cecaa
--- /dev/null
+++ b/coffee/seinfeld.coffee
@@ -0,0 +1,5 @@
+# What month is it?
+
+month: () ->
+ Date.today().getMonth()
+
diff --git a/jade/index.jade b/jade/index.jade
index 26bca68..9fea33d 100644
--- a/jade/index.jade
+++ b/jade/index.jade
@@ -1,21 +1,22 @@
!!! 5
- var days = ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"]
- var rows = [1,2,3,4,5]
html(lang="en")
head
title Seinfeld Calendar
script(src: "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js")
script(src: "http://cachedcommons.org/cache/datejs/1.0.0/javascripts/date-min.js")
+ script(src: "js/seinfeld.js")
body
header
h1 Seinfeld Calendar
section
h2 This Month
table
tr.days
- each day in days
td= day
- each row in rows
tr.calendar
-each day in days
td.day placeholder
|
bohde/seinfeld
|
3a5fc4dd75fc0ca55aecc27842beb785bd878557
|
Added some libraries.
|
diff --git a/jade/index.jade b/jade/index.jade
index a406b60..26bca68 100644
--- a/jade/index.jade
+++ b/jade/index.jade
@@ -1,19 +1,21 @@
!!! 5
- var days = ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"]
- var rows = [1,2,3,4,5]
html(lang="en")
head
title Seinfeld Calendar
+ script(src: "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js")
+ script(src: "http://cachedcommons.org/cache/datejs/1.0.0/javascripts/date-min.js")
body
header
h1 Seinfeld Calendar
section
h2 This Month
table
tr.days
- each day in days
td= day
- each row in rows
tr.calendar
-each day in days
td.day placeholder
|
bohde/seinfeld
|
61f36dfdb841b71dace15201a222f885f6355b49
|
Added rough index page.
|
diff --git a/Cakefile b/Cakefile
new file mode 100644
index 0000000..7de52c6
--- /dev/null
+++ b/Cakefile
@@ -0,0 +1,13 @@
+fs = require 'fs'
+
+dir = "build"
+
+task 'build:html', 'compile the jade template files to html', () ->
+ jade = require 'jade'
+ jade.renderFile 'jade/index.jade', (err, html) ->
+ if err
+ console.log err
+ else
+ fs.mkdir "$dir", 0755,() ->
+ fs.writeFile "$dir/index.html", html
+
diff --git a/jade/index.jade b/jade/index.jade
new file mode 100644
index 0000000..a406b60
--- /dev/null
+++ b/jade/index.jade
@@ -0,0 +1,19 @@
+!!! 5
+- var days = ["Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"]
+- var rows = [1,2,3,4,5]
+html(lang="en")
+ head
+ title Seinfeld Calendar
+ body
+ header
+ h1 Seinfeld Calendar
+ section
+ h2 This Month
+ table
+ tr.days
+ - each day in days
+ td= day
+ - each row in rows
+ tr.calendar
+ -each day in days
+ td.day placeholder
|
bohde/seinfeld
|
105c8355a61c0454071750eed0cca2171ea59456
|
Added gitignore.
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..041000e
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+build
+*.js
\ No newline at end of file
|
igaiga/oauth_rails_sample
|
68039fdc07f5b7f6e62e4f927afe42caaa7bae2b
|
OAuthãµã³ãã«å®è£
ä¸(access token åå¾ã¾ã§)
|
diff --git a/for_rails3/oauth-plugin b/for_rails3/oauth-plugin
new file mode 160000
index 0000000..92183e2
--- /dev/null
+++ b/for_rails3/oauth-plugin
@@ -0,0 +1 @@
+Subproject commit 92183e2f4b961b737d43596d000555207781cc79
diff --git a/iga_oauth_provider/service_provider/iga_sample_at_access.rb b/iga_oauth_provider/sample_consumer.rb
similarity index 52%
rename from iga_oauth_provider/service_provider/iga_sample_at_access.rb
rename to iga_oauth_provider/sample_consumer.rb
index bdeefad..ccf70be 100644
--- a/iga_oauth_provider/service_provider/iga_sample_at_access.rb
+++ b/iga_oauth_provider/sample_consumer.rb
@@ -1,22 +1,20 @@
require 'rubygems'
require 'oauth'
require 'oauth/consumer'
-CONSUMER_KEY = 'd1QoG7kftoxprzFgoLZz'
-CONSUMER_SECRET = 'WB30de6Pg4yQq5qeyHrwS1J2gaLtJrgssXu7BG0B'
-ACCESS_TOKEN = 'fFH5yu5YMl0jqQrpPzFW'
-ACCESS_TOKEN_SECRET = '7Neup3OU4f2wm5HWqTo2IIxsrZgMdAPFJw9IhuUh'
+CONSUMER_KEY = 'znTAGqe0IED9P1NRdMeu'
+CONSUMER_SECRET = 'J8L8QxmHXltKtDwcP0Y7kevuorj2RG0ua0d5kKbt'
+ACCESS_TOKEN = '5g8ldDMT2XU9a5j5tuNZ'
+ACCESS_TOKEN_SECRET = 'mQMr5HHN1QEK4cAjxBrySXkfF34oUdm0ldB0M0Xt'
+#ACCESS_TOKEN = ''
+#ACCESS_TOKEN_SECRET = ''
consumer = OAuth::Consumer.new(
CONSUMER_KEY,
CONSUMER_SECRET,
:site => "http://localhost:3001",
:authorize_url => "http://localhost:3001/oauth/authorize"
)
-
access_token = OAuth::AccessToken.new(consumer, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
-response = access_token.get(
- '/oauth/at_access',
- {})
-
+response = access_token.get('/oauth/at_access')
puts response.inspect, response.body
diff --git a/iga_oauth_provider/service_provider/app/controllers/application_controller.rb b/iga_oauth_provider/service_provider/app/controllers/application_controller.rb
index 6efe540..ad6de64 100644
--- a/iga_oauth_provider/service_provider/app/controllers/application_controller.rb
+++ b/iga_oauth_provider/service_provider/app/controllers/application_controller.rb
@@ -1,15 +1,14 @@
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
- def current_user
- # User:new
- @current_user ||= User.authenticate('igaiga', 'hoge')
+ def current_user
+ @current_user ||= User.authenticate('foo', 'hoge')
end
# Scrub sensitive parameters from your log
# filter_parameter_logging :password
end
diff --git a/iga_oauth_provider/service_provider/app/controllers/oauth_clients_controller.rb b/iga_oauth_provider/service_provider/app/controllers/oauth_clients_controller.rb
index 65e51e3..f261eec 100644
--- a/iga_oauth_provider/service_provider/app/controllers/oauth_clients_controller.rb
+++ b/iga_oauth_provider/service_provider/app/controllers/oauth_clients_controller.rb
@@ -1,61 +1,56 @@
class OauthClientsController < ApplicationController
before_filter :login_required
before_filter :get_client_application, :only => [:show, :edit, :update, :destroy]
def index
@client_applications = current_user.client_applications
@tokens = current_user.tokens.find :all, :conditions => 'oauth_tokens.invalidated_at is null and oauth_tokens.authorized_at is not null'
end
def new
@client_application = ClientApplication.new
end
def create
@client_application = current_user.client_applications.build(params[:client_application])
if @client_application.save
flash[:notice] = "Registered the information successfully"
redirect_to :action => "show", :id => @client_application.id
else
render :action => "new"
end
end
def show
end
def edit
end
def update
if @client_application.update_attributes(params[:client_application])
flash[:notice] = "Updated the client information successfully"
redirect_to :action => "show", :id => @client_application.id
else
render :action => "edit"
end
end
def destroy
@client_application.destroy
flash[:notice] = "Destroyed the client application registration"
redirect_to :action => "index"
end
def login_required
true
end
-# def current_user
-# # User:new
-# @current_user ||= User.authenticate('igaiga', 'hoge')
-# end
-
private
def get_client_application
unless @client_application = current_user.client_applications.find(params[:id])
flash.now[:error] = "Wrong application id"
raise ActiveRecord::RecordNotFound
end
end
end
diff --git a/iga_oauth_provider/service_provider/app/controllers/oauth_controller.rb b/iga_oauth_provider/service_provider/app/controllers/oauth_controller.rb
index b9f9f20..350520b 100644
--- a/iga_oauth_provider/service_provider/app/controllers/oauth_controller.rb
+++ b/iga_oauth_provider/service_provider/app/controllers/oauth_controller.rb
@@ -1,26 +1,21 @@
require 'oauth/controllers/provider_controller'
class OauthController < AccountController
#class OauthController < ApplicationController
include OAuth::Controllers::ProviderController
-# before_filter :oauth_required, :only => [:at_access]
+ before_filter :oauth_required, :only => [:at_access]
# Override this to match your authorization page form
# It currently expects a checkbox called authorize
# def user_authorizes_token?
# params[:authorize] == '1'
# end
def login_required
- #user = User.find_by_identifier(params[:identifier]) || User.create(:identifier => params[:identifier])
- p current_user
- #p current_user = User.authenticate('igaiga', 'hoge')
false
end
def at_access
p 'at_access success!'
- # redirect_to :action => "index"
- 'hoge'
end
end
diff --git a/iga_oauth_provider/service_provider/app/views/oauth/at_access.html.erb b/iga_oauth_provider/service_provider/app/views/oauth/at_access.html.erb
new file mode 100644
index 0000000..82f174d
--- /dev/null
+++ b/iga_oauth_provider/service_provider/app/views/oauth/at_access.html.erb
@@ -0,0 +1 @@
+<h1>You have successed to accesss with access token!</h1>
diff --git a/iga_oauth_provider/service_provider/vendor/plugins/oauth-plugin/lib/oauth/controllers/application_controller_methods.rb b/iga_oauth_provider/service_provider/vendor/plugins/oauth-plugin/lib/oauth/controllers/application_controller_methods.rb
index 37fb860..2c3ade8 100644
--- a/iga_oauth_provider/service_provider/vendor/plugins/oauth-plugin/lib/oauth/controllers/application_controller_methods.rb
+++ b/iga_oauth_provider/service_provider/vendor/plugins/oauth-plugin/lib/oauth/controllers/application_controller_methods.rb
@@ -1,110 +1,112 @@
require 'oauth/signature'
module OAuth
module Controllers
module ApplicationControllerMethods
protected
def current_token
@current_token
end
def current_client_application
@current_client_application
end
def oauthenticate
verified=verify_oauth_signature
return verified && current_token.is_a?(::AccessToken)
end
def oauth?
current_token!=nil
end
# use in a before_filter
def oauth_required
+ p 'at oauth_required'
+
if oauthenticate
if authorized?
return true
else
invalid_oauth_response
end
else
invalid_oauth_response
end
end
# This requies that you have an acts_as_authenticated compatible authentication plugin installed
def login_or_oauth_required
if oauthenticate
if authorized?
return true
else
invalid_oauth_response
end
else
login_required
end
end
# verifies a request token request
def verify_oauth_consumer_signature
begin
valid = ClientApplication.verify_request(request) do |request_proxy|
@current_client_application = ClientApplication.find_by_key(request_proxy.consumer_key)
# Store this temporarily in client_application object for use in request token generation
@current_client_application.token_callback_url=request_proxy.oauth_callback if request_proxy.oauth_callback
# return the token secret and the consumer secret
[nil, @current_client_application.secret]
end
rescue
valid=false
end
invalid_oauth_response unless valid
end
def verify_oauth_request_token
verify_oauth_signature && current_token.is_a?(::RequestToken)
end
def invalid_oauth_response(code=401,message="Invalid OAuth Request")
render :text => message, :status => code
end
private
def current_token=(token)
@current_token=token
if @current_token
@current_user=@current_token.user
@current_client_application=@current_token.client_application
end
@current_token
end
# Implement this for your own application using app-specific models
def verify_oauth_signature
begin
valid = ClientApplication.verify_request(request) do |request_proxy|
self.current_token = ClientApplication.find_token(request_proxy.token)
if self.current_token.respond_to?(:provided_oauth_verifier=)
self.current_token.provided_oauth_verifier=request_proxy.oauth_verifier
end
# return the token secret and the consumer secret
[(current_token.nil? ? nil : current_token.secret), (current_client_application.nil? ? nil : current_client_application.secret)]
end
# reset @current_user to clear state for restful_...._authentication
@current_user = nil if (!valid)
valid
rescue
false
end
end
end
end
-end
\ No newline at end of file
+end
diff --git a/oauth_service_provider/app/views/oauth/at_access.html.erb b/oauth_service_provider/app/views/oauth/at_access.html.erb
new file mode 100644
index 0000000..effe24a
--- /dev/null
+++ b/oauth_service_provider/app/views/oauth/at_access.html.erb
@@ -0,0 +1 @@
+<h1>You have allowed this request</h1>
\ No newline at end of file
diff --git a/readme.txt b/readme.txt
index f69d37d..c56f7aa 100644
--- a/readme.txt
+++ b/readme.txt
@@ -1,57 +1,93 @@
consumer: script/server -p 3000
-privider: script/server -p 3001
+provider: script/server -p 3001
Service Provider input
Application URL : http://localhost:3000
Callback URL : http://localhost:3000/my_sample/callback
âprovider ã® client_applications ãã¼ãã«ã«consumer key/secret ãç»é²ããã
â OAuth Service Provider ã®ä½ãæ¹
sudo gem install oauth
rails service_provider
cd service_provider
script/plugin install git://github.com/pelle/oauth-plugin.git
script/generate oauth_provider
# acts_as_privider
script/plugin install git://github.com/gundestrup/acts_as_authenticated.git
script/generate authenticated user account
user.rb ãä¿®æ£
has_many :client_applications
has_many :tokens, :class_name=>"OauthToken",:order=>"authorized_at desc",:include=>[:client_application]
âhttp://localhost:3000/oauth_clients
undefined method `login_required' for #<OauthClientsController:0x1032070e8>
oauth_clients_controller.rb
追å
def login_required
true
end
undefined local variable or method `current_user' for #<OauthClientsController:0x1035373a8>
âacts_as_auththenticated ã® user ãå¿
è¦ã«ãªãã£ã½ããäºåã«ãã°ã¤ã³ããã¦ã¦ã¼ã¶ã¼ã¤ãããã(/account)
â/oauth/authoized
/oauth_client ã§ã³ã³ã·ã¥ã¼ããç»é²
-oauth_client_controller ã® current_userã¡ã½ããã夿´
+oauth_client_controller ã® current_userã¡ã½ããã夿´(accountã§ä½æããã¦ã¼ã¶ã¼åã¨ãã¹ã¯ã¼ããå
¥å(ææã))
def current_user
# User:new
- User.authenticate('igaiga', 'hoge')
- end
+ @current_user ||= User.authenticate('foo', 'bar')
+ã end
Service Provider input
Application URL : http://localhost:3000
Callback URL : http://localhost:3000/my_sample/callback
âæåããã°access_token ããããã
â AccessTokenãã¤ãã£ãã¢ã¯ã»ã¹
å¶å¾¡ãããã¡ã½ããã®åã«before_filterãæå®ãã
before_filter :oauth_required, :only => [:at_access]
-#http://localhost:3001/oauth/at_access?access_token=fFH5yu5YMl0jqQrpPzFW&access_secret=7Neup3OU4f2wm5HWqTo2IIxsrZgMdAPFJw9IhuUh
+â Consumer 㨠Provider ã§ã話ããæ¹æ³
+Provider ã -p 3001, Consumer ã -p 3000 ã§èµ·åããå ´å
+
+* consumer: script/server -p 3000
+* provider: script/server -p 3001
+
+!! Provider ã§ consumer key/secret ãçºè¡ãã
+* http://localhost:3001/account/ ã§ã¦ãã¨ãã«ãµã¤ã³ã¢ãããã
+* /oauth_clients ã§ã¯ã©ã¤ã¢ã³ããç»é²ãã
+** Application URL : http://localhost:3000
+** Callback URL : http://localhost:3000/my_sample/callback
+*** âprovider ã® client_applications ãã¼ãã«ã«consumer key/secret ãç»é²ããã
+*** consumer key/secret ãã³ãã¼ãã¦ãã
+
+!! Consumer ã§ access token ãå¾ã
+* http://localhost:3000/ ã§ã¦ãã¨ãã«ãµã¤ã³ã¢ãããã
+* new_consumer ã使ãã
+** service provider : my_sample
+** consumer key/secret ä¸è¨ã§ã³ãã¼ãããã®
+** scope ã¯ç©ºã§OK
+* access token ãå¾ã
+** my sample - establish
+** authorize access ã«ãã§ãã¯ãå
¥ã save changes
+* access token/secret ã表示ãããã®ã§ã³ãã¼ãã¦ãã
+
+!! Consumer ã§ access token ã使ã£ã¦ã¢ã¯ã»ã¹ãã
+sample_consumer.rb ã« consumer key/secret, access token/token secret ãè¨å®
+å®è¡
+ #<Net::HTTPOK 200 OK readbody=true>
+ <h1>You have successed to accesss with access token!</h1>
+ã¨åºãã°OK
+
+
+â Rails3ã§ä½¿ãæ¹æ³
+Gemfile ã«
+gem 'oauth'
+gem 'oauth-plugin', :git => 'git://github.com/pelle/oauth-plugin.git', :branch => 'rails3'
|
grumdrig/woses
|
c63650d3c823422d710fe43ebc82030f9dbe4a90
|
Fix rot, make js RPC async
|
diff --git a/woses.js b/woses.js
index 7a02a69..7000827 100644
--- a/woses.js
+++ b/woses.js
@@ -1,234 +1,239 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
"use strict";
var
- sys = require('sys'),
+ util = require('util'),
+ console = require('console'),
fs = require('fs'),
http = require('http'),
url = require('url'),
path = require('path');
function respondWithPhp(req, res) {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
var params = [parp, req.filepath];
for (var param in req.query)
params.push(escape(param) + "=" + escape(req.query[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers.host);
params.push("REQUEST_URI=" + req.url);
var child = require('child_process').spawn("php", params);
child.stdout.addListener('data', function (data) {
res.body += data;
});
child.stderr.addListener('data', function (data) {
- sys.puts("STDERR (php): " + content);
+ console.log("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
});
child.addListener('exit', function (code) {
res.header("content-type", (res.body.indexOf("<?xml") === 0) ?
"application/xml" : "text/html");
- sys.puts(req.requestLine + " (php) " + res.body.length);
+ console.log(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
});
}
function respondWithJsRpc(req, res) {
// TODO: use conf file to distinguish client & server js
try {
var script = require(path.join(process.cwd(), req.basepath));
} catch (e) {
res.status = 404;
- res.respond("404: In absentia or error in module.\n" + sys.inspect(e));
+ res.respond("404: In absentia or error in module.\n" + util.inspect(e));
return;
}
- script.fetch(req, res);
- var len = res.respond();
- sys.puts(req.requestLine + " " + len);
+ script.fetch(req, res, () => {
+ var len = res.respond();
+ console.log(req.requestLine + " " + len);
+ });
}
function respondWithStatic(req, res) {
var content_type = config.mimetypes[req.extname] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
fs.readFile(req.filepath, res.encoding, function(err, data) {
if (err) {
- sys.puts("Error 404: " + req.filepath);
+ console.log("Error 404: " + req.filepath);
res.status = 404;
res.header('content-type', 'text/plain');
res.respond('404: I looked but did not find.');
} else {
res.header('content-type', content_type);
- sys.puts(req.requestLine + " " + data.length);
+ console.log(req.requestLine + " " + data.length);
res.respond(data);
}
});
}
function mixin(target, source) {
for (var name in source) {
if (source.hasOwnProperty(name))
target[name] = source[name];
}
}
var config = {
port: 8053,
index: "index.html",
mimetypes: {
".css" : "text/css",
".gif" : "image/gif",
".html": "text/html",
".ico" : "image/vnd.microsoft.icon",
".jpg" : "image/jpeg",
".js" : "application/javascript",
".png" : "image/png",
".xml" : "application/xml",
".xul" : "application/vnd.mozilla.xul+xml",
},
handlers: [
[/\.php$/, respondWithPhp],
[/-rpc\.js$/, respondWithJsRpc],
[/$/, respondWithStatic]
]
}
-if (process.ARGV.length > 2)
- process.chdir(process.ARGV[2]);
+if (process.argv.length > 2)
+ process.chdir(process.argv[2]);
// Read config
try {
var cf = require(path.join(process.cwd(), ".woses-conf"));
} catch (e) {
// No config file is OK
var cf = {};
}
mixin(config.mimetypes, cf.mimetypes || {});
delete cf.mimetypes;
if (cf.handlers) {
config.handlers = cf.handlers.concat(config.handlers || []);
delete cf.handlers;
}
mixin(config, cf);
// Go
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.url + " HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
- sys.p(req.headers);
+ util.p(req.headers);
res.respond = function (body) {
- this.status = this.status || 200;
- this.body = body || this.body || "";
- if (typeof this.body != 'string') {
- this.header("content-type", "application/json");
- this.body = JSON.stringify(this.body);
+ if (!this.responded) {
+ this.responded = true;
+ this.status = this.status || 200;
+ this.body = body || this.body || "";
+ if (typeof this.body != 'string') {
+ this.header("content-type", "application/json");
+ this.body = JSON.stringify(this.body);
+ }
+ this.encoding = this.encoding || 'utf8';
+ this.length = (this.encoding === 'utf8' ?
+ encodeURIComponent(this.body).replace(/%../g, 'x').length :
+ this.body.length);
+ this.header('content-length', this.length);
+
+ this.writeHead(this.status, this.headers);
+ this.write(this.body, this.encoding);
+ this.end();
}
- this.encoding = this.encoding || 'utf8';
- this.length = (this.encoding === 'utf8' ?
- encodeURIComponent(this.body).replace(/%../g, 'x').length :
- this.body.length);
- this.header('content-length', this.length);
-
- this.writeHead(this.status, this.headers);
- this.write(this.body, this.encoding);
- this.end();
return this.body.length;
};
res.header = function(header, value) {
if (!this.headers) this.headers = {};
this.headers[header] = value;
};
mixin(req, url.parse(req.url, true));
req.query = req.query || {};
if (req.pathname.substr(0,1) != '/') {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
req.filepath = req.pathname.substr(1) || config.index; // path/name.ext
if (!path.basename(req.filepath) || // ""
path.basename(req.filepath).slice(-1) == "/") // dir/
req.filepath = path.join(req.filepath, config.index); // dir/index.html
req.filename = path.basename(req.filepath); // name.ext
req.extname = path.extname(req.filename); // .ext
req.basename = path.basename(req.filename, req.extname); // name
req.basepath = path.join(path.dirname(req.filepath),
req.basename); // path.name
// Exclude ".." in uri
if (req.pathname.indexOf('..') >= 0 || req.filename.substr(0,1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
req.body = '';
req.addListener('data', function(chunk) {
//req.pause();
req.body += chunk;
//setTimeout(function() { req.resume(); });
});
req.addListener('end', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var querystring = require("querystring");
var form = querystring.parse(req.body);
mixin(req.query, form);
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
mixin(req.query, req.json);
}
for (var i = 0; config.handlers[i]; ++i) {
var match = config.handlers[i][0].exec(req.pathname);
if (match) {
req.match = match;
config.handlers[i][1](req, res);
break;
}
}
});
}).listen(config.port);
-sys.puts('Woses running at http://127.0.0.1:' +
+console.log('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
af4ada1cb61cfa51216ed0152994c5f105a36227
|
Separate test folder; put documention in root. Also fix index for folders.
|
diff --git a/doc/index.html b/index.html
similarity index 83%
rename from doc/index.html
rename to index.html
index 4c3b30c..edd4e52 100644
--- a/doc/index.html
+++ b/index.html
@@ -1,125 +1,161 @@
<head>
<title>Woses Webserver</title>
- <link rel="stylesheet" href="style.css"/>
<link rel="icon" href="wose.png"/>
+ <style>
+pre, code { color: #060; font-size: 11pt; }
+pre { margin-left: 2ex; padding: 1ex; background-color: #eee; }
+p { font-size: 12pt; }
+body {
+ margin-left: 10%;
+ margin-right: 10%;
+ background-color: #fff;
+ color: black;
+ max-width: 800px;
+}
+h1,h2,h3,h4 { font-family: helvetica }
+h1 { font-size: 36pt; }
+h1 {
+ background-color: #58b;
+ color: white;
+ padding-left:6px;
+}
+h2 {
+ color: #28b;
+}
+li > code:first-child {
+ font-weight: bold;
+}
+
+.right {
+ float: right;
+ padding-right: 0.5ex;
+}
+
+form, input {
+ display: inline;
+}
+ </style>
</head>
<body>
<h1>
<!--☶ ☁ ⎈ 𐂷 ☃-->
Woses <span class=right style=color:black>⚉</span>
</h1>
<p>
Woses is a <a href=http://nodejs.org/>Node</a>-based webserver with
support for <a href=http://php.net/>PHP</a> templating.
<p>
Additionally it includes a mechanism for server-side JavaScript RPC.
<p>
The home page for Woses is
<a href=http://grumdrig.com/woses/>http://grumdrig.com/woses/</a>. The
code lives at
<a href=http://github.com/grumdrig/woses>http://github.com/grumdrig/woses</a>.
<h2>Usage</h2>
<pre>
$ node woses.js DOCUMENT_ROOT
</pre>
will run the HTTP server against the content in DOCUMENT_ROOT. For example,
<pre>
$ node woses.js doc
</pre>
<p>
will serve this documentation on <a href=http://localhost:8053/>port
8053</a>.
<p>
Included also is the script <code>serverloop.py</code> which runs the
server in a loop, polling for changes to the configuration
file, <code>woses.js</code>, or files listed on the command line.
Changes or <code>^C</code> restart the server. This is most useful for
running the server during development. Usage is:
<pre>
$ ./serverloop.py DOCUMENT_ROOT [OTHER_FILES...]
</pre>
<h2> Configuration </h2>
<p>
Woses can be configured by placing a file
called <code>.woses-conf.js</code> in the document root. This file may
export the following settings:
<ul>
<li> <code>port</code>: A port other than the default 8053 on which to
serve.
<li> <code>index</code>: Name of a directory index page to use for
URI's which point to a folder, rather than the
default, <code>index.html</code> falling back
to <code>index.php</code>.
<li> <code>mimetypes</code>: A map from file extensions to MIME types
for serving content.
</ul>
Here is an example configuration file:
<pre>
exports.port = 80;
exports.index = "home.html";
exports.mimetypes = {
'.gif': 'image/gif',
'.readme': 'text/plain'
}
</pre>
<h2> PHP </h2>
<p>
Woses will serve PHP scripts through the mechanism of the PHP
command-line interface; thus the <code>php</code> command must be available for
woses to serve PHP scripts.
<p>
The big caveat of PHP support is that, within PHP code, calls to
`header()' have no effect.
<h2> JS RPC </h2>
<p>
Requests for filenames ending in <code>-rpc.js</code> (some more
sensible mechanism to distinguish is a TODO item) are loaded as
modules and the HTTP request is proxied through their
exported <code>fetch</code> function, with signature:
<pre>
exports.fetch = function(request, response) {
// ...
response.body = ...;
};
</pre>
<h2> JS Templating </h2>
<p>
Templating in the style of EJS / Resig's micro-templating is planned,
but not implemented
<h2> Security </h2>
<p>
URLs with ".." in them are disallowed, but security is probably poor
at the moment. That is, an attacker may be able to pwn your system if
you are running this on a public server.
<h2> Tests </h2>
If this page is served by Woses itself,
-<a href=test.html>this is a test page.</a>
+<a href=test/>this is a test page.</a>
+
+<br>
+<br>
diff --git a/doc/.woses-conf.js b/test/.woses-conf.js
similarity index 100%
rename from doc/.woses-conf.js
rename to test/.woses-conf.js
diff --git a/doc/Markdown.pl b/test/Markdown.pl
similarity index 100%
rename from doc/Markdown.pl
rename to test/Markdown.pl
diff --git a/doc/test.html b/test/index.html
similarity index 100%
rename from doc/test.html
rename to test/index.html
diff --git a/doc/json-rpc.js b/test/json-rpc.js
similarity index 100%
rename from doc/json-rpc.js
rename to test/json-rpc.js
diff --git a/doc/sceltictree.jpg b/test/sceltictree.jpg
similarity index 100%
rename from doc/sceltictree.jpg
rename to test/sceltictree.jpg
diff --git a/doc/script.js b/test/script.js
similarity index 100%
rename from doc/script.js
rename to test/script.js
diff --git a/doc/test-rpc.js b/test/test-rpc.js
similarity index 100%
rename from doc/test-rpc.js
rename to test/test-rpc.js
diff --git a/doc/test.markdown b/test/test.markdown
similarity index 100%
rename from doc/test.markdown
rename to test/test.markdown
diff --git a/doc/test.php b/test/test.php
similarity index 100%
rename from doc/test.php
rename to test/test.php
diff --git a/doc/wose.png b/test/wose.png
similarity index 100%
rename from doc/wose.png
rename to test/wose.png
diff --git a/doc/xml-rpc.php b/test/xml-rpc.php
similarity index 100%
rename from doc/xml-rpc.php
rename to test/xml-rpc.php
diff --git a/woses.js b/woses.js
index 6ad7930..7a02a69 100644
--- a/woses.js
+++ b/woses.js
@@ -1,233 +1,234 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
"use strict";
var
sys = require('sys'),
fs = require('fs'),
http = require('http'),
url = require('url'),
path = require('path');
function respondWithPhp(req, res) {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
var params = [parp, req.filepath];
for (var param in req.query)
params.push(escape(param) + "=" + escape(req.query[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers.host);
params.push("REQUEST_URI=" + req.url);
var child = require('child_process').spawn("php", params);
child.stdout.addListener('data', function (data) {
res.body += data;
});
child.stderr.addListener('data', function (data) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
});
child.addListener('exit', function (code) {
res.header("content-type", (res.body.indexOf("<?xml") === 0) ?
"application/xml" : "text/html");
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
});
}
function respondWithJsRpc(req, res) {
// TODO: use conf file to distinguish client & server js
try {
var script = require(path.join(process.cwd(), req.basepath));
} catch (e) {
res.status = 404;
res.respond("404: In absentia or error in module.\n" + sys.inspect(e));
return;
}
script.fetch(req, res);
var len = res.respond();
sys.puts(req.requestLine + " " + len);
}
function respondWithStatic(req, res) {
var content_type = config.mimetypes[req.extname] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
fs.readFile(req.filepath, res.encoding, function(err, data) {
if (err) {
sys.puts("Error 404: " + req.filepath);
res.status = 404;
res.header('content-type', 'text/plain');
res.respond('404: I looked but did not find.');
} else {
res.header('content-type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
}
});
}
function mixin(target, source) {
for (var name in source) {
if (source.hasOwnProperty(name))
target[name] = source[name];
}
}
var config = {
port: 8053,
index: "index.html",
mimetypes: {
".css" : "text/css",
".gif" : "image/gif",
".html": "text/html",
".ico" : "image/vnd.microsoft.icon",
".jpg" : "image/jpeg",
".js" : "application/javascript",
".png" : "image/png",
".xml" : "application/xml",
".xul" : "application/vnd.mozilla.xul+xml",
},
handlers: [
[/\.php$/, respondWithPhp],
[/-rpc\.js$/, respondWithJsRpc],
[/$/, respondWithStatic]
]
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
// Read config
try {
var cf = require(path.join(process.cwd(), ".woses-conf"));
} catch (e) {
// No config file is OK
var cf = {};
}
mixin(config.mimetypes, cf.mimetypes || {});
delete cf.mimetypes;
if (cf.handlers) {
config.handlers = cf.handlers.concat(config.handlers || []);
delete cf.handlers;
}
mixin(config, cf);
// Go
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.url + " HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
res.respond = function (body) {
this.status = this.status || 200;
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
this.encoding = this.encoding || 'utf8';
this.length = (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length);
this.header('content-length', this.length);
this.writeHead(this.status, this.headers);
this.write(this.body, this.encoding);
this.end();
return this.body.length;
};
res.header = function(header, value) {
if (!this.headers) this.headers = {};
this.headers[header] = value;
};
mixin(req, url.parse(req.url, true));
req.query = req.query || {};
if (req.pathname.substr(0,1) != '/') {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
req.filepath = req.pathname.substr(1) || config.index; // path/name.ext
- if (!path.basename(req.filepath))
- req.filepath = path.join(req.filepath, config.index);
+ if (!path.basename(req.filepath) || // ""
+ path.basename(req.filepath).slice(-1) == "/") // dir/
+ req.filepath = path.join(req.filepath, config.index); // dir/index.html
req.filename = path.basename(req.filepath); // name.ext
req.extname = path.extname(req.filename); // .ext
req.basename = path.basename(req.filename, req.extname); // name
req.basepath = path.join(path.dirname(req.filepath),
req.basename); // path.name
// Exclude ".." in uri
if (req.pathname.indexOf('..') >= 0 || req.filename.substr(0,1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
req.body = '';
req.addListener('data', function(chunk) {
//req.pause();
req.body += chunk;
//setTimeout(function() { req.resume(); });
});
req.addListener('end', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var querystring = require("querystring");
var form = querystring.parse(req.body);
mixin(req.query, form);
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
mixin(req.query, req.json);
}
for (var i = 0; config.handlers[i]; ++i) {
var match = config.handlers[i][0].exec(req.pathname);
if (match) {
req.match = match;
config.handlers[i][1](req, res);
break;
}
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
7e5288b18b86a75910799251b588a396adaca508
|
Chance default port to 8053, which doesn't conflict with node_inspector and kinda spells WOSE
|
diff --git a/doc/.woses-conf.js b/doc/.woses-conf.js
index 4a4bf02..78b3765 100644
--- a/doc/.woses-conf.js
+++ b/doc/.woses-conf.js
@@ -1,24 +1,24 @@
exports.mimetypes = {
'.gif': "image/gif"
}
-exports.port = 8080;
+exports.port = 8053;
//exports.logRequestHeaders = true;
function respondWithMarkdown(req, res) {
- require('child_process').exec("Markdown.pl < " + req.filepath,
+ require('child_process').exec("./Markdown.pl < " + req.filepath,
function (error, stdout, stderr) {
if (error) {
res.status = 404;
res.respond("404: Mark my words. No such file.");
} else {
res.respond(stdout);
}
});
}
exports.handlers = [
[/\.(md|mkd|markdown)$/, respondWithMarkdown]
];
\ No newline at end of file
diff --git a/doc/index.html b/doc/index.html
index aba2cb5..4c3b30c 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,125 +1,125 @@
<head>
<title>Woses Webserver</title>
<link rel="stylesheet" href="style.css"/>
<link rel="icon" href="wose.png"/>
</head>
<body>
<h1>
<!--☶ ☁ ⎈ 𐂷 ☃-->
Woses <span class=right style=color:black>⚉</span>
</h1>
<p>
Woses is a <a href=http://nodejs.org/>Node</a>-based webserver with
support for <a href=http://php.net/>PHP</a> templating.
<p>
Additionally it includes a mechanism for server-side JavaScript RPC.
<p>
The home page for Woses is
<a href=http://grumdrig.com/woses/>http://grumdrig.com/woses/</a>. The
code lives at
<a href=http://github.com/grumdrig/woses>http://github.com/grumdrig/woses</a>.
<h2>Usage</h2>
<pre>
$ node woses.js DOCUMENT_ROOT
</pre>
will run the HTTP server against the content in DOCUMENT_ROOT. For example,
<pre>
$ node woses.js doc
</pre>
<p>
-will serve this documentation on <a href=http://localhost:8080/>port
-8080</a>.
+will serve this documentation on <a href=http://localhost:8053/>port
+8053</a>.
<p>
Included also is the script <code>serverloop.py</code> which runs the
server in a loop, polling for changes to the configuration
file, <code>woses.js</code>, or files listed on the command line.
Changes or <code>^C</code> restart the server. This is most useful for
running the server during development. Usage is:
<pre>
$ ./serverloop.py DOCUMENT_ROOT [OTHER_FILES...]
</pre>
<h2> Configuration </h2>
<p>
Woses can be configured by placing a file
called <code>.woses-conf.js</code> in the document root. This file may
export the following settings:
<ul>
-<li> <code>port</code>: A port other than the default 8080 on which to
+<li> <code>port</code>: A port other than the default 8053 on which to
serve.
<li> <code>index</code>: Name of a directory index page to use for
URI's which point to a folder, rather than the
default, <code>index.html</code> falling back
to <code>index.php</code>.
<li> <code>mimetypes</code>: A map from file extensions to MIME types
for serving content.
</ul>
Here is an example configuration file:
<pre>
exports.port = 80;
exports.index = "home.html";
exports.mimetypes = {
'.gif': 'image/gif',
'.readme': 'text/plain'
}
</pre>
<h2> PHP </h2>
<p>
Woses will serve PHP scripts through the mechanism of the PHP
command-line interface; thus the <code>php</code> command must be available for
woses to serve PHP scripts.
<p>
The big caveat of PHP support is that, within PHP code, calls to
`header()' have no effect.
<h2> JS RPC </h2>
<p>
Requests for filenames ending in <code>-rpc.js</code> (some more
sensible mechanism to distinguish is a TODO item) are loaded as
modules and the HTTP request is proxied through their
exported <code>fetch</code> function, with signature:
<pre>
exports.fetch = function(request, response) {
// ...
response.body = ...;
};
</pre>
<h2> JS Templating </h2>
<p>
Templating in the style of EJS / Resig's micro-templating is planned,
but not implemented
<h2> Security </h2>
<p>
URLs with ".." in them are disallowed, but security is probably poor
at the moment. That is, an attacker may be able to pwn your system if
you are running this on a public server.
<h2> Tests </h2>
If this page is served by Woses itself,
<a href=test.html>this is a test page.</a>
diff --git a/woses.coffee b/woses.coffee
index b13770a..1c8a1fe 100644
--- a/woses.coffee
+++ b/woses.coffee
@@ -1,185 +1,185 @@
#
# HTTP server for static and PHP files via Node.js (nodejs.org)
# See http://bitbucket.org/grumdrig/woses/wiki/Home
#
# Usage: node woses.js DOCUMENT_ROOT
#
# By Eric Fredricksen <[email protected]> in 2010 and perhaps onwards.
# No rights reserved; this code is placed into the public domain.
#
sys: require 'sys'
fs: require 'fs'
http: require 'http'
url: require 'url'
path: require 'path'
respondWithPhp: (req, res) ->
res.body: ''
parp: __filename.split('/').slice(0,-1).concat("parp.php").join("/")
params: [parp, req.filepath].concat(for param,value of req.query
escape(param) + "=" + escape(value))
params.push "-s"
params.push "HTTP_USER_AGENT=" + req.headers['user-agent']
params.push "HTTP_HOST=" + req.headers.host
params.push "REQUEST_URI=" + req.url
child: require('child_process').spawn("php", params)
child.stdout.addListener 'data', (data) ->
res.body += data
child.stderr.addListener 'data', (data) ->
sys.puts "STDERR (php): " + content
child.addListener 'exit', (code) ->
res.header('content-type', if res.body.indexOf("<?xml") == 0 then "application/xml" else "text/html")
sys.puts req.requestLine + " (php) " + res.body.length
res.status: 404 if res.body.match(/^404:/)
res.respond()
respondWithJsRpc: (req, res) ->
# TODO: use conf file to distinguish client & server js
try
script: require(req.basepath)
catch e
res.status: 404
res.respond "404: In absentia or error in module.\n" + sys.inspect(e)
return
script.fetch(req, res)
len: res.respond()
sys.puts(req.requestLine + " " + len)
respondWithStatic: (req, res) ->
content_type: config.mimetypes[req.extname] || "text/plain"
res.encoding: if content_type.slice(0,4) == 'text' then 'utf8' else 'binary'
fs.readFile req.filepath, res.encoding, (err, data) ->
if err
sys.puts("Error 404: " + req.filepath)
res.status: 404
res.header('content-type', 'text/plain')
res.respond('404: I looked but did not find.')
else
res.header('content-type', content_type)
sys.puts(req.requestLine + " " + data.length)
res.respond(data)
mixin: (target, source) ->
for name,value of source
target[name]: value
config: {
- port: 8080,
+ port: 8053,
index: "index.html",
mimetypes: {
".css" : "text/css",
".gif" : "image/gif",
".html": "text/html",
".ico" : "image/vnd.microsoft.icon",
".jpg" : "image/jpeg",
".js" : "application/javascript",
".png" : "image/png",
".xml" : "application/xml",
".xul" : "application/vnd.mozilla.xul+xml",
},
handlers: [
[/\.php$/, respondWithPhp],
[/-rpc\.js$/, respondWithJsRpc],
[/$/, respondWithStatic]
]
}
process.chdir(process.ARGV[2]) if process.ARGV.length > 2
# Read config
require.paths.push(process.cwd())
try
cf: require(".woses-conf")
catch e
# No config file is OK
cf: {}
mixin(config.mimetypes, cf.mimetypes || {})
delete cf.mimetypes
if cf.handlers
config.handlers: cf.handlers.concat(config.handlers || [])
delete cf.handlers
mixin(config, cf)
# Go
serverFn: (req, res) ->
req.requestLine: req.method + " " + req.url + " HTTP/" + req.httpVersion
sys.p(req.headers) if (config.logRequestHeaders)
res.respond: (body) ->
this.status: this.status || 200
this.body: body || this.body || ""
if (typeof this.body != 'string')
this.header("content-type", "application/json")
this.body: JSON.stringify(this.body)
this.encoding: this.encoding || 'utf8'
this.length: if this.encoding == 'utf8' then encodeURIComponent(this.body).replace(/%../g, 'x').length else this.body.length
this.header('content-length', this.length)
this.writeHead(this.status, this.headers)
this.write(this.body, this.encoding)
this.end()
return this.body.length
res.header: (header, value) ->
this.headers: or {}
this.headers[header]: value
mixin(req, url.parse(req.url, true))
req.query: or {}
if req.pathname.substr(0,1) != '/'
res.status: 400
return res.respond("400: I have no idea what that is")
req.filepath: req.pathname.substr(1) || config.index # path/name.ext
if not path.basename(req.filepath)
req.filepath: path.join(req.filepath, config.index)
req.filename: path.basename(req.filepath) # name.ext
req.extname : path.extname(req.filename) # .ext
req.basename: path.basename(req.filename, req.extname) # name
req.basepath: path.join(path.dirname(req.filepath),
req.basename) # path.name
# Exclude ".." in uri
if req.pathname.indexOf('..') >= 0 || req.filename.substr(0,1) == "."
res.status: 403
return res.respond("403: Don't hack me, bro")
req.body: ''
req.addListener('data', (chunk) -> req.body += chunk)
req.addListener 'end', () ->
ct: req.headers['content-type']
ct: and ct.split(';')[0]
if ct == "application/x-www-form-urlencoded"
form: require("querystring").parse(req.body)
mixin(req.query, form)
else if ct == "application/json"
req.json: JSON.parse(req.body)
mixin(req.query, req.json)
for handler in config.handlers
req.match: handler[0](req.pathname)
if req.match
handler[1](req, res)
break
http.createServer(serverFn).listen(config.port)
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd())
diff --git a/woses.js b/woses.js
index 63136c3..6ad7930 100644
--- a/woses.js
+++ b/woses.js
@@ -1,233 +1,233 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
"use strict";
var
sys = require('sys'),
fs = require('fs'),
http = require('http'),
url = require('url'),
path = require('path');
function respondWithPhp(req, res) {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
var params = [parp, req.filepath];
for (var param in req.query)
params.push(escape(param) + "=" + escape(req.query[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers.host);
params.push("REQUEST_URI=" + req.url);
var child = require('child_process').spawn("php", params);
child.stdout.addListener('data', function (data) {
res.body += data;
});
child.stderr.addListener('data', function (data) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
});
child.addListener('exit', function (code) {
res.header("content-type", (res.body.indexOf("<?xml") === 0) ?
"application/xml" : "text/html");
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
});
}
function respondWithJsRpc(req, res) {
// TODO: use conf file to distinguish client & server js
try {
var script = require(path.join(process.cwd(), req.basepath));
} catch (e) {
res.status = 404;
res.respond("404: In absentia or error in module.\n" + sys.inspect(e));
return;
}
script.fetch(req, res);
var len = res.respond();
sys.puts(req.requestLine + " " + len);
}
function respondWithStatic(req, res) {
var content_type = config.mimetypes[req.extname] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
fs.readFile(req.filepath, res.encoding, function(err, data) {
if (err) {
sys.puts("Error 404: " + req.filepath);
res.status = 404;
res.header('content-type', 'text/plain');
res.respond('404: I looked but did not find.');
} else {
res.header('content-type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
}
});
}
function mixin(target, source) {
for (var name in source) {
if (source.hasOwnProperty(name))
target[name] = source[name];
}
}
var config = {
- port: 8080,
+ port: 8053,
index: "index.html",
mimetypes: {
".css" : "text/css",
".gif" : "image/gif",
".html": "text/html",
".ico" : "image/vnd.microsoft.icon",
".jpg" : "image/jpeg",
".js" : "application/javascript",
".png" : "image/png",
".xml" : "application/xml",
".xul" : "application/vnd.mozilla.xul+xml",
},
handlers: [
[/\.php$/, respondWithPhp],
[/-rpc\.js$/, respondWithJsRpc],
[/$/, respondWithStatic]
]
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
// Read config
try {
var cf = require(path.join(process.cwd(), ".woses-conf"));
} catch (e) {
// No config file is OK
var cf = {};
}
mixin(config.mimetypes, cf.mimetypes || {});
delete cf.mimetypes;
if (cf.handlers) {
config.handlers = cf.handlers.concat(config.handlers || []);
delete cf.handlers;
}
mixin(config, cf);
// Go
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.url + " HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
res.respond = function (body) {
this.status = this.status || 200;
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
this.encoding = this.encoding || 'utf8';
this.length = (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length);
this.header('content-length', this.length);
this.writeHead(this.status, this.headers);
this.write(this.body, this.encoding);
this.end();
return this.body.length;
};
res.header = function(header, value) {
if (!this.headers) this.headers = {};
this.headers[header] = value;
};
mixin(req, url.parse(req.url, true));
req.query = req.query || {};
if (req.pathname.substr(0,1) != '/') {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
req.filepath = req.pathname.substr(1) || config.index; // path/name.ext
if (!path.basename(req.filepath))
req.filepath = path.join(req.filepath, config.index);
req.filename = path.basename(req.filepath); // name.ext
req.extname = path.extname(req.filename); // .ext
req.basename = path.basename(req.filename, req.extname); // name
req.basepath = path.join(path.dirname(req.filepath),
req.basename); // path.name
// Exclude ".." in uri
if (req.pathname.indexOf('..') >= 0 || req.filename.substr(0,1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
req.body = '';
req.addListener('data', function(chunk) {
//req.pause();
req.body += chunk;
//setTimeout(function() { req.resume(); });
});
req.addListener('end', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var querystring = require("querystring");
var form = querystring.parse(req.body);
mixin(req.query, form);
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
mixin(req.query, req.json);
}
for (var i = 0; config.handlers[i]; ++i) {
var match = config.handlers[i][0].exec(req.pathname);
if (match) {
req.match = match;
config.handlers[i][1](req, res);
break;
}
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
d5513ed5d95ab373b0414ed2ec201bfa411c9b2f
|
Put Markdown in repo so the test of it will work
|
diff --git a/doc/Markdown.pl b/doc/Markdown.pl
new file mode 100755
index 0000000..e4c8469
--- /dev/null
+++ b/doc/Markdown.pl
@@ -0,0 +1,1450 @@
+#!/usr/bin/perl
+
+#
+# Markdown -- A text-to-HTML conversion tool for web writers
+#
+# Copyright (c) 2004 John Gruber
+# <http://daringfireball.net/projects/markdown/>
+#
+
+
+package Markdown;
+require 5.006_000;
+use strict;
+use warnings;
+
+use Digest::MD5 qw(md5_hex);
+use vars qw($VERSION);
+$VERSION = '1.0.1';
+# Tue 14 Dec 2004
+
+## Disabled; causes problems under Perl 5.6.1:
+# use utf8;
+# binmode( STDOUT, ":utf8" ); # c.f.: http://acis.openlib.org/dev/perl-unicode-struggle.html
+
+
+#
+# Global default settings:
+#
+my $g_empty_element_suffix = " />"; # Change to ">" for HTML output
+my $g_tab_width = 4;
+
+
+#
+# Globals:
+#
+
+# Regex to match balanced [brackets]. See Friedl's
+# "Mastering Regular Expressions", 2nd Ed., pp. 328-331.
+my $g_nested_brackets;
+$g_nested_brackets = qr{
+ (?> # Atomic matching
+ [^\[\]]+ # Anything other than brackets
+ |
+ \[
+ (??{ $g_nested_brackets }) # Recursive set of nested brackets
+ \]
+ )*
+}x;
+
+
+# Table of hash values for escaped characters:
+my %g_escape_table;
+foreach my $char (split //, '\\`*_{}[]()>#+-.!') {
+ $g_escape_table{$char} = md5_hex($char);
+}
+
+
+# Global hashes, used by various utility routines
+my %g_urls;
+my %g_titles;
+my %g_html_blocks;
+
+# Used to track when we're inside an ordered or unordered list
+# (see _ProcessListItems() for details):
+my $g_list_level = 0;
+
+
+#### Blosxom plug-in interface ##########################################
+
+# Set $g_blosxom_use_meta to 1 to use Blosxom's meta plug-in to determine
+# which posts Markdown should process, using a "meta-markup: markdown"
+# header. If it's set to 0 (the default), Markdown will process all
+# entries.
+my $g_blosxom_use_meta = 0;
+
+sub start { 1; }
+sub story {
+ my($pkg, $path, $filename, $story_ref, $title_ref, $body_ref) = @_;
+
+ if ( (! $g_blosxom_use_meta) or
+ (defined($meta::markup) and ($meta::markup =~ /^\s*markdown\s*$/i))
+ ){
+ $$body_ref = Markdown($$body_ref);
+ }
+ 1;
+}
+
+
+#### Movable Type plug-in interface #####################################
+eval {require MT}; # Test to see if we're running in MT.
+unless ($@) {
+ require MT;
+ import MT;
+ require MT::Template::Context;
+ import MT::Template::Context;
+
+ eval {require MT::Plugin}; # Test to see if we're running >= MT 3.0.
+ unless ($@) {
+ require MT::Plugin;
+ import MT::Plugin;
+ my $plugin = new MT::Plugin({
+ name => "Markdown",
+ description => "A plain-text-to-HTML formatting plugin. (Version: $VERSION)",
+ doc_link => 'http://daringfireball.net/projects/markdown/'
+ });
+ MT->add_plugin( $plugin );
+ }
+
+ MT::Template::Context->add_container_tag(MarkdownOptions => sub {
+ my $ctx = shift;
+ my $args = shift;
+ my $builder = $ctx->stash('builder');
+ my $tokens = $ctx->stash('tokens');
+
+ if (defined ($args->{'output'}) ) {
+ $ctx->stash('markdown_output', lc $args->{'output'});
+ }
+
+ defined (my $str = $builder->build($ctx, $tokens) )
+ or return $ctx->error($builder->errstr);
+ $str; # return value
+ });
+
+ MT->add_text_filter('markdown' => {
+ label => 'Markdown',
+ docs => 'http://daringfireball.net/projects/markdown/',
+ on_format => sub {
+ my $text = shift;
+ my $ctx = shift;
+ my $raw = 0;
+ if (defined $ctx) {
+ my $output = $ctx->stash('markdown_output');
+ if (defined $output && $output =~ m/^html/i) {
+ $g_empty_element_suffix = ">";
+ $ctx->stash('markdown_output', '');
+ }
+ elsif (defined $output && $output eq 'raw') {
+ $raw = 1;
+ $ctx->stash('markdown_output', '');
+ }
+ else {
+ $raw = 0;
+ $g_empty_element_suffix = " />";
+ }
+ }
+ $text = $raw ? $text : Markdown($text);
+ $text;
+ },
+ });
+
+ # If SmartyPants is loaded, add a combo Markdown/SmartyPants text filter:
+ my $smartypants;
+
+ {
+ no warnings "once";
+ $smartypants = $MT::Template::Context::Global_filters{'smarty_pants'};
+ }
+
+ if ($smartypants) {
+ MT->add_text_filter('markdown_with_smartypants' => {
+ label => 'Markdown With SmartyPants',
+ docs => 'http://daringfireball.net/projects/markdown/',
+ on_format => sub {
+ my $text = shift;
+ my $ctx = shift;
+ if (defined $ctx) {
+ my $output = $ctx->stash('markdown_output');
+ if (defined $output && $output eq 'html') {
+ $g_empty_element_suffix = ">";
+ }
+ else {
+ $g_empty_element_suffix = " />";
+ }
+ }
+ $text = Markdown($text);
+ $text = $smartypants->($text, '1');
+ },
+ });
+ }
+}
+else {
+#### BBEdit/command-line text filter interface ##########################
+# Needs to be hidden from MT (and Blosxom when running in static mode).
+
+ # We're only using $blosxom::version once; tell Perl not to warn us:
+ no warnings 'once';
+ unless ( defined($blosxom::version) ) {
+ use warnings;
+
+ #### Check for command-line switches: #################
+ my %cli_opts;
+ use Getopt::Long;
+ Getopt::Long::Configure('pass_through');
+ GetOptions(\%cli_opts,
+ 'version',
+ 'shortversion',
+ 'html4tags',
+ );
+ if ($cli_opts{'version'}) { # Version info
+ print "\nThis is Markdown, version $VERSION.\n";
+ print "Copyright 2004 John Gruber\n";
+ print "http://daringfireball.net/projects/markdown/\n\n";
+ exit 0;
+ }
+ if ($cli_opts{'shortversion'}) { # Just the version number string.
+ print $VERSION;
+ exit 0;
+ }
+ if ($cli_opts{'html4tags'}) { # Use HTML tag style instead of XHTML
+ $g_empty_element_suffix = ">";
+ }
+
+
+ #### Process incoming text: ###########################
+ my $text;
+ {
+ local $/; # Slurp the whole file
+ $text = <>;
+ }
+ print Markdown($text);
+ }
+}
+
+
+
+sub Markdown {
+#
+# Main function. The order in which other subs are called here is
+# essential. Link and image substitutions need to happen before
+# _EscapeSpecialChars(), so that any *'s or _'s in the <a>
+# and <img> tags get encoded.
+#
+ my $text = shift;
+
+ # Clear the global hashes. If we don't clear these, you get conflicts
+ # from other articles when generating a page which contains more than
+ # one article (e.g. an index page that shows the N most recent
+ # articles):
+ %g_urls = ();
+ %g_titles = ();
+ %g_html_blocks = ();
+
+
+ # Standardize line endings:
+ $text =~ s{\r\n}{\n}g; # DOS to Unix
+ $text =~ s{\r}{\n}g; # Mac to Unix
+
+ # Make sure $text ends with a couple of newlines:
+ $text .= "\n\n";
+
+ # Convert all tabs to spaces.
+ $text = _Detab($text);
+
+ # Strip any lines consisting only of spaces and tabs.
+ # This makes subsequent regexen easier to write, because we can
+ # match consecutive blank lines with /\n+/ instead of something
+ # contorted like /[ \t]*\n+/ .
+ $text =~ s/^[ \t]+$//mg;
+
+ # Turn block-level HTML blocks into hash entries
+ $text = _HashHTMLBlocks($text);
+
+ # Strip link definitions, store in hashes.
+ $text = _StripLinkDefinitions($text);
+
+ $text = _RunBlockGamut($text);
+
+ $text = _UnescapeSpecialChars($text);
+
+ return $text . "\n";
+}
+
+
+sub _StripLinkDefinitions {
+#
+# Strips link definitions from text, stores the URLs and titles in
+# hash references.
+#
+ my $text = shift;
+ my $less_than_tab = $g_tab_width - 1;
+
+ # Link defs are in the form: ^[id]: url "optional title"
+ while ($text =~ s{
+ ^[ ]{0,$less_than_tab}\[(.+)\]: # id = $1
+ [ \t]*
+ \n? # maybe *one* newline
+ [ \t]*
+ <?(\S+?)>? # url = $2
+ [ \t]*
+ \n? # maybe one newline
+ [ \t]*
+ (?:
+ (?<=\s) # lookbehind for whitespace
+ ["(]
+ (.+?) # title = $3
+ [")]
+ [ \t]*
+ )? # title is optional
+ (?:\n+|\Z)
+ }
+ {}mx) {
+ $g_urls{lc $1} = _EncodeAmpsAndAngles( $2 ); # Link IDs are case-insensitive
+ if ($3) {
+ $g_titles{lc $1} = $3;
+ $g_titles{lc $1} =~ s/"/"/g;
+ }
+ }
+
+ return $text;
+}
+
+
+sub _HashHTMLBlocks {
+ my $text = shift;
+ my $less_than_tab = $g_tab_width - 1;
+
+ # Hashify HTML blocks:
+ # We only want to do this for block-level HTML tags, such as headers,
+ # lists, and tables. That's because we still want to wrap <p>s around
+ # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
+ # phrase emphasis, and spans. The list of tags we're looking for is
+ # hard-coded:
+ my $block_tags_a = qr/p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del/;
+ my $block_tags_b = qr/p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math/;
+
+ # First, look for nested blocks, e.g.:
+ # <div>
+ # <div>
+ # tags for inner block must be indented.
+ # </div>
+ # </div>
+ #
+ # The outermost tags must start at the left margin for this to match, and
+ # the inner nested divs must be indented.
+ # We need to do this before the next, more liberal match, because the next
+ # match will start at the first `<div>` and stop at the first `</div>`.
+ $text =~ s{
+ ( # save in $1
+ ^ # start of line (with /m)
+ <($block_tags_a) # start tag = $2
+ \b # word break
+ (.*\n)*? # any number of lines, minimally matching
+ </\2> # the matching end tag
+ [ \t]* # trailing spaces/tabs
+ (?=\n+|\Z) # followed by a newline or end of document
+ )
+ }{
+ my $key = md5_hex($1);
+ $g_html_blocks{$key} = $1;
+ "\n\n" . $key . "\n\n";
+ }egmx;
+
+
+ #
+ # Now match more liberally, simply from `\n<tag>` to `</tag>\n`
+ #
+ $text =~ s{
+ ( # save in $1
+ ^ # start of line (with /m)
+ <($block_tags_b) # start tag = $2
+ \b # word break
+ (.*\n)*? # any number of lines, minimally matching
+ .*</\2> # the matching end tag
+ [ \t]* # trailing spaces/tabs
+ (?=\n+|\Z) # followed by a newline or end of document
+ )
+ }{
+ my $key = md5_hex($1);
+ $g_html_blocks{$key} = $1;
+ "\n\n" . $key . "\n\n";
+ }egmx;
+ # Special case just for <hr />. It was easier to make a special case than
+ # to make the other regex more complicated.
+ $text =~ s{
+ (?:
+ (?<=\n\n) # Starting after a blank line
+ | # or
+ \A\n? # the beginning of the doc
+ )
+ ( # save in $1
+ [ ]{0,$less_than_tab}
+ <(hr) # start tag = $2
+ \b # word break
+ ([^<>])*? #
+ /?> # the matching end tag
+ [ \t]*
+ (?=\n{2,}|\Z) # followed by a blank line or end of document
+ )
+ }{
+ my $key = md5_hex($1);
+ $g_html_blocks{$key} = $1;
+ "\n\n" . $key . "\n\n";
+ }egx;
+
+ # Special case for standalone HTML comments:
+ $text =~ s{
+ (?:
+ (?<=\n\n) # Starting after a blank line
+ | # or
+ \A\n? # the beginning of the doc
+ )
+ ( # save in $1
+ [ ]{0,$less_than_tab}
+ (?s:
+ <!
+ (--.*?--\s*)+
+ >
+ )
+ [ \t]*
+ (?=\n{2,}|\Z) # followed by a blank line or end of document
+ )
+ }{
+ my $key = md5_hex($1);
+ $g_html_blocks{$key} = $1;
+ "\n\n" . $key . "\n\n";
+ }egx;
+
+
+ return $text;
+}
+
+
+sub _RunBlockGamut {
+#
+# These are all the transformations that form block-level
+# tags like paragraphs, headers, and list items.
+#
+ my $text = shift;
+
+ $text = _DoHeaders($text);
+
+ # Do Horizontal Rules:
+ $text =~ s{^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$}{\n<hr$g_empty_element_suffix\n}gmx;
+ $text =~ s{^[ ]{0,2}([ ]? -[ ]?){3,}[ \t]*$}{\n<hr$g_empty_element_suffix\n}gmx;
+ $text =~ s{^[ ]{0,2}([ ]? _[ ]?){3,}[ \t]*$}{\n<hr$g_empty_element_suffix\n}gmx;
+
+ $text = _DoLists($text);
+
+ $text = _DoCodeBlocks($text);
+
+ $text = _DoBlockQuotes($text);
+
+ # We already ran _HashHTMLBlocks() before, in Markdown(), but that
+ # was to escape raw HTML in the original Markdown source. This time,
+ # we're escaping the markup we've just created, so that we don't wrap
+ # <p> tags around block-level tags.
+ $text = _HashHTMLBlocks($text);
+
+ $text = _FormParagraphs($text);
+
+ return $text;
+}
+
+
+sub _RunSpanGamut {
+#
+# These are all the transformations that occur *within* block-level
+# tags like paragraphs, headers, and list items.
+#
+ my $text = shift;
+
+ $text = _DoCodeSpans($text);
+
+ $text = _EscapeSpecialChars($text);
+
+ # Process anchor and image tags. Images must come first,
+ # because ![foo][f] looks like an anchor.
+ $text = _DoImages($text);
+ $text = _DoAnchors($text);
+
+ # Make links out of things like `<http://example.com/>`
+ # Must come after _DoAnchors(), because you can use < and >
+ # delimiters in inline links like [this](<url>).
+ $text = _DoAutoLinks($text);
+
+ $text = _EncodeAmpsAndAngles($text);
+
+ $text = _DoItalicsAndBold($text);
+
+ # Do hard breaks:
+ $text =~ s/ {2,}\n/ <br$g_empty_element_suffix\n/g;
+
+ return $text;
+}
+
+
+sub _EscapeSpecialChars {
+ my $text = shift;
+ my $tokens ||= _TokenizeHTML($text);
+
+ $text = ''; # rebuild $text from the tokens
+# my $in_pre = 0; # Keep track of when we're inside <pre> or <code> tags.
+# my $tags_to_skip = qr!<(/?)(?:pre|code|kbd|script|math)[\s>]!;
+
+ foreach my $cur_token (@$tokens) {
+ if ($cur_token->[0] eq "tag") {
+ # Within tags, encode * and _ so they don't conflict
+ # with their use in Markdown for italics and strong.
+ # We're replacing each such character with its
+ # corresponding MD5 checksum value; this is likely
+ # overkill, but it should prevent us from colliding
+ # with the escape values by accident.
+ $cur_token->[1] =~ s! \* !$g_escape_table{'*'}!gx;
+ $cur_token->[1] =~ s! _ !$g_escape_table{'_'}!gx;
+ $text .= $cur_token->[1];
+ } else {
+ my $t = $cur_token->[1];
+ $t = _EncodeBackslashEscapes($t);
+ $text .= $t;
+ }
+ }
+ return $text;
+}
+
+
+sub _DoAnchors {
+#
+# Turn Markdown link shortcuts into XHTML <a> tags.
+#
+ my $text = shift;
+
+ #
+ # First, handle reference-style links: [link text] [id]
+ #
+ $text =~ s{
+ ( # wrap whole match in $1
+ \[
+ ($g_nested_brackets) # link text = $2
+ \]
+
+ [ ]? # one optional space
+ (?:\n[ ]*)? # one optional newline followed by spaces
+
+ \[
+ (.*?) # id = $3
+ \]
+ )
+ }{
+ my $result;
+ my $whole_match = $1;
+ my $link_text = $2;
+ my $link_id = lc $3;
+
+ if ($link_id eq "") {
+ $link_id = lc $link_text; # for shortcut links like [this][].
+ }
+
+ if (defined $g_urls{$link_id}) {
+ my $url = $g_urls{$link_id};
+ $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid
+ $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics/bold.
+ $result = "<a href=\"$url\"";
+ if ( defined $g_titles{$link_id} ) {
+ my $title = $g_titles{$link_id};
+ $title =~ s! \* !$g_escape_table{'*'}!gx;
+ $title =~ s! _ !$g_escape_table{'_'}!gx;
+ $result .= " title=\"$title\"";
+ }
+ $result .= ">$link_text</a>";
+ }
+ else {
+ $result = $whole_match;
+ }
+ $result;
+ }xsge;
+
+ #
+ # Next, inline-style links: [link text](url "optional title")
+ #
+ $text =~ s{
+ ( # wrap whole match in $1
+ \[
+ ($g_nested_brackets) # link text = $2
+ \]
+ \( # literal paren
+ [ \t]*
+ <?(.*?)>? # href = $3
+ [ \t]*
+ ( # $4
+ (['"]) # quote char = $5
+ (.*?) # Title = $6
+ \5 # matching quote
+ )? # title is optional
+ \)
+ )
+ }{
+ my $result;
+ my $whole_match = $1;
+ my $link_text = $2;
+ my $url = $3;
+ my $title = $6;
+
+ $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid
+ $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics/bold.
+ $result = "<a href=\"$url\"";
+
+ if (defined $title) {
+ $title =~ s/"/"/g;
+ $title =~ s! \* !$g_escape_table{'*'}!gx;
+ $title =~ s! _ !$g_escape_table{'_'}!gx;
+ $result .= " title=\"$title\"";
+ }
+
+ $result .= ">$link_text</a>";
+
+ $result;
+ }xsge;
+
+ return $text;
+}
+
+
+sub _DoImages {
+#
+# Turn Markdown image shortcuts into <img> tags.
+#
+ my $text = shift;
+
+ #
+ # First, handle reference-style labeled images: ![alt text][id]
+ #
+ $text =~ s{
+ ( # wrap whole match in $1
+ !\[
+ (.*?) # alt text = $2
+ \]
+
+ [ ]? # one optional space
+ (?:\n[ ]*)? # one optional newline followed by spaces
+
+ \[
+ (.*?) # id = $3
+ \]
+
+ )
+ }{
+ my $result;
+ my $whole_match = $1;
+ my $alt_text = $2;
+ my $link_id = lc $3;
+
+ if ($link_id eq "") {
+ $link_id = lc $alt_text; # for shortcut links like ![this][].
+ }
+
+ $alt_text =~ s/"/"/g;
+ if (defined $g_urls{$link_id}) {
+ my $url = $g_urls{$link_id};
+ $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid
+ $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics/bold.
+ $result = "<img src=\"$url\" alt=\"$alt_text\"";
+ if (defined $g_titles{$link_id}) {
+ my $title = $g_titles{$link_id};
+ $title =~ s! \* !$g_escape_table{'*'}!gx;
+ $title =~ s! _ !$g_escape_table{'_'}!gx;
+ $result .= " title=\"$title\"";
+ }
+ $result .= $g_empty_element_suffix;
+ }
+ else {
+ # If there's no such link ID, leave intact:
+ $result = $whole_match;
+ }
+
+ $result;
+ }xsge;
+
+ #
+ # Next, handle inline images: 
+ # Don't forget: encode * and _
+
+ $text =~ s{
+ ( # wrap whole match in $1
+ !\[
+ (.*?) # alt text = $2
+ \]
+ \( # literal paren
+ [ \t]*
+ <?(\S+?)>? # src url = $3
+ [ \t]*
+ ( # $4
+ (['"]) # quote char = $5
+ (.*?) # title = $6
+ \5 # matching quote
+ [ \t]*
+ )? # title is optional
+ \)
+ )
+ }{
+ my $result;
+ my $whole_match = $1;
+ my $alt_text = $2;
+ my $url = $3;
+ my $title = '';
+ if (defined($6)) {
+ $title = $6;
+ }
+
+ $alt_text =~ s/"/"/g;
+ $title =~ s/"/"/g;
+ $url =~ s! \* !$g_escape_table{'*'}!gx; # We've got to encode these to avoid
+ $url =~ s! _ !$g_escape_table{'_'}!gx; # conflicting with italics/bold.
+ $result = "<img src=\"$url\" alt=\"$alt_text\"";
+ if (defined $title) {
+ $title =~ s! \* !$g_escape_table{'*'}!gx;
+ $title =~ s! _ !$g_escape_table{'_'}!gx;
+ $result .= " title=\"$title\"";
+ }
+ $result .= $g_empty_element_suffix;
+
+ $result;
+ }xsge;
+
+ return $text;
+}
+
+
+sub _DoHeaders {
+ my $text = shift;
+
+ # Setext-style headers:
+ # Header 1
+ # ========
+ #
+ # Header 2
+ # --------
+ #
+ $text =~ s{ ^(.+)[ \t]*\n=+[ \t]*\n+ }{
+ "<h1>" . _RunSpanGamut($1) . "</h1>\n\n";
+ }egmx;
+
+ $text =~ s{ ^(.+)[ \t]*\n-+[ \t]*\n+ }{
+ "<h2>" . _RunSpanGamut($1) . "</h2>\n\n";
+ }egmx;
+
+
+ # atx-style headers:
+ # # Header 1
+ # ## Header 2
+ # ## Header 2 with closing hashes ##
+ # ...
+ # ###### Header 6
+ #
+ $text =~ s{
+ ^(\#{1,6}) # $1 = string of #'s
+ [ \t]*
+ (.+?) # $2 = Header text
+ [ \t]*
+ \#* # optional closing #'s (not counted)
+ \n+
+ }{
+ my $h_level = length($1);
+ "<h$h_level>" . _RunSpanGamut($2) . "</h$h_level>\n\n";
+ }egmx;
+
+ return $text;
+}
+
+
+sub _DoLists {
+#
+# Form HTML ordered (numbered) and unordered (bulleted) lists.
+#
+ my $text = shift;
+ my $less_than_tab = $g_tab_width - 1;
+
+ # Re-usable patterns to match list item bullets and number markers:
+ my $marker_ul = qr/[*+-]/;
+ my $marker_ol = qr/\d+[.]/;
+ my $marker_any = qr/(?:$marker_ul|$marker_ol)/;
+
+ # Re-usable pattern to match any entirel ul or ol list:
+ my $whole_list = qr{
+ ( # $1 = whole list
+ ( # $2
+ [ ]{0,$less_than_tab}
+ (${marker_any}) # $3 = first list item marker
+ [ \t]+
+ )
+ (?s:.+?)
+ ( # $4
+ \z
+ |
+ \n{2,}
+ (?=\S)
+ (?! # Negative lookahead for another list item marker
+ [ \t]*
+ ${marker_any}[ \t]+
+ )
+ )
+ )
+ }mx;
+
+ # We use a different prefix before nested lists than top-level lists.
+ # See extended comment in _ProcessListItems().
+ #
+ # Note: There's a bit of duplication here. My original implementation
+ # created a scalar regex pattern as the conditional result of the test on
+ # $g_list_level, and then only ran the $text =~ s{...}{...}egmx
+ # substitution once, using the scalar as the pattern. This worked,
+ # everywhere except when running under MT on my hosting account at Pair
+ # Networks. There, this caused all rebuilds to be killed by the reaper (or
+ # perhaps they crashed, but that seems incredibly unlikely given that the
+ # same script on the same server ran fine *except* under MT. I've spent
+ # more time trying to figure out why this is happening than I'd like to
+ # admit. My only guess, backed up by the fact that this workaround works,
+ # is that Perl optimizes the substition when it can figure out that the
+ # pattern will never change, and when this optimization isn't on, we run
+ # afoul of the reaper. Thus, the slightly redundant code to that uses two
+ # static s/// patterns rather than one conditional pattern.
+
+ if ($g_list_level) {
+ $text =~ s{
+ ^
+ $whole_list
+ }{
+ my $list = $1;
+ my $list_type = ($3 =~ m/$marker_ul/) ? "ul" : "ol";
+ # Turn double returns into triple returns, so that we can make a
+ # paragraph for the last item in a list, if necessary:
+ $list =~ s/\n{2,}/\n\n\n/g;
+ my $result = _ProcessListItems($list, $marker_any);
+ $result = "<$list_type>\n" . $result . "</$list_type>\n";
+ $result;
+ }egmx;
+ }
+ else {
+ $text =~ s{
+ (?:(?<=\n\n)|\A\n?)
+ $whole_list
+ }{
+ my $list = $1;
+ my $list_type = ($3 =~ m/$marker_ul/) ? "ul" : "ol";
+ # Turn double returns into triple returns, so that we can make a
+ # paragraph for the last item in a list, if necessary:
+ $list =~ s/\n{2,}/\n\n\n/g;
+ my $result = _ProcessListItems($list, $marker_any);
+ $result = "<$list_type>\n" . $result . "</$list_type>\n";
+ $result;
+ }egmx;
+ }
+
+
+ return $text;
+}
+
+
+sub _ProcessListItems {
+#
+# Process the contents of a single ordered or unordered list, splitting it
+# into individual list items.
+#
+
+ my $list_str = shift;
+ my $marker_any = shift;
+
+
+ # The $g_list_level global keeps track of when we're inside a list.
+ # Each time we enter a list, we increment it; when we leave a list,
+ # we decrement. If it's zero, we're not in a list anymore.
+ #
+ # We do this because when we're not inside a list, we want to treat
+ # something like this:
+ #
+ # I recommend upgrading to version
+ # 8. Oops, now this line is treated
+ # as a sub-list.
+ #
+ # As a single paragraph, despite the fact that the second line starts
+ # with a digit-period-space sequence.
+ #
+ # Whereas when we're inside a list (or sub-list), that line will be
+ # treated as the start of a sub-list. What a kludge, huh? This is
+ # an aspect of Markdown's syntax that's hard to parse perfectly
+ # without resorting to mind-reading. Perhaps the solution is to
+ # change the syntax rules such that sub-lists must start with a
+ # starting cardinal number; e.g. "1." or "a.".
+
+ $g_list_level++;
+
+ # trim trailing blank lines:
+ $list_str =~ s/\n{2,}\z/\n/;
+
+
+ $list_str =~ s{
+ (\n)? # leading line = $1
+ (^[ \t]*) # leading whitespace = $2
+ ($marker_any) [ \t]+ # list marker = $3
+ ((?s:.+?) # list item text = $4
+ (\n{1,2}))
+ (?= \n* (\z | \2 ($marker_any) [ \t]+))
+ }{
+ my $item = $4;
+ my $leading_line = $1;
+ my $leading_space = $2;
+
+ if ($leading_line or ($item =~ m/\n{2,}/)) {
+ $item = _RunBlockGamut(_Outdent($item));
+ }
+ else {
+ # Recursion for sub-lists:
+ $item = _DoLists(_Outdent($item));
+ chomp $item;
+ $item = _RunSpanGamut($item);
+ }
+
+ "<li>" . $item . "</li>\n";
+ }egmx;
+
+ $g_list_level--;
+ return $list_str;
+}
+
+
+
+sub _DoCodeBlocks {
+#
+# Process Markdown `<pre><code>` blocks.
+#
+
+ my $text = shift;
+
+ $text =~ s{
+ (?:\n\n|\A)
+ ( # $1 = the code block -- one or more lines, starting with a space/tab
+ (?:
+ (?:[ ]{$g_tab_width} | \t) # Lines must start with a tab or a tab-width of spaces
+ .*\n+
+ )+
+ )
+ ((?=^[ ]{0,$g_tab_width}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
+ }{
+ my $codeblock = $1;
+ my $result; # return value
+
+ $codeblock = _EncodeCode(_Outdent($codeblock));
+ $codeblock = _Detab($codeblock);
+ $codeblock =~ s/\A\n+//; # trim leading newlines
+ $codeblock =~ s/\s+\z//; # trim trailing whitespace
+
+ $result = "\n\n<pre><code>" . $codeblock . "\n</code></pre>\n\n";
+
+ $result;
+ }egmx;
+
+ return $text;
+}
+
+
+sub _DoCodeSpans {
+#
+# * Backtick quotes are used for <code></code> spans.
+#
+# * You can use multiple backticks as the delimiters if you want to
+# include literal backticks in the code span. So, this input:
+#
+# Just type ``foo `bar` baz`` at the prompt.
+#
+# Will translate to:
+#
+# <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
+#
+# There's no arbitrary limit to the number of backticks you
+# can use as delimters. If you need three consecutive backticks
+# in your code, use four for delimiters, etc.
+#
+# * You can use spaces to get literal backticks at the edges:
+#
+# ... type `` `bar` `` ...
+#
+# Turns to:
+#
+# ... type <code>`bar`</code> ...
+#
+
+ my $text = shift;
+
+ $text =~ s@
+ (`+) # $1 = Opening run of `
+ (.+?) # $2 = The code block
+ (?<!`)
+ \1 # Matching closer
+ (?!`)
+ @
+ my $c = "$2";
+ $c =~ s/^[ \t]*//g; # leading whitespace
+ $c =~ s/[ \t]*$//g; # trailing whitespace
+ $c = _EncodeCode($c);
+ "<code>$c</code>";
+ @egsx;
+
+ return $text;
+}
+
+
+sub _EncodeCode {
+#
+# Encode/escape certain characters inside Markdown code runs.
+# The point is that in code, these characters are literals,
+# and lose their special Markdown meanings.
+#
+ local $_ = shift;
+
+ # Encode all ampersands; HTML entities are not
+ # entities within a Markdown code span.
+ s/&/&/g;
+
+ # Encode $'s, but only if we're running under Blosxom.
+ # (Blosxom interpolates Perl variables in article bodies.)
+ {
+ no warnings 'once';
+ if (defined($blosxom::version)) {
+ s/\$/$/g;
+ }
+ }
+
+
+ # Do the angle bracket song and dance:
+ s! < !<!gx;
+ s! > !>!gx;
+
+ # Now, escape characters that are magic in Markdown:
+ s! \* !$g_escape_table{'*'}!gx;
+ s! _ !$g_escape_table{'_'}!gx;
+ s! { !$g_escape_table{'{'}!gx;
+ s! } !$g_escape_table{'}'}!gx;
+ s! \[ !$g_escape_table{'['}!gx;
+ s! \] !$g_escape_table{']'}!gx;
+ s! \\ !$g_escape_table{'\\'}!gx;
+
+ return $_;
+}
+
+
+sub _DoItalicsAndBold {
+ my $text = shift;
+
+ # <strong> must go first:
+ $text =~ s{ (\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1 }
+ {<strong>$2</strong>}gsx;
+
+ $text =~ s{ (\*|_) (?=\S) (.+?) (?<=\S) \1 }
+ {<em>$2</em>}gsx;
+
+ return $text;
+}
+
+
+sub _DoBlockQuotes {
+ my $text = shift;
+
+ $text =~ s{
+ ( # Wrap whole match in $1
+ (
+ ^[ \t]*>[ \t]? # '>' at the start of a line
+ .+\n # rest of the first line
+ (.+\n)* # subsequent consecutive lines
+ \n* # blanks
+ )+
+ )
+ }{
+ my $bq = $1;
+ $bq =~ s/^[ \t]*>[ \t]?//gm; # trim one level of quoting
+ $bq =~ s/^[ \t]+$//mg; # trim whitespace-only lines
+ $bq = _RunBlockGamut($bq); # recurse
+
+ $bq =~ s/^/ /g;
+ # These leading spaces screw with <pre> content, so we need to fix that:
+ $bq =~ s{
+ (\s*<pre>.+?</pre>)
+ }{
+ my $pre = $1;
+ $pre =~ s/^ //mg;
+ $pre;
+ }egsx;
+
+ "<blockquote>\n$bq\n</blockquote>\n\n";
+ }egmx;
+
+
+ return $text;
+}
+
+
+sub _FormParagraphs {
+#
+# Params:
+# $text - string to process with html <p> tags
+#
+ my $text = shift;
+
+ # Strip leading and trailing lines:
+ $text =~ s/\A\n+//;
+ $text =~ s/\n+\z//;
+
+ my @grafs = split(/\n{2,}/, $text);
+
+ #
+ # Wrap <p> tags.
+ #
+ foreach (@grafs) {
+ unless (defined( $g_html_blocks{$_} )) {
+ $_ = _RunSpanGamut($_);
+ s/^([ \t]*)/<p>/;
+ $_ .= "</p>";
+ }
+ }
+
+ #
+ # Unhashify HTML blocks
+ #
+ foreach (@grafs) {
+ if (defined( $g_html_blocks{$_} )) {
+ $_ = $g_html_blocks{$_};
+ }
+ }
+
+ return join "\n\n", @grafs;
+}
+
+
+sub _EncodeAmpsAndAngles {
+# Smart processing for ampersands and angle brackets that need to be encoded.
+
+ my $text = shift;
+
+ # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
+ # http://bumppo.net/projects/amputator/
+ $text =~ s/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/&/g;
+
+ # Encode naked <'s
+ $text =~ s{<(?![a-z/?\$!])}{<}gi;
+
+ return $text;
+}
+
+
+sub _EncodeBackslashEscapes {
+#
+# Parameter: String.
+# Returns: The string, with after processing the following backslash
+# escape sequences.
+#
+ local $_ = shift;
+
+ s! \\\\ !$g_escape_table{'\\'}!gx; # Must process escaped backslashes first.
+ s! \\` !$g_escape_table{'`'}!gx;
+ s! \\\* !$g_escape_table{'*'}!gx;
+ s! \\_ !$g_escape_table{'_'}!gx;
+ s! \\\{ !$g_escape_table{'{'}!gx;
+ s! \\\} !$g_escape_table{'}'}!gx;
+ s! \\\[ !$g_escape_table{'['}!gx;
+ s! \\\] !$g_escape_table{']'}!gx;
+ s! \\\( !$g_escape_table{'('}!gx;
+ s! \\\) !$g_escape_table{')'}!gx;
+ s! \\> !$g_escape_table{'>'}!gx;
+ s! \\\# !$g_escape_table{'#'}!gx;
+ s! \\\+ !$g_escape_table{'+'}!gx;
+ s! \\\- !$g_escape_table{'-'}!gx;
+ s! \\\. !$g_escape_table{'.'}!gx;
+ s{ \\! }{$g_escape_table{'!'}}gx;
+
+ return $_;
+}
+
+
+sub _DoAutoLinks {
+ my $text = shift;
+
+ $text =~ s{<((https?|ftp):[^'">\s]+)>}{<a href="$1">$1</a>}gi;
+
+ # Email addresses: <[email protected]>
+ $text =~ s{
+ <
+ (?:mailto:)?
+ (
+ [-.\w]+
+ \@
+ [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
+ )
+ >
+ }{
+ _EncodeEmailAddress( _UnescapeSpecialChars($1) );
+ }egix;
+
+ return $text;
+}
+
+
+sub _EncodeEmailAddress {
+#
+# Input: an email address, e.g. "[email protected]"
+#
+# Output: the email address as a mailto link, with each character
+# of the address encoded as either a decimal or hex entity, in
+# the hopes of foiling most address harvesting spam bots. E.g.:
+#
+# <a href="mailto:foo@e
+# xample.com">foo
+# @example.com</a>
+#
+# Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
+# mailing list: <http://tinyurl.com/yu7ue>
+#
+
+ my $addr = shift;
+
+ srand;
+ my @encode = (
+ sub { '&#' . ord(shift) . ';' },
+ sub { '&#x' . sprintf( "%X", ord(shift) ) . ';' },
+ sub { shift },
+ );
+
+ $addr = "mailto:" . $addr;
+
+ $addr =~ s{(.)}{
+ my $char = $1;
+ if ( $char eq '@' ) {
+ # this *must* be encoded. I insist.
+ $char = $encode[int rand 1]->($char);
+ } elsif ( $char ne ':' ) {
+ # leave ':' alone (to spot mailto: later)
+ my $r = rand;
+ # roughly 10% raw, 45% hex, 45% dec
+ $char = (
+ $r > .9 ? $encode[2]->($char) :
+ $r < .45 ? $encode[1]->($char) :
+ $encode[0]->($char)
+ );
+ }
+ $char;
+ }gex;
+
+ $addr = qq{<a href="$addr">$addr</a>};
+ $addr =~ s{">.+?:}{">}; # strip the mailto: from the visible part
+
+ return $addr;
+}
+
+
+sub _UnescapeSpecialChars {
+#
+# Swap back in all the special characters we've hidden.
+#
+ my $text = shift;
+
+ while( my($char, $hash) = each(%g_escape_table) ) {
+ $text =~ s/$hash/$char/g;
+ }
+ return $text;
+}
+
+
+sub _TokenizeHTML {
+#
+# Parameter: String containing HTML markup.
+# Returns: Reference to an array of the tokens comprising the input
+# string. Each token is either a tag (possibly with nested,
+# tags contained therein, such as <a href="<MTFoo>">, or a
+# run of text between tags. Each element of the array is a
+# two-element array; the first is either 'tag' or 'text';
+# the second is the actual value.
+#
+#
+# Derived from the _tokenize() subroutine from Brad Choate's MTRegex plugin.
+# <http://www.bradchoate.com/past/mtregex.php>
+#
+
+ my $str = shift;
+ my $pos = 0;
+ my $len = length $str;
+ my @tokens;
+
+ my $depth = 6;
+ my $nested_tags = join('|', ('(?:<[a-z/!$](?:[^<>]') x $depth) . (')*>)' x $depth);
+ my $match = qr/(?s: <! ( -- .*? -- \s* )+ > ) | # comment
+ (?s: <\? .*? \?> ) | # processing instruction
+ $nested_tags/ix; # nested tags
+
+ while ($str =~ m/($match)/g) {
+ my $whole_tag = $1;
+ my $sec_start = pos $str;
+ my $tag_start = $sec_start - length $whole_tag;
+ if ($pos < $tag_start) {
+ push @tokens, ['text', substr($str, $pos, $tag_start - $pos)];
+ }
+ push @tokens, ['tag', $whole_tag];
+ $pos = pos $str;
+ }
+ push @tokens, ['text', substr($str, $pos, $len - $pos)] if $pos < $len;
+ \@tokens;
+}
+
+
+sub _Outdent {
+#
+# Remove one level of line-leading tabs or spaces
+#
+ my $text = shift;
+
+ $text =~ s/^(\t|[ ]{1,$g_tab_width})//gm;
+ return $text;
+}
+
+
+sub _Detab {
+#
+# Cribbed from a post by Bart Lateur:
+# <http://www.nntp.perl.org/group/perl.macperl.anyperl/154>
+#
+ my $text = shift;
+
+ $text =~ s{(.*?)\t}{$1.(' ' x ($g_tab_width - length($1) % $g_tab_width))}ge;
+ return $text;
+}
+
+
+1;
+
+__END__
+
+
+=pod
+
+=head1 NAME
+
+B<Markdown>
+
+
+=head1 SYNOPSIS
+
+B<Markdown.pl> [ B<--html4tags> ] [ B<--version> ] [ B<-shortversion> ]
+ [ I<file> ... ]
+
+
+=head1 DESCRIPTION
+
+Markdown is a text-to-HTML filter; it translates an easy-to-read /
+easy-to-write structured text format into HTML. Markdown's text format
+is most similar to that of plain text email, and supports features such
+as headers, *emphasis*, code blocks, blockquotes, and links.
+
+Markdown's syntax is designed not as a generic markup language, but
+specifically to serve as a front-end to (X)HTML. You can use span-level
+HTML tags anywhere in a Markdown document, and you can use block level
+HTML tags (like <div> and <table> as well).
+
+For more information about Markdown's syntax, see:
+
+ http://daringfireball.net/projects/markdown/
+
+
+=head1 OPTIONS
+
+Use "--" to end switch parsing. For example, to open a file named "-z", use:
+
+ Markdown.pl -- -z
+
+=over 4
+
+
+=item B<--html4tags>
+
+Use HTML 4 style for empty element tags, e.g.:
+
+ <br>
+
+instead of Markdown's default XHTML style tags, e.g.:
+
+ <br />
+
+
+=item B<-v>, B<--version>
+
+Display Markdown's version number and copyright information.
+
+
+=item B<-s>, B<--shortversion>
+
+Display the short-form version number.
+
+
+=back
+
+
+
+=head1 BUGS
+
+To file bug reports or feature requests (other than topics listed in the
+Caveats section above) please send email to:
+
+ [email protected]
+
+Please include with your report: (1) the example input; (2) the output
+you expected; (3) the output Markdown actually produced.
+
+
+=head1 VERSION HISTORY
+
+See the readme file for detailed release notes for this version.
+
+1.0.1 - 14 Dec 2004
+
+1.0 - 28 Aug 2004
+
+
+=head1 AUTHOR
+
+ John Gruber
+ http://daringfireball.net
+
+ PHP port and other contributions by Michel Fortin
+ http://michelf.com
+
+
+=head1 COPYRIGHT AND LICENSE
+
+Copyright (c) 2003-2004 John Gruber
+<http://daringfireball.net/>
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+* Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+* Neither the name "Markdown" nor the names of its contributors may
+ be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+This software is provided by the copyright holders and contributors "as
+is" and any express 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 copyright owner
+or contributors 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.
+
+=cut
|
grumdrig/woses
|
8157b708b9905f84af442c4cf38b40959ca3b47e
|
Improve mixin(), albeit in ways that don't really matter.
|
diff --git a/woses.js b/woses.js
index b2c3f7a..4418529 100644
--- a/woses.js
+++ b/woses.js
@@ -1,234 +1,235 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
"use strict";
var
sys = require('sys'),
fs = require('fs'),
http = require('http'),
url = require('url'),
path = require('path');
function respondWithPhp(req, res) {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
var params = [parp, req.filepath];
for (var param in req.query)
params.push(escape(param) + "=" + escape(req.query[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers.host);
params.push("REQUEST_URI=" + req.url);
var child = require('child_process').spawn("php", params);
child.stdout.addListener('data', function (data) {
res.body += data;
});
child.stderr.addListener('data', function (data) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
});
child.addListener('exit', function (code) {
res.header("content-type", (res.body.indexOf("<?xml") === 0) ?
"application/xml" : "text/html");
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
});
}
function respondWithJsRpc(req, res) {
// TODO: use conf file to distinguish client & server js
try {
var script = require(req.basepath);
} catch (e) {
res.status = 404
res.respond("404: In absentia or error in module.\n" + sys.inspect(e));
return;
}
script.fetch(req, res);
var len = res.respond();
sys.puts(req.requestLine + " " + len);
}
function respondWithStatic(req, res) {
var content_type = config.mimetypes[req.extname] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
fs.readFile(req.filepath, res.encoding, function(err, data) {
if (err) {
sys.puts("Error 404: " + req.filepath);
res.status = 404;
res.header('content-type', 'text/plain');
res.respond('404: I looked but did not find.');
} else {
res.header('content-type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
}
});
}
-
function mixin(target, source) {
- for (name in source)
- target[name] = source[name];
+ for (var name in source) {
+ if (source.hasOwnProperty(name))
+ target[name] = source[name];
+ }
}
var config = {
port: 8080,
index: "index.html",
mimetypes: {
".css" : "text/css",
".gif" : "image/gif",
".html": "text/html",
".ico" : "image/vnd.microsoft.icon",
".jpg" : "image/jpeg",
".js" : "application/javascript",
".png" : "image/png",
".xml" : "application/xml",
".xul" : "application/vnd.mozilla.xul+xml",
},
handlers: [
[/\.php$/, respondWithPhp],
[/-rpc\.js$/, respondWithJsRpc],
[/$/, respondWithStatic]
]
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
// Read config
require.paths.push(process.cwd());
try {
var cf = require(".woses-conf");
} catch (e) {
// No config file is OK
var cf = {};
}
mixin(config.mimetypes, cf.mimetypes || {});
delete cf.mimetypes;
if (cf.handlers) {
config.handlers = cf.handlers.concat(config.handlers || []);
delete cf.handlers;
}
mixin(config, cf);
// Go
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.url + " HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
res.respond = function (body) {
this.status = this.status || 200;
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
this.encoding = this.encoding || 'utf8';
this.length = (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length);
this.header('content-length', this.length);
this.writeHead(this.status, this.headers);
this.write(this.body, this.encoding);
this.end();
return this.body.length;
}
res.header = function(header, value) {
if (!this.headers) this.headers = {};
this.headers[header] = value;
}
mixin(req, url.parse(req.url, true));
req.query = req.query || {};
if (req.pathname.substr(0,1) != '/') {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
req.filepath = req.pathname.substr(1) || config.index; // path/name.ext
if (!path.basename(req.filepath))
req.filepath = path.join(req.filepath, config.index);
req.filename = path.basename(req.filepath); // name.ext
req.extname = path.extname(req.filename); // .ext
req.basename = path.basename(req.filename, req.extname); // name
req.basepath = path.join(path.dirname(req.filepath),
req.basename); // path.name
// Exclude ".." in uri
if (req.pathname.indexOf('..') >= 0 || req.filename.substr(0,1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
req.body = '';
req.addListener('data', function(chunk) {
//req.pause();
req.body += chunk;
//setTimeout(function() { req.resume(); });
});
req.addListener('end', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var querystring = require("querystring");
var form = querystring.parse(req.body);
mixin(req.query, form);
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
mixin(req.query, req.json);
}
for (var i = 0; config.handlers[i]; ++i) {
var match = config.handlers[i][0](req.pathname);
if (match) {
req.match = match;
config.handlers[i][1](req, res);
break;
}
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
99663c38d25234f439f4dfe3b57fea010efa0d1b
|
Fix bug when no handlers in config
|
diff --git a/woses.js b/woses.js
index f76363e..b2c3f7a 100644
--- a/woses.js
+++ b/woses.js
@@ -1,232 +1,234 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
"use strict";
var
sys = require('sys'),
fs = require('fs'),
http = require('http'),
url = require('url'),
path = require('path');
function respondWithPhp(req, res) {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
var params = [parp, req.filepath];
for (var param in req.query)
params.push(escape(param) + "=" + escape(req.query[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers.host);
params.push("REQUEST_URI=" + req.url);
var child = require('child_process').spawn("php", params);
child.stdout.addListener('data', function (data) {
res.body += data;
});
child.stderr.addListener('data', function (data) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
});
child.addListener('exit', function (code) {
res.header("content-type", (res.body.indexOf("<?xml") === 0) ?
"application/xml" : "text/html");
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
});
}
function respondWithJsRpc(req, res) {
// TODO: use conf file to distinguish client & server js
try {
var script = require(req.basepath);
} catch (e) {
res.status = 404
res.respond("404: In absentia or error in module.\n" + sys.inspect(e));
return;
}
script.fetch(req, res);
var len = res.respond();
sys.puts(req.requestLine + " " + len);
}
function respondWithStatic(req, res) {
var content_type = config.mimetypes[req.extname] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
fs.readFile(req.filepath, res.encoding, function(err, data) {
if (err) {
sys.puts("Error 404: " + req.filepath);
res.status = 404;
res.header('content-type', 'text/plain');
res.respond('404: I looked but did not find.');
} else {
res.header('content-type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
}
});
}
function mixin(target, source) {
for (name in source)
target[name] = source[name];
}
var config = {
port: 8080,
index: "index.html",
mimetypes: {
".css" : "text/css",
".gif" : "image/gif",
".html": "text/html",
".ico" : "image/vnd.microsoft.icon",
".jpg" : "image/jpeg",
".js" : "application/javascript",
".png" : "image/png",
".xml" : "application/xml",
".xul" : "application/vnd.mozilla.xul+xml",
},
handlers: [
[/\.php$/, respondWithPhp],
[/-rpc\.js$/, respondWithJsRpc],
[/$/, respondWithStatic]
]
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
// Read config
require.paths.push(process.cwd());
try {
var cf = require(".woses-conf");
} catch (e) {
// No config file is OK
var cf = {};
}
mixin(config.mimetypes, cf.mimetypes || {});
delete cf.mimetypes;
-config.handlers = cf.handlers.concat(config.handlers || []);
-delete cf.handlers;
+if (cf.handlers) {
+ config.handlers = cf.handlers.concat(config.handlers || []);
+ delete cf.handlers;
+}
mixin(config, cf);
// Go
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.url + " HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
res.respond = function (body) {
this.status = this.status || 200;
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
this.encoding = this.encoding || 'utf8';
this.length = (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length);
this.header('content-length', this.length);
this.writeHead(this.status, this.headers);
this.write(this.body, this.encoding);
this.end();
return this.body.length;
}
res.header = function(header, value) {
if (!this.headers) this.headers = {};
this.headers[header] = value;
}
mixin(req, url.parse(req.url, true));
req.query = req.query || {};
if (req.pathname.substr(0,1) != '/') {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
req.filepath = req.pathname.substr(1) || config.index; // path/name.ext
if (!path.basename(req.filepath))
req.filepath = path.join(req.filepath, config.index);
req.filename = path.basename(req.filepath); // name.ext
req.extname = path.extname(req.filename); // .ext
req.basename = path.basename(req.filename, req.extname); // name
req.basepath = path.join(path.dirname(req.filepath),
req.basename); // path.name
// Exclude ".." in uri
if (req.pathname.indexOf('..') >= 0 || req.filename.substr(0,1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
req.body = '';
req.addListener('data', function(chunk) {
//req.pause();
req.body += chunk;
//setTimeout(function() { req.resume(); });
});
req.addListener('end', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var querystring = require("querystring");
var form = querystring.parse(req.body);
mixin(req.query, form);
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
mixin(req.query, req.json);
}
for (var i = 0; config.handlers[i]; ++i) {
var match = config.handlers[i][0](req.pathname);
if (match) {
req.match = match;
config.handlers[i][1](req, res);
break;
}
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
f5d3ff08981f978c5be516206f43ccc9a12c1dbe
|
Minor doc edits
|
diff --git a/README.md b/README.md
index 282790e..1b531bd 100644
--- a/README.md
+++ b/README.md
@@ -1,17 +1,21 @@
Woses
=====
-HTTP server for static and PHP files via [Node](http://nodejs.org/)
+HTTP server for static, PHP and JS server files via [Node](http://nodejs.org/)
Project home is at [http://grumdrig.com/woses/].
Source code lives at [http://github.com/grumdrig/woses].
Usage
-----
-`$ node woses.js`
+`$ node woses.js [HTML_ROOT]`
+
+or
+
+`$ ./serverloop.py [HTML_ROOT]`
Tested with Node version v0.1.25-15-g4e16e38
|
grumdrig/woses
|
d3e0eb260d87541dec4737e7b57f66a527c1d687
|
Coffeescript version of woses. Watch out - compiling it wipes out woses.js
|
diff --git a/woses.coffee b/woses.coffee
new file mode 100644
index 0000000..b13770a
--- /dev/null
+++ b/woses.coffee
@@ -0,0 +1,185 @@
+#
+# HTTP server for static and PHP files via Node.js (nodejs.org)
+# See http://bitbucket.org/grumdrig/woses/wiki/Home
+#
+# Usage: node woses.js DOCUMENT_ROOT
+#
+# By Eric Fredricksen <[email protected]> in 2010 and perhaps onwards.
+# No rights reserved; this code is placed into the public domain.
+#
+
+sys: require 'sys'
+fs: require 'fs'
+http: require 'http'
+url: require 'url'
+path: require 'path'
+
+
+respondWithPhp: (req, res) ->
+ res.body: ''
+ parp: __filename.split('/').slice(0,-1).concat("parp.php").join("/")
+ params: [parp, req.filepath].concat(for param,value of req.query
+ escape(param) + "=" + escape(value))
+
+ params.push "-s"
+ params.push "HTTP_USER_AGENT=" + req.headers['user-agent']
+ params.push "HTTP_HOST=" + req.headers.host
+ params.push "REQUEST_URI=" + req.url
+ child: require('child_process').spawn("php", params)
+ child.stdout.addListener 'data', (data) ->
+ res.body += data
+ child.stderr.addListener 'data', (data) ->
+ sys.puts "STDERR (php): " + content
+ child.addListener 'exit', (code) ->
+ res.header('content-type', if res.body.indexOf("<?xml") == 0 then "application/xml" else "text/html")
+ sys.puts req.requestLine + " (php) " + res.body.length
+ res.status: 404 if res.body.match(/^404:/)
+ res.respond()
+
+
+
+respondWithJsRpc: (req, res) ->
+ # TODO: use conf file to distinguish client & server js
+ try
+ script: require(req.basepath)
+ catch e
+ res.status: 404
+ res.respond "404: In absentia or error in module.\n" + sys.inspect(e)
+ return
+ script.fetch(req, res)
+ len: res.respond()
+ sys.puts(req.requestLine + " " + len)
+
+
+
+respondWithStatic: (req, res) ->
+ content_type: config.mimetypes[req.extname] || "text/plain"
+ res.encoding: if content_type.slice(0,4) == 'text' then 'utf8' else 'binary'
+ fs.readFile req.filepath, res.encoding, (err, data) ->
+ if err
+ sys.puts("Error 404: " + req.filepath)
+ res.status: 404
+ res.header('content-type', 'text/plain')
+ res.respond('404: I looked but did not find.')
+ else
+ res.header('content-type', content_type)
+ sys.puts(req.requestLine + " " + data.length)
+ res.respond(data)
+
+
+mixin: (target, source) ->
+ for name,value of source
+ target[name]: value
+
+config: {
+ port: 8080,
+ index: "index.html",
+ mimetypes: {
+ ".css" : "text/css",
+ ".gif" : "image/gif",
+ ".html": "text/html",
+ ".ico" : "image/vnd.microsoft.icon",
+ ".jpg" : "image/jpeg",
+ ".js" : "application/javascript",
+ ".png" : "image/png",
+ ".xml" : "application/xml",
+ ".xul" : "application/vnd.mozilla.xul+xml",
+ },
+ handlers: [
+ [/\.php$/, respondWithPhp],
+ [/-rpc\.js$/, respondWithJsRpc],
+ [/$/, respondWithStatic]
+ ]
+}
+
+
+process.chdir(process.ARGV[2]) if process.ARGV.length > 2
+
+
+# Read config
+
+require.paths.push(process.cwd())
+
+try
+ cf: require(".woses-conf")
+catch e
+ # No config file is OK
+ cf: {}
+mixin(config.mimetypes, cf.mimetypes || {})
+delete cf.mimetypes
+
+if cf.handlers
+ config.handlers: cf.handlers.concat(config.handlers || [])
+ delete cf.handlers
+
+mixin(config, cf)
+
+# Go
+
+serverFn: (req, res) ->
+ req.requestLine: req.method + " " + req.url + " HTTP/" + req.httpVersion
+
+ sys.p(req.headers) if (config.logRequestHeaders)
+
+ res.respond: (body) ->
+ this.status: this.status || 200
+ this.body: body || this.body || ""
+ if (typeof this.body != 'string')
+ this.header("content-type", "application/json")
+ this.body: JSON.stringify(this.body)
+ this.encoding: this.encoding || 'utf8'
+ this.length: if this.encoding == 'utf8' then encodeURIComponent(this.body).replace(/%../g, 'x').length else this.body.length
+ this.header('content-length', this.length)
+
+ this.writeHead(this.status, this.headers)
+ this.write(this.body, this.encoding)
+ this.end()
+ return this.body.length
+
+ res.header: (header, value) ->
+ this.headers: or {}
+ this.headers[header]: value
+
+ mixin(req, url.parse(req.url, true))
+ req.query: or {}
+ if req.pathname.substr(0,1) != '/'
+ res.status: 400
+ return res.respond("400: I have no idea what that is")
+ req.filepath: req.pathname.substr(1) || config.index # path/name.ext
+ if not path.basename(req.filepath)
+ req.filepath: path.join(req.filepath, config.index)
+ req.filename: path.basename(req.filepath) # name.ext
+ req.extname : path.extname(req.filename) # .ext
+ req.basename: path.basename(req.filename, req.extname) # name
+ req.basepath: path.join(path.dirname(req.filepath),
+ req.basename) # path.name
+
+ # Exclude ".." in uri
+ if req.pathname.indexOf('..') >= 0 || req.filename.substr(0,1) == "."
+ res.status: 403
+ return res.respond("403: Don't hack me, bro")
+
+ req.body: ''
+ req.addListener('data', (chunk) -> req.body += chunk)
+ req.addListener 'end', () ->
+ ct: req.headers['content-type']
+ ct: and ct.split(';')[0]
+ if ct == "application/x-www-form-urlencoded"
+ form: require("querystring").parse(req.body)
+ mixin(req.query, form)
+ else if ct == "application/json"
+ req.json: JSON.parse(req.body)
+ mixin(req.query, req.json)
+
+ for handler in config.handlers
+ req.match: handler[0](req.pathname)
+ if req.match
+ handler[1](req, res)
+ break
+
+http.createServer(serverFn).listen(config.port)
+
+
+sys.puts('Woses running at http://127.0.0.1:' +
+ config.port + '/ in ' +
+ process.cwd())
|
grumdrig/woses
|
a58397f94752da2944cb0e75fddc08f8398085cc
|
Various minor edits, e.g. stray semicolons
|
diff --git a/woses.js b/woses.js
index 976a633..19788a8 100644
--- a/woses.js
+++ b/woses.js
@@ -1,225 +1,227 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
-var
+"use strict";
+
+var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
url = require('url'),
path = require('path');
function respondWithPhp(req, res) {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
var params = [parp, req.filepath];
for (var param in req.query)
params.push(escape(param) + "=" + escape(req.query[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
- params.push("HTTP_HOST=" + req.headers['host']);
+ params.push("HTTP_HOST=" + req.headers.host);
params.push("REQUEST_URI=" + req.url);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
- "application/xml" : "text/html")
+ "application/xml" : "text/html");
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
- if (content != null) {
+ if (content !== null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
function respondWithJsRpc(req, res) {
// TODO: use conf file to distinguish client & server js
try {
var script = require(req.basepath);
} catch (e) {
res.status = 404
res.respond("404: In absentia or error in module.\n" + sys.inspect(e));
return;
}
script.fetch(req, res);
var len = res.respond();
sys.puts(req.requestLine + " " + len);
}
function respondWithStatic(req, res) {
var content_type = config.mimetypes[req.extname] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
var promise = posix.cat(req.filepath, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function(data) {
sys.puts("Error 404: " + req.filepath);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
var config = {
port: 8080,
index: "index.html",
mimetypes: {
".css" : "text/css",
+ ".gif" : "image/gif",
".html": "text/html",
".ico" : "image/vnd.microsoft.icon",
".jpg" : "image/jpeg",
".js" : "application/javascript",
".png" : "image/png",
".xml" : "application/xml",
".xul" : "application/vnd.mozilla.xul+xml",
},
handlers: [
[/\.php$/, respondWithPhp],
[/-rpc\.js$/, respondWithJsRpc],
[/$/, respondWithStatic]
]
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
require.paths.push(process.cwd());
try {
var cf = require(".woses-conf");
} catch (e) {
// No config file is OK
- var cf = {}
+ var cf = {};
}
config.port = cf.port || config.port;
-config.index = cf.index || config.index
+config.index = cf.index || config.index;
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
}
if (cf.handlers) {
config.handlers = cf.handlers.concat(config.handlers);
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.url + " HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
var result = this.body ? this.body.length : 0;
this.encoding = this.encoding || 'utf8';
res.header('Content-Length', (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length));
this.sendBody(this.body, this.encoding);
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
process.mixin(req, url.parse(req.url, true));
req.query = req.query || {};
if (req.pathname.substr(0,1) != '/') {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
req.filepath = req.pathname.substr(1) || config.index; // path/name.ext
if (!path.basename(req.filepath))
req.filepath = path.join(req.filepath, config.index);
req.filename = path.basename(req.filepath); // name.ext
req.extname = path.extname(req.filename); // .ext
req.basename = path.basename(req.filename, req.extname); // name
req.basepath = path.join(path.dirname(req.filepath),
req.basename); // path.name
// Exclude ".." in uri
if (req.pathname.indexOf('..') >= 0 || req.filename.substr(0,1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var querystring = require("querystring");
var form = querystring.parse(req.body);
- for (var param in form)
- req.query[param] = form[param];
+ process.mixin(req.query, form);
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
process.mixin(req.query, req.json);
}
for (var i = 0; config.handlers[i]; ++i) {
var match = config.handlers[i][0](req.pathname);
if (match) {
req.match = match;
config.handlers[i][1](req, res);
break;
}
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
5381b79d80da69d9fd9a44ebc67420b54f3479b0
|
Dont make handlers call response.respond
|
diff --git a/doc/index.html b/doc/index.html
index 56a2262..aba2cb5 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,126 +1,125 @@
<head>
<title>Woses Webserver</title>
<link rel="stylesheet" href="style.css"/>
<link rel="icon" href="wose.png"/>
</head>
<body>
<h1>
<!--☶ ☁ ⎈ 𐂷 ☃-->
Woses <span class=right style=color:black>⚉</span>
</h1>
<p>
Woses is a <a href=http://nodejs.org/>Node</a>-based webserver with
support for <a href=http://php.net/>PHP</a> templating.
<p>
Additionally it includes a mechanism for server-side JavaScript RPC.
<p>
The home page for Woses is
<a href=http://grumdrig.com/woses/>http://grumdrig.com/woses/</a>. The
code lives at
<a href=http://github.com/grumdrig/woses>http://github.com/grumdrig/woses</a>.
<h2>Usage</h2>
<pre>
$ node woses.js DOCUMENT_ROOT
</pre>
will run the HTTP server against the content in DOCUMENT_ROOT. For example,
<pre>
$ node woses.js doc
</pre>
<p>
will serve this documentation on <a href=http://localhost:8080/>port
8080</a>.
<p>
Included also is the script <code>serverloop.py</code> which runs the
server in a loop, polling for changes to the configuration
file, <code>woses.js</code>, or files listed on the command line.
Changes or <code>^C</code> restart the server. This is most useful for
running the server during development. Usage is:
<pre>
$ ./serverloop.py DOCUMENT_ROOT [OTHER_FILES...]
</pre>
<h2> Configuration </h2>
<p>
Woses can be configured by placing a file
called <code>.woses-conf.js</code> in the document root. This file may
export the following settings:
<ul>
<li> <code>port</code>: A port other than the default 8080 on which to
serve.
<li> <code>index</code>: Name of a directory index page to use for
URI's which point to a folder, rather than the
default, <code>index.html</code> falling back
to <code>index.php</code>.
<li> <code>mimetypes</code>: A map from file extensions to MIME types
for serving content.
</ul>
Here is an example configuration file:
<pre>
exports.port = 80;
exports.index = "home.html";
exports.mimetypes = {
'.gif': 'image/gif',
'.readme': 'text/plain'
}
</pre>
<h2> PHP </h2>
<p>
Woses will serve PHP scripts through the mechanism of the PHP
command-line interface; thus the <code>php</code> command must be available for
woses to serve PHP scripts.
<p>
The big caveat of PHP support is that, within PHP code, calls to
`header()' have no effect.
<h2> JS RPC </h2>
<p>
Requests for filenames ending in <code>-rpc.js</code> (some more
sensible mechanism to distinguish is a TODO item) are loaded as
modules and the HTTP request is proxied through their
exported <code>fetch</code> function, with signature:
<pre>
exports.fetch = function(request, response) {
// ...
response.body = ...;
- return response.respond();
};
</pre>
<h2> JS Templating </h2>
<p>
Templating in the style of EJS / Resig's micro-templating is planned,
but not implemented
<h2> Security </h2>
<p>
URLs with ".." in them are disallowed, but security is probably poor
at the moment. That is, an attacker may be able to pwn your system if
you are running this on a public server.
<h2> Tests </h2>
If this page is served by Woses itself,
<a href=test.html>this is a test page.</a>
diff --git a/doc/json-rpc.js b/doc/json-rpc.js
index cfffab2..96efb56 100644
--- a/doc/json-rpc.js
+++ b/doc/json-rpc.js
@@ -1,8 +1,7 @@
var sys = require("sys");
exports.fetch = function (request, response) {
response.header("content-type", "application/json");
response.body = {sum: request.json.a + request.json.b,
aka: request.query.a + request.query.b};
- return response.respond();
}
diff --git a/doc/test-rpc.js b/doc/test-rpc.js
index 0a5004a..8f24db6 100644
--- a/doc/test-rpc.js
+++ b/doc/test-rpc.js
@@ -1,7 +1,6 @@
var sys = require("sys");
exports.fetch = function (request, response) {
response.header("content-type", "text/html");
response.body = "Got it. <pre>" + sys.inspect(request.query);
- return response.respond();
}
diff --git a/woses.js b/woses.js
index e065212..976a633 100644
--- a/woses.js
+++ b/woses.js
@@ -1,231 +1,225 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
url = require('url'),
path = require('path');
function respondWithPhp(req, res) {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
var params = [parp, req.filepath];
for (var param in req.query)
params.push(escape(param) + "=" + escape(req.query[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.url);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
"application/xml" : "text/html")
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
function respondWithJsRpc(req, res) {
// TODO: use conf file to distinguish client & server js
try {
var script = require(req.basepath);
- // TODO: don't have fetch call respond - just set body
- var len = script.fetch(req, res);
- sys.puts(req.requestLine + " " + len);
} catch (e) {
res.status = 404
- res.respond("404: In absentia. Or elsewhere.\n" +
- sys.inspect(e));
+ res.respond("404: In absentia or error in module.\n" + sys.inspect(e));
+ return;
}
+ script.fetch(req, res);
+ var len = res.respond();
+ sys.puts(req.requestLine + " " + len);
}
function respondWithStatic(req, res) {
var content_type = config.mimetypes[req.extname] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
var promise = posix.cat(req.filepath, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function(data) {
sys.puts("Error 404: " + req.filepath);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
var config = {
port: 8080,
index: "index.html",
mimetypes: {
".css" : "text/css",
".html": "text/html",
".ico" : "image/vnd.microsoft.icon",
".jpg" : "image/jpeg",
".js" : "application/javascript",
".png" : "image/png",
".xml" : "application/xml",
".xul" : "application/vnd.mozilla.xul+xml",
},
handlers: [
[/\.php$/, respondWithPhp],
[/-rpc\.js$/, respondWithJsRpc],
[/$/, respondWithStatic]
]
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
require.paths.push(process.cwd());
-try {
- posix.stat(config.index).wait();
-} catch (e) {
- config.index = "index.html"
-}
-
try {
var cf = require(".woses-conf");
} catch (e) {
// No config file is OK
var cf = {}
}
config.port = cf.port || config.port;
config.index = cf.index || config.index
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
}
if (cf.handlers) {
config.handlers = cf.handlers.concat(config.handlers);
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.url + " HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
var result = this.body ? this.body.length : 0;
this.encoding = this.encoding || 'utf8';
res.header('Content-Length', (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length));
this.sendBody(this.body, this.encoding);
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
process.mixin(req, url.parse(req.url, true));
req.query = req.query || {};
if (req.pathname.substr(0,1) != '/') {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
req.filepath = req.pathname.substr(1) || config.index; // path/name.ext
if (!path.basename(req.filepath))
req.filepath = path.join(req.filepath, config.index);
req.filename = path.basename(req.filepath); // name.ext
req.extname = path.extname(req.filename); // .ext
req.basename = path.basename(req.filename, req.extname); // name
req.basepath = path.join(path.dirname(req.filepath),
req.basename); // path.name
// Exclude ".." in uri
if (req.pathname.indexOf('..') >= 0 || req.filename.substr(0,1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var querystring = require("querystring");
var form = querystring.parse(req.body);
for (var param in form)
req.query[param] = form[param];
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
process.mixin(req.query, req.json);
}
for (var i = 0; config.handlers[i]; ++i) {
var match = config.handlers[i][0](req.pathname);
if (match) {
req.match = match;
config.handlers[i][1](req, res);
break;
}
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
4c2f2385c93f237036fd9385f399f9da1521da0c
|
Use path module rather than my regexp and fix config.index past root / URI
|
diff --git a/doc/.woses-conf.js b/doc/.woses-conf.js
index 543e721..f2d8135 100644
--- a/doc/.woses-conf.js
+++ b/doc/.woses-conf.js
@@ -1,23 +1,23 @@
var sys = require("sys");
exports.mimetypes = {
- gif: "image/gif"
+ '.gif': "image/gif"
}
exports.port = 8080;
//exports.logRequestHeaders = true;
function respondWithMarkdown(req, res) {
- sys.exec("Markdown.pl < " + req.filename)
+ sys.exec("Markdown.pl < " + req.filepath)
.addCallback(function (stdout, stderr) {
res.respond(stdout);})
.addErrback(function (code, stdout, stderr) {
res.status = 404;
res.respond("404: Mark my words. No such file.");
});
}
exports.handlers = [
- [/\.(md|markdown)$/, respondWithMarkdown]
+ [/\.(md|mkd|markdown)$/, respondWithMarkdown]
];
\ No newline at end of file
diff --git a/doc/index.html b/doc/index.html
index f1849b3..56a2262 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,126 +1,126 @@
<head>
<title>Woses Webserver</title>
<link rel="stylesheet" href="style.css"/>
<link rel="icon" href="wose.png"/>
</head>
<body>
<h1>
<!--☶ ☁ ⎈ 𐂷 ☃-->
Woses <span class=right style=color:black>⚉</span>
</h1>
<p>
Woses is a <a href=http://nodejs.org/>Node</a>-based webserver with
support for <a href=http://php.net/>PHP</a> templating.
<p>
Additionally it includes a mechanism for server-side JavaScript RPC.
<p>
The home page for Woses is
<a href=http://grumdrig.com/woses/>http://grumdrig.com/woses/</a>. The
code lives at
<a href=http://github.com/grumdrig/woses>http://github.com/grumdrig/woses</a>.
<h2>Usage</h2>
<pre>
$ node woses.js DOCUMENT_ROOT
</pre>
will run the HTTP server against the content in DOCUMENT_ROOT. For example,
<pre>
$ node woses.js doc
</pre>
<p>
will serve this documentation on <a href=http://localhost:8080/>port
8080</a>.
<p>
Included also is the script <code>serverloop.py</code> which runs the
server in a loop, polling for changes to the configuration
file, <code>woses.js</code>, or files listed on the command line.
Changes or <code>^C</code> restart the server. This is most useful for
running the server during development. Usage is:
<pre>
$ ./serverloop.py DOCUMENT_ROOT [OTHER_FILES...]
</pre>
<h2> Configuration </h2>
<p>
Woses can be configured by placing a file
called <code>.woses-conf.js</code> in the document root. This file may
export the following settings:
<ul>
<li> <code>port</code>: A port other than the default 8080 on which to
serve.
<li> <code>index</code>: Name of a directory index page to use for
URI's which point to a folder, rather than the
default, <code>index.html</code> falling back
to <code>index.php</code>.
<li> <code>mimetypes</code>: A map from file extensions to MIME types
for serving content.
</ul>
Here is an example configuration file:
<pre>
exports.port = 80;
exports.index = "home.html";
exports.mimetypes = {
- 'gif': 'image/gif',
- 'readme': 'text/plain'
+ '.gif': 'image/gif',
+ '.readme': 'text/plain'
}
</pre>
<h2> PHP </h2>
<p>
Woses will serve PHP scripts through the mechanism of the PHP
command-line interface; thus the <code>php</code> command must be available for
woses to serve PHP scripts.
<p>
The big caveat of PHP support is that, within PHP code, calls to
`header()' have no effect.
<h2> JS RPC </h2>
<p>
Requests for filenames ending in <code>-rpc.js</code> (some more
sensible mechanism to distinguish is a TODO item) are loaded as
modules and the HTTP request is proxied through their
exported <code>fetch</code> function, with signature:
<pre>
exports.fetch = function(request, response) {
// ...
response.body = ...;
return response.respond();
};
</pre>
<h2> JS Templating </h2>
<p>
Templating in the style of EJS / Resig's micro-templating is planned,
but not implemented
<h2> Security </h2>
<p>
URLs with ".." in them are disallowed, but security is probably poor
at the moment. That is, an attacker may be able to pwn your system if
you are running this on a public server.
<h2> Tests </h2>
If this page is served by Woses itself,
<a href=test.html>this is a test page.</a>
diff --git a/woses.js b/woses.js
index f5bda92..e065212 100644
--- a/woses.js
+++ b/woses.js
@@ -1,231 +1,231 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
- url = require('url');
+ url = require('url'),
+ path = require('path');
function respondWithPhp(req, res) {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
- var params = [parp, req.filename];
+ var params = [parp, req.filepath];
for (var param in req.query)
params.push(escape(param) + "=" + escape(req.query[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.url);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
"application/xml" : "text/html")
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
function respondWithJsRpc(req, res) {
// TODO: use conf file to distinguish client & server js
try {
- var script = require(req.basename);
+ var script = require(req.basepath);
// TODO: don't have fetch call respond - just set body
var len = script.fetch(req, res);
sys.puts(req.requestLine + " " + len);
} catch (e) {
res.status = 404
res.respond("404: In absentia. Or elsewhere.\n" +
sys.inspect(e));
}
}
function respondWithStatic(req, res) {
- var content_type = config.mimetypes[req.ext] || "text/plain";
+ var content_type = config.mimetypes[req.extname] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
- var promise = posix.cat(req.filename, res.encoding);
+ var promise = posix.cat(req.filepath, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function(data) {
- sys.puts("Error 404: " + req.filename);
+ sys.puts("Error 404: " + req.filepath);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
var config = {
port: 8080,
index: "index.html",
mimetypes: {
- "css" : "text/css",
- "html": "text/html",
- "ico" : "image/vnd.microsoft.icon",
- "jpg" : "image/jpeg",
- "js" : "application/javascript",
- "png" : "image/png",
- "xml" : "application/xml",
- "xul" : "application/vnd.mozilla.xul+xml",
+ ".css" : "text/css",
+ ".html": "text/html",
+ ".ico" : "image/vnd.microsoft.icon",
+ ".jpg" : "image/jpeg",
+ ".js" : "application/javascript",
+ ".png" : "image/png",
+ ".xml" : "application/xml",
+ ".xul" : "application/vnd.mozilla.xul+xml",
},
handlers: [
[/\.php$/, respondWithPhp],
[/-rpc\.js$/, respondWithJsRpc],
[/$/, respondWithStatic]
]
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
require.paths.push(process.cwd());
try {
posix.stat(config.index).wait();
} catch (e) {
- config.index = "index.php"
+ config.index = "index.html"
}
try {
var cf = require(".woses-conf");
- if (cf.mimetypes) {
- process.mixin(config.mimetypes, cf.mimetypes);
- delete cf.mimetypes;
- }
- if (cf.handlers) {
- config.handlers = cf.handlers.concat(config.handlers);
- delete cf.handlers;
- }
- process.mixin(config, cf);
- config.validate();
} catch (e) {
// No config file is OK
+ var cf = {}
+}
+config.port = cf.port || config.port;
+config.index = cf.index || config.index
+if (cf.mimetypes) {
+ process.mixin(config.mimetypes, cf.mimetypes);
+}
+if (cf.handlers) {
+ config.handlers = cf.handlers.concat(config.handlers);
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.url + " HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
- if (req.url == '/')
- req.url = "/" + config.index;
-
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
var result = this.body ? this.body.length : 0;
this.encoding = this.encoding || 'utf8';
res.header('Content-Length', (this.encoding === 'utf8' ?
- encodeURIComponent(this.body).replace(/%../g, 'x').length :
+ encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length));
this.sendBody(this.body, this.encoding);
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
- req.query = req.query || {};
process.mixin(req, url.parse(req.url, true));
- var uriparts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(req.pathname);
- if (!uriparts) {
+ req.query = req.query || {};
+ if (req.pathname.substr(0,1) != '/') {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
- req.filename = uriparts[1];
- req.basename = uriparts[2];
- req.ext = uriparts[4];
+ req.filepath = req.pathname.substr(1) || config.index; // path/name.ext
+ if (!path.basename(req.filepath))
+ req.filepath = path.join(req.filepath, config.index);
+ req.filename = path.basename(req.filepath); // name.ext
+ req.extname = path.extname(req.filename); // .ext
+ req.basename = path.basename(req.filename, req.extname); // name
+ req.basepath = path.join(path.dirname(req.filepath),
+ req.basename); // path.name
// Exclude ".." in uri
if (req.pathname.indexOf('..') >= 0 || req.filename.substr(0,1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var querystring = require("querystring");
var form = querystring.parse(req.body);
- sys.p(form);
for (var param in form)
req.query[param] = form[param];
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
process.mixin(req.query, req.json);
}
for (var i = 0; config.handlers[i]; ++i) {
var match = config.handlers[i][0](req.pathname);
if (match) {
req.match = match;
config.handlers[i][1](req, res);
break;
}
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
d79650d2f6f6497b6238c13a2115217afe5a0dcd
|
Lose redundant req.params and use querystring module.
|
diff --git a/doc/index.html b/doc/index.html
index 14dae87..f1849b3 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,125 +1,126 @@
<head>
<title>Woses Webserver</title>
<link rel="stylesheet" href="style.css"/>
+ <link rel="icon" href="wose.png"/>
</head>
<body>
<h1>
<!--☶ ☁ ⎈ 𐂷 ☃-->
Woses <span class=right style=color:black>⚉</span>
</h1>
<p>
Woses is a <a href=http://nodejs.org/>Node</a>-based webserver with
support for <a href=http://php.net/>PHP</a> templating.
<p>
Additionally it includes a mechanism for server-side JavaScript RPC.
<p>
The home page for Woses is
<a href=http://grumdrig.com/woses/>http://grumdrig.com/woses/</a>. The
code lives at
<a href=http://github.com/grumdrig/woses>http://github.com/grumdrig/woses</a>.
<h2>Usage</h2>
<pre>
$ node woses.js DOCUMENT_ROOT
</pre>
will run the HTTP server against the content in DOCUMENT_ROOT. For example,
<pre>
$ node woses.js doc
</pre>
<p>
will serve this documentation on <a href=http://localhost:8080/>port
8080</a>.
<p>
Included also is the script <code>serverloop.py</code> which runs the
server in a loop, polling for changes to the configuration
file, <code>woses.js</code>, or files listed on the command line.
Changes or <code>^C</code> restart the server. This is most useful for
running the server during development. Usage is:
<pre>
$ ./serverloop.py DOCUMENT_ROOT [OTHER_FILES...]
</pre>
<h2> Configuration </h2>
<p>
Woses can be configured by placing a file
called <code>.woses-conf.js</code> in the document root. This file may
export the following settings:
<ul>
<li> <code>port</code>: A port other than the default 8080 on which to
serve.
<li> <code>index</code>: Name of a directory index page to use for
URI's which point to a folder, rather than the
default, <code>index.html</code> falling back
to <code>index.php</code>.
<li> <code>mimetypes</code>: A map from file extensions to MIME types
for serving content.
</ul>
Here is an example configuration file:
<pre>
exports.port = 80;
exports.index = "home.html";
exports.mimetypes = {
'gif': 'image/gif',
'readme': 'text/plain'
}
</pre>
<h2> PHP </h2>
<p>
Woses will serve PHP scripts through the mechanism of the PHP
command-line interface; thus the <code>php</code> command must be available for
woses to serve PHP scripts.
<p>
The big caveat of PHP support is that, within PHP code, calls to
`header()' have no effect.
<h2> JS RPC </h2>
<p>
Requests for filenames ending in <code>-rpc.js</code> (some more
sensible mechanism to distinguish is a TODO item) are loaded as
modules and the HTTP request is proxied through their
exported <code>fetch</code> function, with signature:
<pre>
exports.fetch = function(request, response) {
// ...
response.body = ...;
return response.respond();
};
</pre>
<h2> JS Templating </h2>
<p>
Templating in the style of EJS / Resig's micro-templating is planned,
but not implemented
<h2> Security </h2>
<p>
URLs with ".." in them are disallowed, but security is probably poor
at the moment. That is, an attacker may be able to pwn your system if
you are running this on a public server.
<h2> Tests </h2>
If this page is served by Woses itself,
<a href=test.html>this is a test page.</a>
diff --git a/doc/json-rpc.js b/doc/json-rpc.js
index 9aec584..cfffab2 100644
--- a/doc/json-rpc.js
+++ b/doc/json-rpc.js
@@ -1,8 +1,8 @@
var sys = require("sys");
exports.fetch = function (request, response) {
response.header("content-type", "application/json");
response.body = {sum: request.json.a + request.json.b,
- aka: request.params.a + request.params.b};
+ aka: request.query.a + request.query.b};
return response.respond();
}
diff --git a/doc/test-rpc.js b/doc/test-rpc.js
index 63135e3..0a5004a 100644
--- a/doc/test-rpc.js
+++ b/doc/test-rpc.js
@@ -1,8 +1,7 @@
var sys = require("sys");
exports.fetch = function (request, response) {
response.header("content-type", "text/html");
- //sys.p(repsonse.headers);
- response.body = "Got it. <pre>" + sys.inspect(request.params);
+ response.body = "Got it. <pre>" + sys.inspect(request.query);
return response.respond();
}
diff --git a/woses.js b/woses.js
index 643da50..f5bda92 100644
--- a/woses.js
+++ b/woses.js
@@ -1,240 +1,231 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
url = require('url');
function respondWithPhp(req, res) {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
var params = [parp, req.filename];
- for (var param in req.params)
- params.push(escape(param) + "=" + escape(req.params[param]));
+ for (var param in req.query)
+ params.push(escape(param) + "=" + escape(req.query[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.url);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
"application/xml" : "text/html")
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
function respondWithJsRpc(req, res) {
// TODO: use conf file to distinguish client & server js
try {
var script = require(req.basename);
// TODO: don't have fetch call respond - just set body
var len = script.fetch(req, res);
sys.puts(req.requestLine + " " + len);
} catch (e) {
res.status = 404
res.respond("404: In absentia. Or elsewhere.\n" +
sys.inspect(e));
}
}
function respondWithStatic(req, res) {
var content_type = config.mimetypes[req.ext] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
var promise = posix.cat(req.filename, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function(data) {
sys.puts("Error 404: " + req.filename);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
var config = {
port: 8080,
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
},
handlers: [
[/\.php$/, respondWithPhp],
[/-rpc\.js$/, respondWithJsRpc],
[/$/, respondWithStatic]
]
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
require.paths.push(process.cwd());
try {
posix.stat(config.index).wait();
} catch (e) {
config.index = "index.php"
}
try {
var cf = require(".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
if (cf.handlers) {
config.handlers = cf.handlers.concat(config.handlers);
delete cf.handlers;
}
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.url + " HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
if (req.url == '/')
req.url = "/" + config.index;
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
var result = this.body ? this.body.length : 0;
this.encoding = this.encoding || 'utf8';
res.header('Content-Length', (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length));
this.sendBody(this.body, this.encoding);
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
req.query = req.query || {};
process.mixin(req, url.parse(req.url, true));
var uriparts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(req.pathname);
if (!uriparts) {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
req.filename = uriparts[1];
req.basename = uriparts[2];
req.ext = uriparts[4];
// Exclude ".." in uri
if (req.pathname.indexOf('..') >= 0 || req.filename.substr(0,1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
- function decodeForm(data) {
- var result = {};
- data
- .split("&")
- .map(function (assignment) { return assignment.split("=").map(
- function (tok) { return decodeURIComponent(tok.replace(/\+/g, " "));})})
- .forEach(function(pair) { result[pair[0]] = pair[1]; });
- return result;
- }
-
- req.params = req.query; // TODO: get rid of this redundancy
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
- var form = decodeForm(req.body);
+ var querystring = require("querystring");
+ var form = querystring.parse(req.body);
+ sys.p(form);
for (var param in form)
- req.params[param] = form[param];
+ req.query[param] = form[param];
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
- process.mixin(req.params, req.json);
+ process.mixin(req.query, req.json);
}
for (var i = 0; config.handlers[i]; ++i) {
var match = config.handlers[i][0](req.pathname);
if (match) {
req.match = match;
config.handlers[i][1](req, res);
break;
}
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
aac5c3b63e4e0f18b41f0c41cb62313229929a59
|
Node version v0.1.25-15-g4e16e38
|
diff --git a/README.md b/README.md
index fe15da3..282790e 100644
--- a/README.md
+++ b/README.md
@@ -1,17 +1,17 @@
Woses
=====
HTTP server for static and PHP files via [Node](http://nodejs.org/)
Project home is at [http://grumdrig.com/woses/].
Source code lives at [http://github.com/grumdrig/woses].
Usage
-----
`$ node woses.js`
-Tested with Node version 0.1.18.
+Tested with Node version v0.1.25-15-g4e16e38
diff --git a/doc/.woses-conf.js b/doc/.woses-conf.js
index d99e0f6..543e721 100644
--- a/doc/.woses-conf.js
+++ b/doc/.woses-conf.js
@@ -1,23 +1,23 @@
var sys = require("sys");
exports.mimetypes = {
gif: "image/gif"
}
exports.port = 8080;
//exports.logRequestHeaders = true;
function respondWithMarkdown(req, res) {
- sys.exec("Markdown.pl < " + req.uri.filename)
+ sys.exec("Markdown.pl < " + req.filename)
.addCallback(function (stdout, stderr) {
res.respond(stdout);})
.addErrback(function (code, stdout, stderr) {
res.status = 404;
res.respond("404: Mark my words. No such file.");
});
}
exports.handlers = [
[/\.(md|markdown)$/, respondWithMarkdown]
];
\ No newline at end of file
diff --git a/doc/test-rpc.js b/doc/test-rpc.js
index 2529089..63135e3 100644
--- a/doc/test-rpc.js
+++ b/doc/test-rpc.js
@@ -1,8 +1,8 @@
var sys = require("sys");
exports.fetch = function (request, response) {
response.header("content-type", "text/html");
//sys.p(repsonse.headers);
- response.body = "Got it. <pre>" + sys.inspect(request.uri.params);
+ response.body = "Got it. <pre>" + sys.inspect(request.params);
return response.respond();
}
diff --git a/woses.js b/woses.js
index fea5b72..643da50 100644
--- a/woses.js
+++ b/woses.js
@@ -1,240 +1,240 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
- http = require('http');
+ http = require('http'),
+ url = require('url');
function respondWithPhp(req, res) {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
- var params = [parp, req.uri.filename];
+ var params = [parp, req.filename];
for (var param in req.params)
params.push(escape(param) + "=" + escape(req.params[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
- params.push("REQUEST_URI=" + req.uri.full);
+ params.push("REQUEST_URI=" + req.url);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
"application/xml" : "text/html")
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
function respondWithJsRpc(req, res) {
// TODO: use conf file to distinguish client & server js
try {
- var script = require(req.uri.basename);
+ var script = require(req.basename);
// TODO: don't have fetch call respond - just set body
var len = script.fetch(req, res);
sys.puts(req.requestLine + " " + len);
} catch (e) {
res.status = 404
res.respond("404: In absentia. Or elsewhere.\n" +
sys.inspect(e));
}
}
function respondWithStatic(req, res) {
- var content_type = config.mimetypes[req.uri.ext] || "text/plain";
+ var content_type = config.mimetypes[req.ext] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
- var promise = posix.cat(req.uri.filename, res.encoding);
+ var promise = posix.cat(req.filename, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
- promise.addErrback(function() {
- sys.puts("Error 404: " + req.uri.filename);
+ promise.addErrback(function(data) {
+ sys.puts("Error 404: " + req.filename);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
var config = {
port: 8080,
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
},
handlers: [
[/\.php$/, respondWithPhp],
[/-rpc\.js$/, respondWithJsRpc],
[/$/, respondWithStatic]
]
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
require.paths.push(process.cwd());
try {
posix.stat(config.index).wait();
} catch (e) {
config.index = "index.php"
}
try {
var cf = require(".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
if (cf.handlers) {
config.handlers = cf.handlers.concat(config.handlers);
delete cf.handlers;
}
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
http.createServer(function(req, res) {
- req.requestLine = req.method + " " + req.uri.full +
- " HTTP/" + req.httpVersion;
+ req.requestLine = req.method + " " + req.url + " HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
- if (req.uri.path == '/')
- req.uri.path = "/" + config.index;
+ if (req.url == '/')
+ req.url = "/" + config.index;
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
var result = this.body ? this.body.length : 0;
this.encoding = this.encoding || 'utf8';
res.header('Content-Length', (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length));
this.sendBody(this.body, this.encoding);
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
- var uriparts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(req.uri.path);
+ req.query = req.query || {};
+ process.mixin(req, url.parse(req.url, true));
+ var uriparts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(req.pathname);
if (!uriparts) {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
- process.mixin(req.uri, {
- filename: uriparts[1],
- basename: uriparts[2],
- ext: uriparts[4]
- });
+ req.filename = uriparts[1];
+ req.basename = uriparts[2];
+ req.ext = uriparts[4];
// Exclude ".." in uri
- if (req.uri.path.indexOf('..') >= 0 || req.uri.filename.substr(1) == ".") {
+ if (req.pathname.indexOf('..') >= 0 || req.filename.substr(0,1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
function decodeForm(data) {
var result = {};
data
.split("&")
.map(function (assignment) { return assignment.split("=").map(
function (tok) { return decodeURIComponent(tok.replace(/\+/g, " "));})})
.forEach(function(pair) { result[pair[0]] = pair[1]; });
return result;
}
- req.params = req.uri.params;
+ req.params = req.query; // TODO: get rid of this redundancy
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var form = decodeForm(req.body);
for (var param in form)
req.params[param] = form[param];
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
process.mixin(req.params, req.json);
}
for (var i = 0; config.handlers[i]; ++i) {
- var match = config.handlers[i][0](req.uri.path);
+ var match = config.handlers[i][0](req.pathname);
if (match) {
- req.uri.match = match;
+ req.match = match;
config.handlers[i][1](req, res);
break;
}
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
adc956801269f798096f29744824fd314c0916b7
|
Bookkeeping
|
diff --git a/README.md b/README.md
index 412757d..fe15da3 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,17 @@
-woses
+Woses
=====
HTTP server for static and PHP files via [Node](http://nodejs.org/)
+Project home is at [http://grumdrig.com/woses/].
+
+Source code lives at [http://github.com/grumdrig/woses].
+
+
Usage
-----
`$ node woses.js`
+
+Tested with Node version 0.1.18.
|
grumdrig/woses
|
2e43c42406b2280de075570529864c67d5a64241
|
Make uri match available to handler
|
diff --git a/woses.js b/woses.js
index 3a67a42..fea5b72 100644
--- a/woses.js
+++ b/woses.js
@@ -1,238 +1,240 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http');
function respondWithPhp(req, res) {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
var params = [parp, req.uri.filename];
for (var param in req.params)
params.push(escape(param) + "=" + escape(req.params[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
"application/xml" : "text/html")
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
function respondWithJsRpc(req, res) {
// TODO: use conf file to distinguish client & server js
try {
var script = require(req.uri.basename);
// TODO: don't have fetch call respond - just set body
var len = script.fetch(req, res);
sys.puts(req.requestLine + " " + len);
} catch (e) {
res.status = 404
res.respond("404: In absentia. Or elsewhere.\n" +
sys.inspect(e));
}
}
function respondWithStatic(req, res) {
var content_type = config.mimetypes[req.uri.ext] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
var promise = posix.cat(req.uri.filename, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function() {
sys.puts("Error 404: " + req.uri.filename);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
var config = {
port: 8080,
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
},
handlers: [
[/\.php$/, respondWithPhp],
[/-rpc\.js$/, respondWithJsRpc],
[/$/, respondWithStatic]
]
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
require.paths.push(process.cwd());
try {
posix.stat(config.index).wait();
} catch (e) {
config.index = "index.php"
}
try {
var cf = require(".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
if (cf.handlers) {
config.handlers = cf.handlers.concat(config.handlers);
delete cf.handlers;
}
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
if (req.uri.path == '/')
req.uri.path = "/" + config.index;
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
var result = this.body ? this.body.length : 0;
this.encoding = this.encoding || 'utf8';
res.header('Content-Length', (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length));
this.sendBody(this.body, this.encoding);
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
var uriparts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(req.uri.path);
if (!uriparts) {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
process.mixin(req.uri, {
filename: uriparts[1],
basename: uriparts[2],
ext: uriparts[4]
});
// Exclude ".." in uri
if (req.uri.path.indexOf('..') >= 0 || req.uri.filename.substr(1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
function decodeForm(data) {
var result = {};
data
.split("&")
.map(function (assignment) { return assignment.split("=").map(
function (tok) { return decodeURIComponent(tok.replace(/\+/g, " "));})})
.forEach(function(pair) { result[pair[0]] = pair[1]; });
return result;
}
req.params = req.uri.params;
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var form = decodeForm(req.body);
for (var param in form)
req.params[param] = form[param];
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
process.mixin(req.params, req.json);
}
for (var i = 0; config.handlers[i]; ++i) {
- if (config.handlers[i][0](req.uri.path)) {
+ var match = config.handlers[i][0](req.uri.path);
+ if (match) {
+ req.uri.match = match;
config.handlers[i][1](req, res);
break;
}
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
79f399976b469123aa88b6e4cee122a4bbd4fbe3
|
Use configurable handler mechanism in test
|
diff --git a/doc/.woses-conf.js b/doc/.woses-conf.js
index dec54ec..d99e0f6 100644
--- a/doc/.woses-conf.js
+++ b/doc/.woses-conf.js
@@ -1,7 +1,23 @@
+var sys = require("sys");
+
exports.mimetypes = {
gif: "image/gif"
}
exports.port = 8080;
//exports.logRequestHeaders = true;
+
+function respondWithMarkdown(req, res) {
+ sys.exec("Markdown.pl < " + req.uri.filename)
+ .addCallback(function (stdout, stderr) {
+ res.respond(stdout);})
+ .addErrback(function (code, stdout, stderr) {
+ res.status = 404;
+ res.respond("404: Mark my words. No such file.");
+ });
+}
+
+exports.handlers = [
+ [/\.(md|markdown)$/, respondWithMarkdown]
+];
\ No newline at end of file
diff --git a/doc/README.md b/doc/README.md
deleted file mode 100644
index 412757d..0000000
--- a/doc/README.md
+++ /dev/null
@@ -1,10 +0,0 @@
-woses
-=====
-
-HTTP server for static and PHP files via [Node](http://nodejs.org/)
-
-Usage
------
-
-`$ node woses.js`
-
diff --git a/doc/test.html b/doc/test.html
index 7ee8f83..3006760 100644
--- a/doc/test.html
+++ b/doc/test.html
@@ -1,58 +1,58 @@
<head>
<title>Woses Test Page</title>
<link rel="stylesheet" href="style.css"/>
<script src="script.js"></script>
</head>
<body onLoad="unittest()">
<h1>Woses</h1>
<h2>Test Page</h2>
<img class=right src=wose.png>
<img class=right src=sceltictree.jpg>
<p>
<a href=index.html>HTML</a>
⚉
<a href=not-here.html>404</a>
<p>
-<a href=README.md>Markdown README</a>
+<a href=test.markdown>Markdown</a>
⚉
<a href=not-here.md>404</a>
<form action=test.php method=post>
<a href=test.php?one=param&two=potato>Test PHP</a>
⚉
<a href=not-here.php>404</a>
⚉
<input type=text name=box value=text>
<input type=submit>
</form>
<p>
<form action=test-rpc.js method=post>
<a href="test-rpc.js?this=that">Test JS RPC</a>
⚉
<a href=not-here-rpc.js>404</a>
⚉
<input type=text name=boxy value=words>
<input type=submit>
</form>
⚉
<button onclick="requestJson({a:5, b:10}, 'json-rpc.js', function(r) {feedback(JSON.stringify(r))})">Button?</button>
<p>
Missing image: <img src=not-here.jpg>
<br>
<br>
<br>
<p id=something>Test results:</p>
diff --git a/doc/test.markdown b/doc/test.markdown
new file mode 100644
index 0000000..7bb1158
--- /dev/null
+++ b/doc/test.markdown
@@ -0,0 +1,10 @@
+Markdown
+========
+
+Markdown.pl is expected to be in your system path.
+
+Fortunately
+-----------
+
+It seems to be.
+
diff --git a/woses.js b/woses.js
index 69f105f..3a67a42 100644
--- a/woses.js
+++ b/woses.js
@@ -1,250 +1,238 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http');
function respondWithPhp(req, res) {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
var params = [parp, req.uri.filename];
for (var param in req.params)
params.push(escape(param) + "=" + escape(req.params[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
"application/xml" : "text/html")
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
function respondWithJsRpc(req, res) {
// TODO: use conf file to distinguish client & server js
try {
var script = require(req.uri.basename);
// TODO: don't have fetch call respond - just set body
var len = script.fetch(req, res);
sys.puts(req.requestLine + " " + len);
} catch (e) {
res.status = 404
res.respond("404: In absentia. Or elsewhere.\n" +
sys.inspect(e));
}
}
-function respondWithMarkdown(req, res) {
- sys.exec("Markdown.pl < " + req.uri.filename)
- .addCallback(function (stdout, stderr) {
- res.respond(stdout);})
- .addErrback(function (code, stdout, stderr) {
- res.status = 404;
- res.respond("404: Mark my words. No such file.");
- });
-}
-
-
function respondWithStatic(req, res) {
var content_type = config.mimetypes[req.uri.ext] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
var promise = posix.cat(req.uri.filename, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function() {
sys.puts("Error 404: " + req.uri.filename);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
var config = {
port: 8080,
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
},
handlers: [
[/\.php$/, respondWithPhp],
[/-rpc\.js$/, respondWithJsRpc],
- [/\.md$/, respondWithMarkdown],
[/$/, respondWithStatic]
]
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
require.paths.push(process.cwd());
try {
posix.stat(config.index).wait();
} catch (e) {
config.index = "index.php"
}
try {
var cf = require(".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
if (cf.handlers) {
config.handlers = cf.handlers.concat(config.handlers);
delete cf.handlers;
}
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
if (req.uri.path == '/')
req.uri.path = "/" + config.index;
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
var result = this.body ? this.body.length : 0;
this.encoding = this.encoding || 'utf8';
res.header('Content-Length', (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length));
this.sendBody(this.body, this.encoding);
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
var uriparts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(req.uri.path);
if (!uriparts) {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
process.mixin(req.uri, {
filename: uriparts[1],
basename: uriparts[2],
ext: uriparts[4]
});
// Exclude ".." in uri
if (req.uri.path.indexOf('..') >= 0 || req.uri.filename.substr(1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
function decodeForm(data) {
var result = {};
data
.split("&")
.map(function (assignment) { return assignment.split("=").map(
function (tok) { return decodeURIComponent(tok.replace(/\+/g, " "));})})
.forEach(function(pair) { result[pair[0]] = pair[1]; });
return result;
}
req.params = req.uri.params;
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var form = decodeForm(req.body);
for (var param in form)
req.params[param] = form[param];
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
process.mixin(req.params, req.json);
}
for (var i = 0; config.handlers[i]; ++i) {
if (config.handlers[i][0](req.uri.path)) {
config.handlers[i][1](req, res);
break;
}
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
42566241285f3e69a4b683579f65c2cc837bfeea
|
Added a mechanism for configurable handlers
|
diff --git a/woses.js b/woses.js
index 0dfc2f9..69f105f 100644
--- a/woses.js
+++ b/woses.js
@@ -1,252 +1,250 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http');
-function parseUri(path) {
- var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(path);
- if (parts) {
- return {
- filename: parts[1],
- basename: parts[2],
- ext: parts[4]
- };
+function respondWithPhp(req, res) {
+ res.body = '';
+ var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
+ var params = [parp, req.uri.filename];
+ for (var param in req.params)
+ params.push(escape(param) + "=" + escape(req.params[param]));
+ params.push("-s");
+ params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
+ params.push("HTTP_HOST=" + req.headers['host']);
+ params.push("REQUEST_URI=" + req.uri.full);
+ var promise = process.createChildProcess("php", params);
+ promise.addListener("output", function (data) {
+ req.pause();
+ if (data != null) {
+ res.body += data;
+ } else {
+ res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
+ "application/xml" : "text/html")
+ sys.puts(req.requestLine + " (php) " + res.body.length);
+ if (res.body.match(/^404:/))
+ res.status = 404;
+ res.respond();
+ }
+ setTimeout(function(){req.resume();});
+ });
+ promise.addListener("error", function(content) {
+ if (content != null) {
+ sys.puts("STDERR (php): " + content);
+ //return res.respond('500: Sombody said something shocking.');
+ }
+ });
+}
+
+
+function respondWithJsRpc(req, res) {
+ // TODO: use conf file to distinguish client & server js
+ try {
+ var script = require(req.uri.basename);
+ // TODO: don't have fetch call respond - just set body
+ var len = script.fetch(req, res);
+ sys.puts(req.requestLine + " " + len);
+ } catch (e) {
+ res.status = 404
+ res.respond("404: In absentia. Or elsewhere.\n" +
+ sys.inspect(e));
}
}
+function respondWithMarkdown(req, res) {
+ sys.exec("Markdown.pl < " + req.uri.filename)
+ .addCallback(function (stdout, stderr) {
+ res.respond(stdout);})
+ .addErrback(function (code, stdout, stderr) {
+ res.status = 404;
+ res.respond("404: Mark my words. No such file.");
+ });
+}
+
+
+function respondWithStatic(req, res) {
+ var content_type = config.mimetypes[req.uri.ext] || "text/plain";
+ res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
+ var promise = posix.cat(req.uri.filename, res.encoding);
+ promise.addCallback(function(data) {
+ res.header('Content-Type', content_type);
+ sys.puts(req.requestLine + " " + data.length);
+ res.respond(data);
+ });
+ promise.addErrback(function() {
+ sys.puts("Error 404: " + req.uri.filename);
+ res.status = 404;
+ res.header('Content-Type', 'text/plain');
+ res.respond('404: I looked but did not find.');
+ });
+}
+
+
var config = {
port: 8080,
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
- }
+ },
+ handlers: [
+ [/\.php$/, respondWithPhp],
+ [/-rpc\.js$/, respondWithJsRpc],
+ [/\.md$/, respondWithMarkdown],
+ [/$/, respondWithStatic]
+ ]
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
require.paths.push(process.cwd());
try {
posix.stat(config.index).wait();
} catch (e) {
config.index = "index.php"
}
try {
var cf = require(".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
+ if (cf.handlers) {
+ config.handlers = cf.handlers.concat(config.handlers);
+ delete cf.handlers;
+ }
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
if (req.uri.path == '/')
req.uri.path = "/" + config.index;
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
var result = this.body ? this.body.length : 0;
this.encoding = this.encoding || 'utf8';
res.header('Content-Length', (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length));
this.sendBody(this.body, this.encoding);
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
- var uri = parseUri(req.uri.path);
- if (!uri) {
+ var uriparts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(req.uri.path);
+ if (!uriparts) {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
+ process.mixin(req.uri, {
+ filename: uriparts[1],
+ basename: uriparts[2],
+ ext: uriparts[4]
+ });
// Exclude ".." in uri
- if (req.uri.path.indexOf('..') >= 0 || uri.filename.substr(1) == ".") {
+ if (req.uri.path.indexOf('..') >= 0 || req.uri.filename.substr(1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
- function respondWithStatic() {
- var content_type = config.mimetypes[uri.ext] || "text/plain";
- res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
- var promise = posix.cat(uri.filename, res.encoding);
- promise.addCallback(function(data) {
- res.header('Content-Type', content_type);
- sys.puts(req.requestLine + " " + data.length);
- res.respond(data);
- });
- promise.addErrback(function() {
- sys.puts("Error 404: " + uri.filename);
- res.status = 404;
- res.header('Content-Type', 'text/plain');
- res.respond('404: I looked but did not find.');
- });
- }
-
function decodeForm(data) {
var result = {};
data
.split("&")
.map(function (assignment) { return assignment.split("=").map(
function (tok) { return decodeURIComponent(tok.replace(/\+/g, " "));})})
.forEach(function(pair) { result[pair[0]] = pair[1]; });
return result;
}
- function respondWithPhp() {
- res.body = '';
- var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
- var params = [parp, uri.filename];
- for (var param in req.params)
- params.push(escape(param) + "=" + escape(req.params[param]));
- params.push("-s");
- params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
- params.push("HTTP_HOST=" + req.headers['host']);
- params.push("REQUEST_URI=" + req.uri.full);
- var promise = process.createChildProcess("php", params);
- promise.addListener("output", function (data) {
- req.pause();
- if (data != null) {
- res.body += data;
- } else {
- res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
- "application/xml" : "text/html")
- sys.puts(req.requestLine + " (php) " + res.body.length);
- if (res.body.match(/^404:/))
- res.status = 404;
- res.respond();
- }
- setTimeout(function(){req.resume();});
- });
- promise.addListener("error", function(content) {
- if (content != null) {
- sys.puts("STDERR (php): " + content);
- //return res.respond('500: Sombody said something shocking.');
- }
- });
- }
-
-
- function respondWithJsRpc() {
- // TODO: use conf file to distinguish client & server js
- try {
- var script = require(uri.basename);
- // TODO: don't have fetch call respond - just set body
- var len = script.fetch(req, res);
- sys.puts(req.requestLine + " " + len);
- } catch (e) {
- res.status = 404
- res.respond("404: In absentia. Or elsewhere.\n" +
- sys.inspect(e));
- }
- }
-
- function respondWithMarkdown() {
- sys.exec("Markdown.pl < " + uri.filename)
- .addCallback(function (stdout, stderr) {
- res.respond(stdout);})
- .addErrback(function (code, stdout, stderr) {
- res.status = 404;
- res.respond("404: Mark my words. No such file.");
- });
- }
-
req.params = req.uri.params;
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var form = decodeForm(req.body);
for (var param in form)
req.params[param] = form[param];
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
process.mixin(req.params, req.json);
}
- handlers = [
- [/\.php$/, respondWithPhp],
- [/-rpc\.js$/, respondWithJsRpc],
- [/\.md$/, respondWithMarkdown],
- [/$/, respondWithStatic]
- ];
-
-
- for (var i = 0; handlers[i]; ++i) {
- if (handlers[i][0](req.uri.path)) {
- handlers[i][1]();
+ for (var i = 0; config.handlers[i]; ++i) {
+ if (config.handlers[i][0](req.uri.path)) {
+ config.handlers[i][1](req, res);
break;
}
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
faf7a933adb2fb80de10e75cbb90b3cca51a2f4b
|
Use matching to determine handler
|
diff --git a/doc/README.md b/doc/README.md
new file mode 100644
index 0000000..412757d
--- /dev/null
+++ b/doc/README.md
@@ -0,0 +1,10 @@
+woses
+=====
+
+HTTP server for static and PHP files via [Node](http://nodejs.org/)
+
+Usage
+-----
+
+`$ node woses.js`
+
diff --git a/doc/index.html b/doc/index.html
index b266cfe..14dae87 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,124 +1,125 @@
<head>
- <title>Woses Documentation/Test</title>
+ <title>Woses Webserver</title>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<h1>
<!--☶ ☁ ⎈ 𐂷 ☃-->
Woses <span class=right style=color:black>⚉</span>
</h1>
<p>
Woses is a <a href=http://nodejs.org/>Node</a>-based webserver with
support for <a href=http://php.net/>PHP</a> templating.
<p>
Additionally it includes a mechanism for server-side JavaScript RPC.
<p>
The home page for Woses is
<a href=http://grumdrig.com/woses/>http://grumdrig.com/woses/</a>. The
code lives at
<a href=http://github.com/grumdrig/woses>http://github.com/grumdrig/woses</a>.
<h2>Usage</h2>
<pre>
$ node woses.js DOCUMENT_ROOT
</pre>
will run the HTTP server against the content in DOCUMENT_ROOT. For example,
<pre>
$ node woses.js doc
</pre>
<p>
will serve this documentation on <a href=http://localhost:8080/>port
8080</a>.
<p>
Included also is the script <code>serverloop.py</code> which runs the
server in a loop, polling for changes to the configuration
file, <code>woses.js</code>, or files listed on the command line.
Changes or <code>^C</code> restart the server. This is most useful for
running the server during development. Usage is:
<pre>
$ ./serverloop.py DOCUMENT_ROOT [OTHER_FILES...]
</pre>
<h2> Configuration </h2>
<p>
Woses can be configured by placing a file
called <code>.woses-conf.js</code> in the document root. This file may
export the following settings:
<ul>
<li> <code>port</code>: A port other than the default 8080 on which to
serve.
<li> <code>index</code>: Name of a directory index page to use for
URI's which point to a folder, rather than the
default, <code>index.html</code> falling back
to <code>index.php</code>.
<li> <code>mimetypes</code>: A map from file extensions to MIME types
for serving content.
</ul>
Here is an example configuration file:
<pre>
exports.port = 80;
exports.index = "home.html";
exports.mimetypes = {
'gif': 'image/gif',
'readme': 'text/plain'
}
</pre>
<h2> PHP </h2>
<p>
Woses will serve PHP scripts through the mechanism of the PHP
command-line interface; thus the <code>php</code> command must be available for
woses to serve PHP scripts.
<p>
The big caveat of PHP support is that, within PHP code, calls to
`header()' have no effect.
<h2> JS RPC </h2>
<p>
Requests for filenames ending in <code>-rpc.js</code> (some more
sensible mechanism to distinguish is a TODO item) are loaded as
modules and the HTTP request is proxied through their
exported <code>fetch</code> function, with signature:
<pre>
exports.fetch = function(request, response) {
// ...
response.body = ...;
return response.respond();
};
</pre>
<h2> JS Templating </h2>
<p>
Templating in the style of EJS / Resig's micro-templating is planned,
but not implemented
<h2> Security </h2>
<p>
URLs with ".." in them are disallowed, but security is probably poor
at the moment. That is, an attacker may be able to pwn your system if
you are running this on a public server.
<h2> Tests </h2>
-<a href=test.html>Test page.</a>
+If this page is served by Woses itself,
+<a href=test.html>this is a test page.</a>
diff --git a/template.js b/template.js
index 952ad18..aeb7e32 100644
--- a/template.js
+++ b/template.js
@@ -1,99 +1,99 @@
// Templates with embedded JavaScript
//
// Some credit is due to John Resig:
// http://ejohn.org/blog/javascript-micro-templating/
// and the templating follows that syntax and that of EJS:
// http://embeddedjs.com/
// Unlike the former, however, this implementation preserved newlines, etc.
//
// The template syntax is literal text, in which may be embedded:
// - Arbitrary code sections between <% ... %> tags, and
// - Evaluated expressions between <%= ... %> tags.
// The code sections may use `print(x)` to add output as well/
//
// Example template:
//
// <ul class="<%= className %>"> <% for (var i=0; item[i]; ++i) { %>
// <li> <% print(item[i]);
// } %>
// </ul>
//
// would produce, with data { className:"bold", item:["One", "Two"]} :
//
// <ul class="bold">
// <li> One
// <li> Two
// </ul>
//
var template = exports.template = function(template, data) {
// TODO cache
var body = [
"var $$p = [];",
"function print() {$$p.push.apply($$p, arguments);}",
"with($$context){",
];
template.split("%>").forEach(function (part) {
var parts = part.split("<%");
body.push("print('" + parts[0]
.split("\\").join("\\\\")
.split("\n").join("\\n")
.split("\r").join("\\r")
.split("'").join("\\'") +
"');");
if (parts.length > 1) {
if (parts[1].substr(0,1) == '=')
body.push("print(" + parts[1].substr(1) + ");");
else
body.push(parts[1]);
}
});
body.push("}");
body.push("return $$p.join('');");
var generator = new Function("$$context", body.join('\n'));
return data ? generator(data) : generator; // Curry
}
function test() {
var sys = require("sys");
var t0 = template(
'<ul class="<%= className %>"> \n' +
' <% for (var i=0; item[i]; ++i) { %> \n' +
' <li> <% print(item[i]); \n' +
' } %> \n' +
'</ul>');
sys.print(t0({ className:"bold", item:["One", "Two"]}));
var t1 = template(
'<script type="text/html" id="item_tmpl">\n'+
' <div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>">\n'+
' <div class="grid_1 alpha right">\n'+
' <img class="righted" src="<%=profile_image_url%>"/>\n'+
' </div>\n'+
' <div class="grid_6 omega contents">\n'+
' <p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>\n'+
' </div>\n'+
' </div>\n'+
'</script>\n'
);
sys.print('\n\n');
sys.print(t1({id:"IDENTIFIER", i:5, profile_image_url:"URL", from_user:"USER", text:"TEXT"}));
var t2 = template(
'<script type="text/html" id="user_tmpl">\n'+
' <% for ( var i = 0; i < users.length; i++ ) { %>\n'+
' <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>\n'+
' <% } %>\n'+
'</script>\n'
);
sys.print('\n\n');
sys.print(t2({users:[{url:'URL1',name:'NAME1'}, {url:'URL2',name:'NAME2'}]}));
}
-test();
+//test();
diff --git a/woses.js b/woses.js
index 2c3ac79..0dfc2f9 100644
--- a/woses.js
+++ b/woses.js
@@ -1,241 +1,252 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http');
function parseUri(path) {
var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(path);
if (parts) {
return {
filename: parts[1],
basename: parts[2],
ext: parts[4]
};
}
}
var config = {
port: 8080,
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
}
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
require.paths.push(process.cwd());
try {
posix.stat(config.index).wait();
} catch (e) {
config.index = "index.php"
}
try {
var cf = require(".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
if (req.uri.path == '/')
req.uri.path = "/" + config.index;
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
var result = this.body ? this.body.length : 0;
this.encoding = this.encoding || 'utf8';
res.header('Content-Length', (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length));
this.sendBody(this.body, this.encoding);
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
var uri = parseUri(req.uri.path);
if (!uri) {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
// Exclude ".." in uri
if (req.uri.path.indexOf('..') >= 0 || uri.filename.substr(1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
function respondWithStatic() {
var content_type = config.mimetypes[uri.ext] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
var promise = posix.cat(uri.filename, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function() {
sys.puts("Error 404: " + uri.filename);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
function decodeForm(data) {
var result = {};
data
.split("&")
.map(function (assignment) { return assignment.split("=").map(
function (tok) { return decodeURIComponent(tok.replace(/\+/g, " "));})})
.forEach(function(pair) { result[pair[0]] = pair[1]; });
return result;
}
function respondWithPhp() {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
var params = [parp, uri.filename];
for (var param in req.params)
params.push(escape(param) + "=" + escape(req.params[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
"application/xml" : "text/html")
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
+
+
+ function respondWithJsRpc() {
+ // TODO: use conf file to distinguish client & server js
+ try {
+ var script = require(uri.basename);
+ // TODO: don't have fetch call respond - just set body
+ var len = script.fetch(req, res);
+ sys.puts(req.requestLine + " " + len);
+ } catch (e) {
+ res.status = 404
+ res.respond("404: In absentia. Or elsewhere.\n" +
+ sys.inspect(e));
+ }
+ }
+
+ function respondWithMarkdown() {
+ sys.exec("Markdown.pl < " + uri.filename)
+ .addCallback(function (stdout, stderr) {
+ res.respond(stdout);})
+ .addErrback(function (code, stdout, stderr) {
+ res.status = 404;
+ res.respond("404: Mark my words. No such file.");
+ });
+ }
req.params = req.uri.params;
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var form = decodeForm(req.body);
for (var param in form)
req.params[param] = form[param];
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
process.mixin(req.params, req.json);
}
+
+ handlers = [
+ [/\.php$/, respondWithPhp],
+ [/-rpc\.js$/, respondWithJsRpc],
+ [/\.md$/, respondWithMarkdown],
+ [/$/, respondWithStatic]
+ ];
- if (uri.ext == "php") {
- respondWithPhp();
-
- } else if (uri.filename.substr(-7) == "-rpc.js") {
- // TODO: use conf file to distinguish client & server js
- try {
- var script = require(uri.basename);
- // TODO: don't have fetch call respond - just set body
- var len = script.fetch(req, res);
- sys.puts(req.requestLine + " " + len);
- } catch (e) {
- res.status = 404
- res.respond("404: In absentia. Or elsewhere.\n" +
- sys.inspect(e));
- }
- } else if (uri.ext == "md") {
- sys.exec("Markdown.pl < " + uri.filename)
- .addCallback(function (stdout, stderr) {
- res.respond(stdout);})
- .addErrback(function (code, stdout, stderr) {
- res.status = 404;
- res.respond("404: Mark my words. No such file.");
- });
-
- } else {
- respondWithStatic();
+ for (var i = 0; handlers[i]; ++i) {
+ if (handlers[i][0](req.uri.path)) {
+ handlers[i][1]();
+ break;
+ }
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
5e51d263f153d6903dad93c361af72bdbf222e48
|
Cleanup and documentation.
|
diff --git a/template.js b/template.js
index 83cd15f..952ad18 100644
--- a/template.js
+++ b/template.js
@@ -1,98 +1,99 @@
-/*
-This is resig's templating function, here for reference:
-
+// Templates with embedded JavaScript
+//
+// Some credit is due to John Resig:
// http://ejohn.org/blog/javascript-micro-templating/
-
-(function(){
- var cache = {};
-
- this.tmpl = function tmpl(str, data){
- // Figure out if we're getting a template, or if we need to
- // load the template - and be sure to cache the result.
- var fn = cache[str] = cache[str] ||
-
- // Generate a reusable function that will serve as a template
- // generator (and which will be cached).
- new Function("obj",
- "var p=[],print=function(){p.push.apply(p,arguments);};" +
-
- // Introduce the data as local variables using with(){}
- "with(obj){p.push('" +
- // Convert the template into JS
- str.replace(/[\r\t\n]/g, " ")
- .split("<%").join("\t")
- .replace(/((^|%>)[^\t]*)'/g, "$1\r")
- .replace(/\t=(.*?)%>/g, "',$1,'")
- .split("\t").join("');")
- .split("%>").join("p.push('")
- .split("\r").join("\\'") +
- "');}return p.join('');");
-
- // Provide some basic currying
- return data ? fn(data) : fn;
- };
-})();
-*/
+// and the templating follows that syntax and that of EJS:
+// http://embeddedjs.com/
+// Unlike the former, however, this implementation preserved newlines, etc.
+//
+// The template syntax is literal text, in which may be embedded:
+// - Arbitrary code sections between <% ... %> tags, and
+// - Evaluated expressions between <%= ... %> tags.
+// The code sections may use `print(x)` to add output as well/
+//
+// Example template:
+//
+// <ul class="<%= className %>"> <% for (var i=0; item[i]; ++i) { %>
+// <li> <% print(item[i]);
+// } %>
+// </ul>
+//
+// would produce, with data { className:"bold", item:["One", "Two"]} :
+//
+// <ul class="bold">
+// <li> One
+// <li> Two
+// </ul>
+//
-function compile(template, data) {
+var template = exports.template = function(template, data) {
// TODO cache
var body = [
"var $$p = [];",
"function print() {$$p.push.apply($$p, arguments);}",
"with($$context){",
];
template.split("%>").forEach(function (part) {
var parts = part.split("<%");
body.push("print('" + parts[0]
.split("\\").join("\\\\")
.split("\n").join("\\n")
.split("\r").join("\\r")
.split("'").join("\\'") +
"');");
if (parts.length > 1) {
if (parts[1].substr(0,1) == '=')
body.push("print(" + parts[1].substr(1) + ");");
else
body.push(parts[1]);
}
});
body.push("}");
body.push("return $$p.join('');");
var generator = new Function("$$context", body.join('\n'));
return data ? generator(data) : generator; // Curry
}
function test() {
var sys = require("sys");
+
+ var t0 = template(
+ '<ul class="<%= className %>"> \n' +
+ ' <% for (var i=0; item[i]; ++i) { %> \n' +
+ ' <li> <% print(item[i]); \n' +
+ ' } %> \n' +
+ '</ul>');
+
+ sys.print(t0({ className:"bold", item:["One", "Two"]}));
- var t1 = compile(
+ var t1 = template(
'<script type="text/html" id="item_tmpl">\n'+
' <div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>">\n'+
' <div class="grid_1 alpha right">\n'+
' <img class="righted" src="<%=profile_image_url%>"/>\n'+
' </div>\n'+
' <div class="grid_6 omega contents">\n'+
' <p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>\n'+
' </div>\n'+
' </div>\n'+
'</script>\n'
);
sys.print('\n\n');
sys.print(t1({id:"IDENTIFIER", i:5, profile_image_url:"URL", from_user:"USER", text:"TEXT"}));
- var t2 = compile(
+ var t2 = template(
'<script type="text/html" id="user_tmpl">\n'+
' <% for ( var i = 0; i < users.length; i++ ) { %>\n'+
' <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>\n'+
' <% } %>\n'+
'</script>\n'
);
sys.print('\n\n');
sys.print(t2({users:[{url:'URL1',name:'NAME1'}, {url:'URL2',name:'NAME2'}]}));
}
test();
|
grumdrig/woses
|
fa4bacb6f7327b1ae96c7abfac27207d788148bb
|
Templating function beginnings. A bit rough still.
|
diff --git a/template.js b/template.js
new file mode 100644
index 0000000..83cd15f
--- /dev/null
+++ b/template.js
@@ -0,0 +1,98 @@
+/*
+This is resig's templating function, here for reference:
+
+// http://ejohn.org/blog/javascript-micro-templating/
+
+(function(){
+ var cache = {};
+
+ this.tmpl = function tmpl(str, data){
+ // Figure out if we're getting a template, or if we need to
+ // load the template - and be sure to cache the result.
+ var fn = cache[str] = cache[str] ||
+
+ // Generate a reusable function that will serve as a template
+ // generator (and which will be cached).
+ new Function("obj",
+ "var p=[],print=function(){p.push.apply(p,arguments);};" +
+
+ // Introduce the data as local variables using with(){}
+ "with(obj){p.push('" +
+ // Convert the template into JS
+ str.replace(/[\r\t\n]/g, " ")
+ .split("<%").join("\t")
+ .replace(/((^|%>)[^\t]*)'/g, "$1\r")
+ .replace(/\t=(.*?)%>/g, "',$1,'")
+ .split("\t").join("');")
+ .split("%>").join("p.push('")
+ .split("\r").join("\\'") +
+ "');}return p.join('');");
+
+ // Provide some basic currying
+ return data ? fn(data) : fn;
+ };
+})();
+*/
+
+
+function compile(template, data) {
+ // TODO cache
+ var body = [
+ "var $$p = [];",
+ "function print() {$$p.push.apply($$p, arguments);}",
+ "with($$context){",
+ ];
+ template.split("%>").forEach(function (part) {
+ var parts = part.split("<%");
+ body.push("print('" + parts[0]
+ .split("\\").join("\\\\")
+ .split("\n").join("\\n")
+ .split("\r").join("\\r")
+ .split("'").join("\\'") +
+ "');");
+ if (parts.length > 1) {
+ if (parts[1].substr(0,1) == '=')
+ body.push("print(" + parts[1].substr(1) + ");");
+ else
+ body.push(parts[1]);
+ }
+ });
+ body.push("}");
+ body.push("return $$p.join('');");
+ var generator = new Function("$$context", body.join('\n'));
+ return data ? generator(data) : generator; // Curry
+}
+
+
+function test() {
+ var sys = require("sys");
+
+ var t1 = compile(
+ '<script type="text/html" id="item_tmpl">\n'+
+ ' <div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>">\n'+
+ ' <div class="grid_1 alpha right">\n'+
+ ' <img class="righted" src="<%=profile_image_url%>"/>\n'+
+ ' </div>\n'+
+ ' <div class="grid_6 omega contents">\n'+
+ ' <p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>\n'+
+ ' </div>\n'+
+ ' </div>\n'+
+ '</script>\n'
+ );
+
+ sys.print('\n\n');
+ sys.print(t1({id:"IDENTIFIER", i:5, profile_image_url:"URL", from_user:"USER", text:"TEXT"}));
+
+ var t2 = compile(
+ '<script type="text/html" id="user_tmpl">\n'+
+ ' <% for ( var i = 0; i < users.length; i++ ) { %>\n'+
+ ' <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>\n'+
+ ' <% } %>\n'+
+ '</script>\n'
+ );
+
+ sys.print('\n\n');
+ sys.print(t2({users:[{url:'URL1',name:'NAME1'}, {url:'URL2',name:'NAME2'}]}));
+}
+
+test();
|
grumdrig/woses
|
4bf7747e30e3b5ccb942d18cad2d945c8496cd18
|
Documentation improvements
|
diff --git a/doc/index.html b/doc/index.html
index 63da3c9..b266cfe 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,92 +1,124 @@
<head>
<title>Woses Documentation/Test</title>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<h1>
<!--☶ ☁ ⎈ 𐂷 ☃-->
Woses <span class=right style=color:black>⚉</span>
</h1>
<p>
Woses is a <a href=http://nodejs.org/>Node</a>-based webserver with
support for <a href=http://php.net/>PHP</a> templating.
<p>
Additionally it includes a mechanism for server-side JavaScript RPC.
<p>
The home page for Woses is
<a href=http://grumdrig.com/woses/>http://grumdrig.com/woses/</a>. The
code lives at
-<a href=http://bitbucket.com/grumdrig/woses>http://bitbucket.com/grumdrig/woses</a>.
+<a href=http://github.com/grumdrig/woses>http://github.com/grumdrig/woses</a>.
<h2>Usage</h2>
<pre>
$ node woses.js DOCUMENT_ROOT
</pre>
will run the HTTP server against the content in DOCUMENT_ROOT. For example,
<pre>
$ node woses.js doc
</pre>
<p>
will serve this documentation on <a href=http://localhost:8080/>port
8080</a>.
+<p>
+Included also is the script <code>serverloop.py</code> which runs the
+server in a loop, polling for changes to the configuration
+file, <code>woses.js</code>, or files listed on the command line.
+Changes or <code>^C</code> restart the server. This is most useful for
+running the server during development. Usage is:
+
+<pre>
+$ ./serverloop.py DOCUMENT_ROOT [OTHER_FILES...]
+</pre>
+
<h2> Configuration </h2>
<p>
Woses can be configured by placing a file
called <code>.woses-conf.js</code> in the document root. This file may
export the following settings:
<ul>
<li> <code>port</code>: A port other than the default 8080 on which to
serve.
<li> <code>index</code>: Name of a directory index page to use for
URI's which point to a folder, rather than the
default, <code>index.html</code> falling back
to <code>index.php</code>.
<li> <code>mimetypes</code>: A map from file extensions to MIME types
for serving content.
</ul>
Here is an example configuration file:
<pre>
exports.port = 80;
exports.index = "home.html";
exports.mimetypes = {
'gif': 'image/gif',
'readme': 'text/plain'
}
</pre>
<h2> PHP </h2>
<p>
Woses will serve PHP scripts through the mechanism of the PHP
command-line interface; thus the <code>php</code> command must be available for
woses to serve PHP scripts.
<p>
The big caveat of PHP support is that, within PHP code, calls to
`header()' have no effect.
<h2> JS RPC </h2>
-Javascript modules.
+<p>
+Requests for filenames ending in <code>-rpc.js</code> (some more
+sensible mechanism to distinguish is a TODO item) are loaded as
+modules and the HTTP request is proxied through their
+exported <code>fetch</code> function, with signature:
+
+<pre>
+exports.fetch = function(request, response) {
+ // ...
+ response.body = ...;
+ return response.respond();
+};
+</pre>
<h2> JS Templating </h2>
+<p>
+Templating in the style of EJS / Resig's micro-templating is planned,
+but not implemented
+
<h2> Security </h2>
+<p>
+URLs with ".." in them are disallowed, but security is probably poor
+at the moment. That is, an attacker may be able to pwn your system if
+you are running this on a public server.
+
<h2> Tests </h2>
<a href=test.html>Test page.</a>
diff --git a/serverloop.py b/serverloop.py
index ba2928a..afa13df 100755
--- a/serverloop.py
+++ b/serverloop.py
@@ -1,63 +1,63 @@
#!/usr/bin/python
# Copyright (c) 2009, Eric Fredricksen <[email protected]>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
""" Run the server named herein or on command line, using node.
Whenever it changes, kill and restart. (See http://nodejs.org/)
This is useful during editing and testing of the server."""
import os, sys, time, signal
root = (sys.argv[1:] or ['.'])[0]
-filenames = ["woses.js"];
+filenames = ["woses.js"] + sys.argv[2:];
conf = os.path.join(root, ".woses-conf.js");
if os.path.exists(conf): filenames.append(conf);
def restart(pid):
if pid:
os.kill(pid, signal.SIGTERM)
pid = os.spawnlp(os.P_NOWAIT, "node", "node", "woses.js", root);
print "Started", pid
return pid
os.system("killall -v node");
pid = None
mtime = []
while True:
m = [os.stat(filename).st_mtime for filename in filenames]
if mtime != m:
pid = restart(pid)
mtime = m
else:
try:
os.kill(pid, 0)
except:
pid = restart(pid)
try:
time.sleep(1)
except KeyboardInterrupt:
print "\nKilling", pid, "^C again to quit"
if pid:
os.kill(pid, signal.SIGTERM)
pid = None
try:
time.sleep(1)
except KeyboardInterrupt:
print
break
|
grumdrig/woses
|
dd514dfe1db3002f329fbca9575c98f31b29c8b1
|
Separate tests from documentation
|
diff --git a/doc/index.html b/doc/index.html
index 2c44d51..63da3c9 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,137 +1,92 @@
<head>
<title>Woses Documentation/Test</title>
<link rel="stylesheet" href="style.css"/>
- <script src="script.js"></script>
</head>
-<body onLoad="unittest()">
+<body>
<h1>
<!--☶ ☁ ⎈ 𐂷 ☃-->
Woses <span class=right style=color:black>⚉</span>
</h1>
<p>
Woses is a <a href=http://nodejs.org/>Node</a>-based webserver with
support for <a href=http://php.net/>PHP</a> templating.
<p>
Additionally it includes a mechanism for server-side JavaScript RPC.
<p>
The home page for Woses is
<a href=http://grumdrig.com/woses/>http://grumdrig.com/woses/</a>. The
code lives at
<a href=http://bitbucket.com/grumdrig/woses>http://bitbucket.com/grumdrig/woses</a>.
<h2>Usage</h2>
<pre>
$ node woses.js DOCUMENT_ROOT
</pre>
will run the HTTP server against the content in DOCUMENT_ROOT. For example,
<pre>
$ node woses.js doc
</pre>
<p>
will serve this documentation on <a href=http://localhost:8080/>port
8080</a>.
<h2> Configuration </h2>
<p>
Woses can be configured by placing a file
called <code>.woses-conf.js</code> in the document root. This file may
export the following settings:
<ul>
<li> <code>port</code>: A port other than the default 8080 on which to
serve.
<li> <code>index</code>: Name of a directory index page to use for
URI's which point to a folder, rather than the
default, <code>index.html</code> falling back
to <code>index.php</code>.
<li> <code>mimetypes</code>: A map from file extensions to MIME types
for serving content.
</ul>
Here is an example configuration file:
<pre>
exports.port = 80;
exports.index = "home.html";
exports.mimetypes = {
'gif': 'image/gif',
'readme': 'text/plain'
}
</pre>
<h2> PHP </h2>
<p>
Woses will serve PHP scripts through the mechanism of the PHP
command-line interface; thus the <code>php</code> command must be available for
woses to serve PHP scripts.
<p>
The big caveat of PHP support is that, within PHP code, calls to
`header()' have no effect.
<h2> JS RPC </h2>
Javascript modules.
<h2> JS Templating </h2>
<h2> Security </h2>
<h2> Tests </h2>
-<img class=right src=wose.png>
-<img class=right src=sceltictree.jpg>
-
-<p>
-
-<a href=index.html>HTML</a>
-⚉
-<a href=not-here.html>404</a>
-
-<p>
-
-<a href=README.md>Markdown README</a>
-⚉
-<a href=not-here.md>404</a>
-
-<form action=test.php method=post>
-<a href=test.php?one=param&two=potato>Test PHP</a>
-⚉
-<a href=not-here.php>404</a>
-⚉
- <input type=text name=box value=text>
- <input type=submit>
-</form>
-
-<p>
-<form action=test-rpc.js method=post>
-<a href="test-rpc.js?this=that">Test JS RPC</a>
-⚉
-<a href=not-here-rpc.js>404</a>
-⚉
- <input type=text name=boxy value=words>
- <input type=submit>
-</form>
-⚉
-<button onclick="requestJson({a:5, b:10}, 'json-rpc.js', function(r) {feedback(JSON.stringify(r))})">Button?</button>
-
-<p>
-
-Missing image: <img src=not-here.jpg>
-
-<br>
-<br>
-<br>
-
-<p id=something>Test results:</p>
+<a href=test.html>Test page.</a>
diff --git a/doc/test.html b/doc/test.html
new file mode 100644
index 0000000..7ee8f83
--- /dev/null
+++ b/doc/test.html
@@ -0,0 +1,58 @@
+<head>
+ <title>Woses Test Page</title>
+ <link rel="stylesheet" href="style.css"/>
+ <script src="script.js"></script>
+</head>
+
+<body onLoad="unittest()">
+
+
+<h1>Woses</h1>
+
+<h2>Test Page</h2>
+
+<img class=right src=wose.png>
+<img class=right src=sceltictree.jpg>
+
+<p>
+
+<a href=index.html>HTML</a>
+⚉
+<a href=not-here.html>404</a>
+
+<p>
+
+<a href=README.md>Markdown README</a>
+⚉
+<a href=not-here.md>404</a>
+
+<form action=test.php method=post>
+<a href=test.php?one=param&two=potato>Test PHP</a>
+⚉
+<a href=not-here.php>404</a>
+⚉
+ <input type=text name=box value=text>
+ <input type=submit>
+</form>
+
+<p>
+<form action=test-rpc.js method=post>
+<a href="test-rpc.js?this=that">Test JS RPC</a>
+⚉
+<a href=not-here-rpc.js>404</a>
+⚉
+ <input type=text name=boxy value=words>
+ <input type=submit>
+</form>
+⚉
+<button onclick="requestJson({a:5, b:10}, 'json-rpc.js', function(r) {feedback(JSON.stringify(r))})">Button?</button>
+
+<p>
+
+Missing image: <img src=not-here.jpg>
+
+<br>
+<br>
+<br>
+
+<p id=something>Test results:</p>
|
grumdrig/woses
|
3e0eeff70826509779aa504b3c88ef0f8a863972
|
Use simpler, good enough, form arg parsing
|
diff --git a/woses.js b/woses.js
index cdaad52..2c3ac79 100644
--- a/woses.js
+++ b/woses.js
@@ -1,232 +1,241 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
- http = require('http'),
- wwwforms = require('./www-forms');
+ http = require('http');
function parseUri(path) {
var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(path);
if (parts) {
return {
filename: parts[1],
basename: parts[2],
ext: parts[4]
};
}
}
var config = {
port: 8080,
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
}
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
require.paths.push(process.cwd());
try {
posix.stat(config.index).wait();
} catch (e) {
config.index = "index.php"
}
try {
var cf = require(".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
if (req.uri.path == '/')
req.uri.path = "/" + config.index;
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
var result = this.body ? this.body.length : 0;
this.encoding = this.encoding || 'utf8';
res.header('Content-Length', (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length));
this.sendBody(this.body, this.encoding);
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
var uri = parseUri(req.uri.path);
if (!uri) {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
// Exclude ".." in uri
if (req.uri.path.indexOf('..') >= 0 || uri.filename.substr(1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
function respondWithStatic() {
var content_type = config.mimetypes[uri.ext] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
var promise = posix.cat(uri.filename, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function() {
sys.puts("Error 404: " + uri.filename);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
+ function decodeForm(data) {
+ var result = {};
+ data
+ .split("&")
+ .map(function (assignment) { return assignment.split("=").map(
+ function (tok) { return decodeURIComponent(tok.replace(/\+/g, " "));})})
+ .forEach(function(pair) { result[pair[0]] = pair[1]; });
+ return result;
+ }
+
function respondWithPhp() {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
var params = [parp, uri.filename];
for (var param in req.params)
params.push(escape(param) + "=" + escape(req.params[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
"application/xml" : "text/html")
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
req.params = req.uri.params;
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
- var form = wwwforms.decodeForm(req.body);
+ var form = decodeForm(req.body);
for (var param in form)
req.params[param] = form[param];
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
process.mixin(req.params, req.json);
}
if (uri.ext == "php") {
respondWithPhp();
} else if (uri.filename.substr(-7) == "-rpc.js") {
// TODO: use conf file to distinguish client & server js
try {
var script = require(uri.basename);
// TODO: don't have fetch call respond - just set body
var len = script.fetch(req, res);
sys.puts(req.requestLine + " " + len);
} catch (e) {
res.status = 404
res.respond("404: In absentia. Or elsewhere.\n" +
sys.inspect(e));
}
} else if (uri.ext == "md") {
sys.exec("Markdown.pl < " + uri.filename)
.addCallback(function (stdout, stderr) {
res.respond(stdout);})
.addErrback(function (code, stdout, stderr) {
res.status = 404;
res.respond("404: Mark my words. No such file.");
});
} else {
respondWithStatic();
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
diff --git a/www-forms.js b/www-forms.js
deleted file mode 100644
index f0b4a08..0000000
--- a/www-forms.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
-Copyright (c) 2009 Hagen Overdick
-
-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.
-*/
-
-function decode(token) {
- return decodeURIComponent(token.replace(/\+/g, " "));
-}
-
-function internalSetValue(target, key, value, force) {
- var arrayTest = key.match(/(.+?)\[(.*)\]/);
- if (arrayTest) {
- target = (target[arrayTest[1]] = target[arrayTest[1]] || []);
- target = target[arrayTest[2]] = value;
- } else {
- target = (target[key] = force ? value : target[key] || value);
- }
- return target;
-}
-
-function setValue(target, key, value) {
- var subkeys = key.split(".");
- var valueKey = subkeys.pop();
-
- for (var i = 0; i < subkeys.length; i++) {
- target = internalSetValue(target, subkeys[i], {}, false);
- }
-
- internalSetValue(target, valueKey, value, true);
-}
-
-exports.decodeForm = function(data) {
- var result = {};
- data
- .split("&")
- .map(function (assignment) { return assignment.split("=").map(decode) })
- .forEach(function(token) { setValue(result, token[0], token[1]) });
- return result;
-}
\ No newline at end of file
|
grumdrig/woses
|
00a0610930db0f9d0a8f97b06001d87502dfcf56
|
No swedes required
|
diff --git a/parp.php b/parp.php
index d83028a..e17ee62 100644
--- a/parp.php
+++ b/parp.php
@@ -1,67 +1,65 @@
<?
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// Command-line use of PHP files as if from a webserver.
//
// Usage: php parp.php file.php arg1=value1 arg2=value2...
// Simulates HTTP request for /file.php?arg1=value1&arg2=value2...
// Opts:
// -r Subsequent key=value pairs are stored in $_REQUEST (default)
// -s Subsequent key=value pairs are stored in $_SERVER
// -S Subsequent key=value pairs are stored in $_SESSION
// --dir=DIR Change directory to specified document root DIR
-//fputs(STDERR, var_export($argv, TRUE));
-
session_start();
$_SESSION['nickname'] = 'Nicholas'; // TODO:
$_SESSION['player'] = 1; // TEMPORARY
$target =& $_REQUEST;
for ($i = 2; $i < count($argv); ++$i) {
if ($argv[$i] == "-s") {
$target =& $_SERVER;
} else if ($argv[$i] == "-r") {
$target =& $_REQUEST;
} else if ($argv[$i] == "-S") {
$target =& $_SESSION;
} else {
$v = explode("=", $argv[$i]);
if ($v[0] == "--dir")
chdir($v[1]);
else
$target[urldecode($v[0])] = urldecode($v[1]);
}
}
//ob_start();
$included = @include($argv[1]);
//$output = ob_get_contents();
//ob_end_clean();
//print $ouput;
if (!$included) {
print "404: No sign of it";
}
//fputs(STDERR, $output);
?>
\ No newline at end of file
|
grumdrig/woses
|
17d9f25b5a4d9d577bbe07b01cdd9ecffce4468b
|
doc improvements
|
diff --git a/doc/.woses-conf.js b/doc/.woses-conf.js
index be7a94c..dec54ec 100644
--- a/doc/.woses-conf.js
+++ b/doc/.woses-conf.js
@@ -1,7 +1,7 @@
exports.mimetypes = {
gif: "image/gif"
}
-//exports.port = 8111;
+exports.port = 8080;
//exports.logRequestHeaders = true;
diff --git a/doc/index.html b/doc/index.html
index f965ad6..2c44d51 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,58 +1,137 @@
<head>
<title>Woses Documentation/Test</title>
<link rel="stylesheet" href="style.css"/>
<script src="script.js"></script>
</head>
<body onLoad="unittest()">
-<h1> ⚉
+<h1>
<!--☶ ☁ ⎈ 𐂷 ☃-->
-Woses
+Woses <span class=right style=color:black>⚉</span>
+</h1>
+
+<p>
+Woses is a <a href=http://nodejs.org/>Node</a>-based webserver with
+support for <a href=http://php.net/>PHP</a> templating.
+
+<p>
+Additionally it includes a mechanism for server-side JavaScript RPC.
+
+<p>
+The home page for Woses is
+<a href=http://grumdrig.com/woses/>http://grumdrig.com/woses/</a>. The
+code lives at
+<a href=http://bitbucket.com/grumdrig/woses>http://bitbucket.com/grumdrig/woses</a>.
+
+<h2>Usage</h2>
+
+<pre>
+$ node woses.js DOCUMENT_ROOT
+</pre>
+
+will run the HTTP server against the content in DOCUMENT_ROOT. For example,
+
+<pre>
+$ node woses.js doc
+</pre>
+
+<p>
+will serve this documentation on <a href=http://localhost:8080/>port
+8080</a>.
+
+<h2> Configuration </h2>
+<p>
+Woses can be configured by placing a file
+called <code>.woses-conf.js</code> in the document root. This file may
+export the following settings:
+
+<ul>
+<li> <code>port</code>: A port other than the default 8080 on which to
+ serve.
+<li> <code>index</code>: Name of a directory index page to use for
+ URI's which point to a folder, rather than the
+ default, <code>index.html</code> falling back
+ to <code>index.php</code>.
+<li> <code>mimetypes</code>: A map from file extensions to MIME types
+ for serving content.
+</ul>
+
+Here is an example configuration file:
+
+<pre>
+exports.port = 80;
+exports.index = "home.html";
+exports.mimetypes = {
+ 'gif': 'image/gif',
+ 'readme': 'text/plain'
+}
+</pre>
+
+<h2> PHP </h2>
+
+<p>
+Woses will serve PHP scripts through the mechanism of the PHP
+command-line interface; thus the <code>php</code> command must be available for
+woses to serve PHP scripts.
+
+<p>
+The big caveat of PHP support is that, within PHP code, calls to
+`header()' have no effect.
+
+<h2> JS RPC </h2>
+
+Javascript modules.
+
+<h2> JS Templating </h2>
+
+<h2> Security </h2>
+
+<h2> Tests </h2>
+
<img class=right src=wose.png>
<img class=right src=sceltictree.jpg>
-</h1>
<p>
<a href=index.html>HTML</a>
⚉
<a href=not-here.html>404</a>
<p>
<a href=README.md>Markdown README</a>
⚉
<a href=not-here.md>404</a>
<form action=test.php method=post>
<a href=test.php?one=param&two=potato>Test PHP</a>
⚉
<a href=not-here.php>404</a>
⚉
<input type=text name=box value=text>
<input type=submit>
</form>
<p>
<form action=test-rpc.js method=post>
<a href="test-rpc.js?this=that">Test JS RPC</a>
⚉
<a href=not-here-rpc.js>404</a>
⚉
<input type=text name=boxy value=words>
<input type=submit>
</form>
⚉
<button onclick="requestJson({a:5, b:10}, 'json-rpc.js', function(r) {feedback(JSON.stringify(r))})">Button?</button>
<p>
Missing image: <img src=not-here.jpg>
<br>
<br>
<br>
<p id=something>Test results:</p>
diff --git a/doc/style.css b/doc/style.css
index 4288f04..c4a5c09 100644
--- a/doc/style.css
+++ b/doc/style.css
@@ -1,11 +1,32 @@
-* {
- font-family: Helvetica;
+pre, code { color: #060; font-size: 11pt; }
+pre { margin-left: 2ex; padding: 1ex; background-color: #eee; }
+p { font-size: 12pt; }
+body {
+ margin-left: 10%;
+ margin-right: 10%;
+ background-color: #fff;
+ color: black;
+ max-width: 800px;
+}
+h1,h2,h3,h4 { font-family: helvetica }
+h1 { font-size: 36pt; }
+h1 {
+ background-color: #58b;
+ color: white;
+ padding-left:6px;
+}
+h2 {
+ color: #28b;
+}
+li > code:first-child {
+ font-weight: bold;
}
.right {
- float:right;
+ float: right;
+ padding-right: 0.5ex;
}
form, input {
display: inline;
-}
\ No newline at end of file
+}
diff --git a/woses.js b/woses.js
index 62dd20e..cdaad52 100644
--- a/woses.js
+++ b/woses.js
@@ -1,226 +1,232 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
wwwforms = require('./www-forms');
function parseUri(path) {
var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(path);
if (parts) {
return {
filename: parts[1],
basename: parts[2],
ext: parts[4]
};
}
}
var config = {
port: 8080,
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
}
}
if (process.ARGV.length > 2)
process.chdir(process.ARGV[2]);
require.paths.push(process.cwd());
+try {
+ posix.stat(config.index).wait();
+} catch (e) {
+ config.index = "index.php"
+}
+
try {
var cf = require(".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
if (req.uri.path == '/')
req.uri.path = "/" + config.index;
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
var result = this.body ? this.body.length : 0;
this.encoding = this.encoding || 'utf8';
res.header('Content-Length', (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length));
this.sendBody(this.body, this.encoding);
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
var uri = parseUri(req.uri.path);
if (!uri) {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
// Exclude ".." in uri
if (req.uri.path.indexOf('..') >= 0 || uri.filename.substr(1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
function respondWithStatic() {
var content_type = config.mimetypes[uri.ext] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
var promise = posix.cat(uri.filename, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function() {
sys.puts("Error 404: " + uri.filename);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
function respondWithPhp() {
res.body = '';
var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
var params = [parp, uri.filename];
for (var param in req.params)
params.push(escape(param) + "=" + escape(req.params[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
"application/xml" : "text/html")
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
req.params = req.uri.params;
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var form = wwwforms.decodeForm(req.body);
for (var param in form)
req.params[param] = form[param];
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
process.mixin(req.params, req.json);
}
if (uri.ext == "php") {
respondWithPhp();
} else if (uri.filename.substr(-7) == "-rpc.js") {
// TODO: use conf file to distinguish client & server js
try {
var script = require(uri.basename);
// TODO: don't have fetch call respond - just set body
var len = script.fetch(req, res);
sys.puts(req.requestLine + " " + len);
} catch (e) {
res.status = 404
res.respond("404: In absentia. Or elsewhere.\n" +
sys.inspect(e));
}
} else if (uri.ext == "md") {
sys.exec("Markdown.pl < " + uri.filename)
.addCallback(function (stdout, stderr) {
res.respond(stdout);})
.addErrback(function (code, stdout, stderr) {
res.status = 404;
res.respond("404: Mark my words. No such file.");
});
} else {
respondWithStatic();
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
c0451c4593d4ef4a23b67dfd1c8993e96b372df6
|
A little more succinct in www-forms
|
diff --git a/www-forms.js b/www-forms.js
index 022a5be..f0b4a08 100644
--- a/www-forms.js
+++ b/www-forms.js
@@ -1,61 +1,56 @@
/*
Copyright (c) 2009 Hagen Overdick
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.
*/
function decode(token) {
return decodeURIComponent(token.replace(/\+/g, " "));
}
-function parseToken(token) {
- return token.split("=").map(decode);
-}
-
function internalSetValue(target, key, value, force) {
var arrayTest = key.match(/(.+?)\[(.*)\]/);
if (arrayTest) {
target = (target[arrayTest[1]] = target[arrayTest[1]] || []);
target = target[arrayTest[2]] = value;
} else {
target = (target[key] = force ? value : target[key] || value);
}
return target;
}
function setValue(target, key, value) {
var subkeys = key.split(".");
var valueKey = subkeys.pop();
- for (var ii = 0; ii < subkeys.length; ii++) {
- target = internalSetValue(target, subkeys[ii], {}, false);
+ for (var i = 0; i < subkeys.length; i++) {
+ target = internalSetValue(target, subkeys[i], {}, false);
}
internalSetValue(target, valueKey, value, true);
}
exports.decodeForm = function(data) {
var result = {};
- if (data && data.split) {
- data.split("&").map(parseToken).forEach(function(token) {
- setValue(result, token[0], token[1]);
- })
- }
+ data
+ .split("&")
+ .map(function (assignment) { return assignment.split("=").map(decode) })
+ .forEach(function(token) { setValue(result, token[0], token[1]) });
return result;
}
\ No newline at end of file
|
grumdrig/woses
|
c1a859e436a97d6cca992237286c3c62aad45adf
|
Use chdir for documentRoot and more tests
|
diff --git a/doc/index.html b/doc/index.html
index 1d515bd..f965ad6 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,58 +1,58 @@
<head>
<title>Woses Documentation/Test</title>
<link rel="stylesheet" href="style.css"/>
<script src="script.js"></script>
</head>
<body onLoad="unittest()">
<h1> ⚉
<!--☶ ☁ ⎈ 𐂷 ☃-->
Woses
<img class=right src=wose.png>
<img class=right src=sceltictree.jpg>
</h1>
<p>
<a href=index.html>HTML</a>
⚉
<a href=not-here.html>404</a>
<p>
<a href=README.md>Markdown README</a>
⚉
<a href=not-here.md>404</a>
<form action=test.php method=post>
<a href=test.php?one=param&two=potato>Test PHP</a>
⚉
<a href=not-here.php>404</a>
⚉
<input type=text name=box value=text>
<input type=submit>
</form>
<p>
<form action=test-rpc.js method=post>
<a href="test-rpc.js?this=that">Test JS RPC</a>
⚉
<a href=not-here-rpc.js>404</a>
⚉
<input type=text name=boxy value=words>
<input type=submit>
</form>
⚉
<button onclick="requestJson({a:5, b:10}, 'json-rpc.js', function(r) {feedback(JSON.stringify(r))})">Button?</button>
<p>
Missing image: <img src=not-here.jpg>
<br>
<br>
<br>
-<p id=something>Script should strike this out.</p>
+<p id=something>Test results:</p>
diff --git a/doc/script.js b/doc/script.js
index 5f9ebcc..1031a02 100644
--- a/doc/script.js
+++ b/doc/script.js
@@ -1,34 +1,79 @@
function feedback(html) {
var s = document.getElementById("something");
- s.innerHTML = html;
+ s.innerHTML = s.innerHTML + "<br>" + html;
}
function requestJson(param, url, callback) {
- var http_request = new XMLHttpRequest();
- http_request.open("POST", url, true);
- http_request.onreadystatechange = function () {
- if (http_request.readyState == 4 && http_request.status == 200) {
- var response = JSON.parse(http_request.responseText);
+ var req = new XMLHttpRequest();
+ req.open("POST", url, true);
+ req.onreadystatechange = function () {
+ if (req.readyState == 4 && req.status == 200) {
+ var response = JSON.parse(req.responseText);
callback(response);
}
};
- http_request.setRequestHeader("Content-Type", "application/json");
- http_request.send(JSON.stringify(param));
+ req.setRequestHeader("Content-Type", "application/json");
+ req.send(JSON.stringify(param));
+}
+
+
+function objectToQueryString(params) {
+ var result = "";
+ for (p in params)
+ if (typeof params[p] != 'undefined')
+ result += (result.length ? "&" : "") + encodeURIComponent(p) + "=" +
+ encodeURIComponent(params[p]);
+ return result;
+}
+
+function requestXml(param, url, callback) {
+ var req = new XMLHttpRequest();
+ req.open("POST", url, true);
+ req.onreadystatechange = function () {
+ if (req.readyState == 4 && req.status == 200) {
+ var t = req.responseText;
+ callback(req.responseXML, t);
+ }
+ };
+ req.setRequestHeader("Content-Type",
+ "application/x-www-form-urlencoded");
+ req.send(objectToQueryString(param));
}
function asserteq(v1, v2) {
if (v1 != v2) {
feedback("ASSERTION FAILED: " + v1 + " = " + v2);
throw "Fit";
}
}
+function adhoc() {
+ var r = '{"whoami":{"id":1,"nickname":"Grum"},"sanity":"check","char":[{"slot":1,"name":"Numkrut Runprib","id":2,"hp":1},{"slot":0,"name":"Xuzshout Ooxxoz","id":1,"hp":"1"}]}';
+ JSON.parse(r);
+}
+
+
+String.prototype.escapeHTML = function () {
+ return(
+ this.replace(/&/g,'&').
+ replace(/>/g,'>').
+ replace(/</g,'<').
+ replace(/"/g,'"')
+ );
+};
+
function unittest() {
+ adhoc();
requestJson({a:8, b:9}, 'json-rpc.js', function (sum) {
- feedback("back");
+ feedback("JSON: " + sum);
asserteq(sum.sum, 17);
- feedback('TESTS RAN OK');
+ requestXml({a:8, b:9}, 'xml-rpc.php', function (xml, tex) {
+ feedback("XML: " + tex.escapeHTML() + ":");
+ //asserteq(sum.sum, 17);
+
+ feedback('TESTS RAN OK');
+ });
});
-}
\ No newline at end of file
+}
diff --git a/doc/xml-rpc.php b/doc/xml-rpc.php
new file mode 100644
index 0000000..13ee327
--- /dev/null
+++ b/doc/xml-rpc.php
@@ -0,0 +1,9 @@
+<?
+
+print '<?xml version="1.0" encoding="utf-8"?>';
+
+print '<response sum="';
+print intval($_REQUEST['a']) + intval($_REQUEST['b']);
+print '"/>';
+
+?>
\ No newline at end of file
diff --git a/woses.js b/woses.js
index 954f717..62dd20e 100644
--- a/woses.js
+++ b/woses.js
@@ -1,239 +1,226 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
wwwforms = require('./www-forms');
function parseUri(path) {
var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(path);
if (parts) {
return {
filename: parts[1],
basename: parts[2],
ext: parts[4]
};
}
}
var config = {
port: 8080,
- documentRoot: "./",
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
- },
- validate: function () {
- if (this.index.substr(0,1) != '/')
- this.index = '/' + this.index;
- if (this.documentRoot.substr(0,1) != '.')
- this.documentRoot = './' + this.documentRoot;
- if (this.documentRoot.substr(-1) != '/')
- this.documentRoot += "/";
}
}
-if (process.ARGV.length > 2) {
- config.documentRoot = process.ARGV[2];
- config.validate();
-}
-var confFile = config.documentRoot + ".woses-conf.js";
+if (process.ARGV.length > 2)
+ process.chdir(process.ARGV[2]);
+
+require.paths.push(process.cwd());
+
try {
- var cf = require(config.documentRoot + ".woses-conf");
+ var cf = require(".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
-//process.chdir(config.documentRoot);
-//config.documentRoot = "./";
-
-
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
if (req.uri.path == '/')
- req.uri.path = config.index;
+ req.uri.path = "/" + config.index;
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
var result = this.body ? this.body.length : 0;
this.encoding = this.encoding || 'utf8';
res.header('Content-Length', (this.encoding === 'utf8' ?
encodeURIComponent(this.body).replace(/%../g, 'x').length :
this.body.length));
this.sendBody(this.body, this.encoding);
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
var uri = parseUri(req.uri.path);
if (!uri) {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
// Exclude ".." in uri
if (req.uri.path.indexOf('..') >= 0 || uri.filename.substr(1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
function respondWithStatic() {
var content_type = config.mimetypes[uri.ext] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
- var promise = posix.cat(config.documentRoot + uri.filename, res.encoding);
+ var promise = posix.cat(uri.filename, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function() {
sys.puts("Error 404: " + uri.filename);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
function respondWithPhp() {
res.body = '';
- var params = ['parp.php', uri.filename, '--dir=' + config.documentRoot];
+ var parp = __filename.split('/').slice(0,-1).concat("parp.php").join("/");
+ var params = [parp, uri.filename];
for (var param in req.params)
params.push(escape(param) + "=" + escape(req.params[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
"application/xml" : "text/html")
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
req.params = req.uri.params;
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var form = wwwforms.decodeForm(req.body);
for (var param in form)
req.params[param] = form[param];
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
process.mixin(req.params, req.json);
}
if (uri.ext == "php") {
respondWithPhp();
} else if (uri.filename.substr(-7) == "-rpc.js") {
// TODO: use conf file to distinguish client & server js
try {
- sys.p(config.documentRoot + uri.basename);
- var script = require(config.documentRoot + uri.basename);
+ var script = require(uri.basename);
// TODO: don't have fetch call respond - just set body
var len = script.fetch(req, res);
sys.puts(req.requestLine + " " + len);
} catch (e) {
res.status = 404
res.respond("404: In absentia. Or elsewhere.\n" +
sys.inspect(e));
}
} else if (uri.ext == "md") {
- sys.exec("Markdown.pl < " + config.documentRoot + uri.filename)
+ sys.exec("Markdown.pl < " + uri.filename)
.addCallback(function (stdout, stderr) {
res.respond(stdout);})
.addErrback(function (code, stdout, stderr) {
res.status = 404;
res.respond("404: Mark my words. No such file.");
});
} else {
respondWithStatic();
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
process.cwd());
|
grumdrig/woses
|
458d68cf9545681d813fc506e5bcc6617cd97594
|
Huppable serverloop, set content-length correctly
|
diff --git a/serverloop.py b/serverloop.py
index 5d92581..ba2928a 100755
--- a/serverloop.py
+++ b/serverloop.py
@@ -1,44 +1,63 @@
#!/usr/bin/python
# Copyright (c) 2009, Eric Fredricksen <[email protected]>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
""" Run the server named herein or on command line, using node.
Whenever it changes, kill and restart. (See http://nodejs.org/)
This is useful during editing and testing of the server."""
-import os, sys, time
+import os, sys, time, signal
root = (sys.argv[1:] or ['.'])[0]
-filenames = ["woses.js", os.path.join(root, ".woses-conf.js")]
+filenames = ["woses.js"];
+conf = os.path.join(root, ".woses-conf.js");
+if os.path.exists(conf): filenames.append(conf);
-def handler():
- print "\n\n"
- os.system("killall -v node");
- os.spawnlp(os.P_NOWAIT, "node", "node", "woses.js", root);
+def restart(pid):
+ if pid:
+ os.kill(pid, signal.SIGTERM)
+ pid = os.spawnlp(os.P_NOWAIT, "node", "node", "woses.js", root);
+ print "Started", pid
+ return pid
+os.system("killall -v node");
+
+pid = None
mtime = []
while True:
m = [os.stat(filename).st_mtime for filename in filenames]
if mtime != m:
- handler()
+ pid = restart(pid)
mtime = m
+ else:
+ try:
+ os.kill(pid, 0)
+ except:
+ pid = restart(pid)
+
try:
time.sleep(1)
except KeyboardInterrupt:
- print
- os.system("killall -v node")
- break
+ print "\nKilling", pid, "^C again to quit"
+ if pid:
+ os.kill(pid, signal.SIGTERM)
+ pid = None
+ try:
+ time.sleep(1)
+ except KeyboardInterrupt:
+ print
+ break
diff --git a/woses.js b/woses.js
index 1ea8fd7..954f717 100644
--- a/woses.js
+++ b/woses.js
@@ -1,232 +1,239 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
wwwforms = require('./www-forms');
function parseUri(path) {
var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(path);
if (parts) {
return {
filename: parts[1],
basename: parts[2],
ext: parts[4]
};
}
}
var config = {
port: 8080,
documentRoot: "./",
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
},
validate: function () {
if (this.index.substr(0,1) != '/')
this.index = '/' + this.index;
+ if (this.documentRoot.substr(0,1) != '.')
+ this.documentRoot = './' + this.documentRoot;
if (this.documentRoot.substr(-1) != '/')
this.documentRoot += "/";
}
}
if (process.ARGV.length > 2) {
config.documentRoot = process.ARGV[2];
config.validate();
}
var confFile = config.documentRoot + ".woses-conf.js";
try {
var cf = require(config.documentRoot + ".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
-
+
+
+//process.chdir(config.documentRoot);
+//config.documentRoot = "./";
+
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
if (req.uri.path == '/')
req.uri.path = config.index;
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string') {
this.header("content-type", "application/json");
this.body = JSON.stringify(this.body);
}
var result = this.body ? this.body.length : 0;
- this.sendBody(this.body, this.encoding || 'utf8');
+ this.encoding = this.encoding || 'utf8';
+ res.header('Content-Length', (this.encoding === 'utf8' ?
+ encodeURIComponent(this.body).replace(/%../g, 'x').length :
+ this.body.length));
+ this.sendBody(this.body, this.encoding);
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
var uri = parseUri(req.uri.path);
if (!uri) {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
// Exclude ".." in uri
if (req.uri.path.indexOf('..') >= 0 || uri.filename.substr(1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
function respondWithStatic() {
var content_type = config.mimetypes[uri.ext] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
var promise = posix.cat(config.documentRoot + uri.filename, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
- res.header('Content-Length', res.encoding === 'utf8' ?
- encodeURIComponent(data).replace(/%../g, 'x').length :
- data.length);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function() {
sys.puts("Error 404: " + uri.filename);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
function respondWithPhp() {
res.body = '';
var params = ['parp.php', uri.filename, '--dir=' + config.documentRoot];
for (var param in req.params)
params.push(escape(param) + "=" + escape(req.params[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
"application/xml" : "text/html")
- res.header("Content-Length", res.body.length);;
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
req.params = req.uri.params;
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
var ct = req.headers['content-type'];
if (ct) ct = ct.split(';')[0];
if (ct == "application/x-www-form-urlencoded") {
var form = wwwforms.decodeForm(req.body);
for (var param in form)
req.params[param] = form[param];
} else if (ct == "application/json") {
req.json = JSON.parse(req.body);
process.mixin(req.params, req.json);
}
if (uri.ext == "php") {
respondWithPhp();
} else if (uri.filename.substr(-7) == "-rpc.js") {
// TODO: use conf file to distinguish client & server js
try {
+ sys.p(config.documentRoot + uri.basename);
var script = require(config.documentRoot + uri.basename);
// TODO: don't have fetch call respond - just set body
var len = script.fetch(req, res);
sys.puts(req.requestLine + " " + len);
} catch (e) {
res.status = 404
res.respond("404: In absentia. Or elsewhere.\n" +
sys.inspect(e));
}
} else if (uri.ext == "md") {
sys.exec("Markdown.pl < " + config.documentRoot + uri.filename)
.addCallback(function (stdout, stderr) {
res.respond(stdout);})
.addErrback(function (code, stdout, stderr) {
res.status = 404;
res.respond("404: Mark my words. No such file.");
});
} else {
respondWithStatic();
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
- config.documentRoot);
+ process.cwd());
|
grumdrig/woses
|
cbeb635673620c173cb5ea4ded299cfefdc0ec62
|
some sort of primitive start to unittesting
|
diff --git a/doc/index.html b/doc/index.html
index 618c495..1d515bd 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,54 +1,58 @@
<head>
<title>Woses Documentation/Test</title>
<link rel="stylesheet" href="style.css"/>
<script src="script.js"></script>
</head>
-<body onLoad="doSomething()">
+<body onLoad="unittest()">
<h1> ⚉
<!--☶ ☁ ⎈ 𐂷 ☃-->
Woses
<img class=right src=wose.png>
<img class=right src=sceltictree.jpg>
</h1>
<p>
<a href=index.html>HTML</a>
⚉
<a href=not-here.html>404</a>
<p>
<a href=README.md>Markdown README</a>
⚉
<a href=not-here.md>404</a>
<form action=test.php method=post>
<a href=test.php?one=param&two=potato>Test PHP</a>
⚉
<a href=not-here.php>404</a>
⚉
<input type=text name=box value=text>
<input type=submit>
</form>
<p>
<form action=test-rpc.js method=post>
<a href="test-rpc.js?this=that">Test JS RPC</a>
⚉
<a href=not-here-rpc.js>404</a>
⚉
<input type=text name=boxy value=words>
<input type=submit>
</form>
⚉
-<button onclick="requestJson({a:5, b:10}, 'json-rpc.js')">Button?</button>
+<button onclick="requestJson({a:5, b:10}, 'json-rpc.js', function(r) {feedback(JSON.stringify(r))})">Button?</button>
<p>
Missing image: <img src=not-here.jpg>
+<br>
+<br>
+<br>
+
<p id=something>Script should strike this out.</p>
diff --git a/doc/script.js b/doc/script.js
index 8b00986..5f9ebcc 100644
--- a/doc/script.js
+++ b/doc/script.js
@@ -1,20 +1,34 @@
-function doSomething() {
+function feedback(html) {
var s = document.getElementById("something");
- s.innerHTML = "<s>" + s.innerHTML + "</s>";
+ s.innerHTML = html;
}
-function requestJson(param, url) {
+function requestJson(param, url, callback) {
var http_request = new XMLHttpRequest();
http_request.open("POST", url, true);
http_request.onreadystatechange = function () {
if (http_request.readyState == 4 && http_request.status == 200) {
var response = JSON.parse(http_request.responseText);
- var s = document.getElementById("something");
- s.innerHTML = JSON.stringify(response);
+ callback(response);
}
};
http_request.setRequestHeader("Content-Type", "application/json");
http_request.send(JSON.stringify(param));
+}
+
+function asserteq(v1, v2) {
+ if (v1 != v2) {
+ feedback("ASSERTION FAILED: " + v1 + " = " + v2);
+ throw "Fit";
+ }
+}
+
+function unittest() {
+ requestJson({a:8, b:9}, 'json-rpc.js', function (sum) {
+ feedback("back");
+ asserteq(sum.sum, 17);
+ feedback('TESTS RAN OK');
+ });
}
\ No newline at end of file
|
grumdrig/woses
|
45311c817ed785f3d08dc4b1c866777b8ab9d1db
|
Rename a couple files
|
diff --git a/doc/index.html b/doc/index.html
index a4f4ce3..618c495 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,54 +1,54 @@
<head>
<title>Woses Documentation/Test</title>
- <link rel="stylesheet" href="main.css"/>
- <script src="main.js"></script>
+ <link rel="stylesheet" href="style.css"/>
+ <script src="script.js"></script>
</head>
<body onLoad="doSomething()">
<h1> ⚉
<!--☶ ☁ ⎈ 𐂷 ☃-->
Woses
<img class=right src=wose.png>
<img class=right src=sceltictree.jpg>
</h1>
<p>
<a href=index.html>HTML</a>
⚉
<a href=not-here.html>404</a>
<p>
<a href=README.md>Markdown README</a>
⚉
<a href=not-here.md>404</a>
<form action=test.php method=post>
<a href=test.php?one=param&two=potato>Test PHP</a>
⚉
<a href=not-here.php>404</a>
⚉
<input type=text name=box value=text>
<input type=submit>
</form>
<p>
<form action=test-rpc.js method=post>
<a href="test-rpc.js?this=that">Test JS RPC</a>
⚉
<a href=not-here-rpc.js>404</a>
⚉
<input type=text name=boxy value=words>
<input type=submit>
</form>
⚉
<button onclick="requestJson({a:5, b:10}, 'json-rpc.js')">Button?</button>
<p>
Missing image: <img src=not-here.jpg>
<p id=something>Script should strike this out.</p>
diff --git a/doc/json-rpc.js b/doc/json-rpc.js
index f2a26c5..9aec584 100644
--- a/doc/json-rpc.js
+++ b/doc/json-rpc.js
@@ -1,10 +1,8 @@
var sys = require("sys");
exports.fetch = function (request, response) {
- sys.p(request);
- sys.p("WTF");
response.header("content-type", "application/json");
response.body = {sum: request.json.a + request.json.b,
aka: request.params.a + request.params.b};
return response.respond();
}
diff --git a/doc/main.js b/doc/script.js
similarity index 100%
rename from doc/main.js
rename to doc/script.js
diff --git a/doc/main.css b/doc/style.css
similarity index 100%
rename from doc/main.css
rename to doc/style.css
|
grumdrig/woses
|
080ad89fdb483c5a962014226e22ecf64487c25a
|
Added JSON RPC
|
diff --git a/doc/.woses-conf.js b/doc/.woses-conf.js
index 76f903e..be7a94c 100644
--- a/doc/.woses-conf.js
+++ b/doc/.woses-conf.js
@@ -1,7 +1,7 @@
exports.mimetypes = {
gif: "image/gif"
}
//exports.port = 8111;
-exports.logRequestHeaders = true;
\ No newline at end of file
+//exports.logRequestHeaders = true;
diff --git a/doc/index.html b/doc/index.html
index 6f8fd1e..a4f4ce3 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,52 +1,54 @@
<head>
<title>Woses Documentation/Test</title>
<link rel="stylesheet" href="main.css"/>
<script src="main.js"></script>
</head>
<body onLoad="doSomething()">
<h1> ⚉
<!--☶ ☁ ⎈ 𐂷 ☃-->
Woses
<img class=right src=wose.png>
<img class=right src=sceltictree.jpg>
</h1>
<p>
<a href=index.html>HTML</a>
⚉
<a href=not-here.html>404</a>
<p>
<a href=README.md>Markdown README</a>
⚉
<a href=not-here.md>404</a>
<form action=test.php method=post>
<a href=test.php?one=param&two=potato>Test PHP</a>
⚉
<a href=not-here.php>404</a>
⚉
<input type=text name=box value=text>
<input type=submit>
</form>
<p>
<form action=test-rpc.js method=post>
<a href="test-rpc.js?this=that">Test JS RPC</a>
⚉
<a href=not-here-rpc.js>404</a>
⚉
<input type=text name=boxy value=words>
<input type=submit>
</form>
+⚉
+<button onclick="requestJson({a:5, b:10}, 'json-rpc.js')">Button?</button>
<p>
Missing image: <img src=not-here.jpg>
<p id=something>Script should strike this out.</p>
diff --git a/doc/json-rpc.js b/doc/json-rpc.js
new file mode 100644
index 0000000..f2a26c5
--- /dev/null
+++ b/doc/json-rpc.js
@@ -0,0 +1,10 @@
+var sys = require("sys");
+
+exports.fetch = function (request, response) {
+ sys.p(request);
+ sys.p("WTF");
+ response.header("content-type", "application/json");
+ response.body = {sum: request.json.a + request.json.b,
+ aka: request.params.a + request.params.b};
+ return response.respond();
+}
diff --git a/doc/main.js b/doc/main.js
index 6421429..8b00986 100644
--- a/doc/main.js
+++ b/doc/main.js
@@ -1,6 +1,20 @@
function doSomething() {
var s = document.getElementById("something");
s.innerHTML = "<s>" + s.innerHTML + "</s>";
+}
+
+function requestJson(param, url) {
+ var http_request = new XMLHttpRequest();
+ http_request.open("POST", url, true);
+ http_request.onreadystatechange = function () {
+ if (http_request.readyState == 4 && http_request.status == 200) {
+ var response = JSON.parse(http_request.responseText);
+ var s = document.getElementById("something");
+ s.innerHTML = JSON.stringify(response);
+ }
+ };
+ http_request.setRequestHeader("Content-Type", "application/json");
+ http_request.send(JSON.stringify(param));
}
\ No newline at end of file
diff --git a/woses.js b/woses.js
index 96e8837..1ea8fd7 100644
--- a/woses.js
+++ b/woses.js
@@ -1,222 +1,232 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
wwwforms = require('./www-forms');
function parseUri(path) {
var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(path);
if (parts) {
return {
filename: parts[1],
basename: parts[2],
ext: parts[4]
};
}
}
var config = {
port: 8080,
documentRoot: "./",
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
},
validate: function () {
if (this.index.substr(0,1) != '/')
this.index = '/' + this.index;
if (this.documentRoot.substr(-1) != '/')
this.documentRoot += "/";
}
}
if (process.ARGV.length > 2) {
config.documentRoot = process.ARGV[2];
config.validate();
}
var confFile = config.documentRoot + ".woses-conf.js";
try {
var cf = require(config.documentRoot + ".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
if (req.uri.path == '/')
req.uri.path = config.index;
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
- if (typeof this.body != 'string')
- this.body = JSON.encode(this.body);
+ if (typeof this.body != 'string') {
+ this.header("content-type", "application/json");
+ this.body = JSON.stringify(this.body);
+ }
var result = this.body ? this.body.length : 0;
this.sendBody(this.body, this.encoding || 'utf8');
this.finish();
return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
var uri = parseUri(req.uri.path);
if (!uri) {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
// Exclude ".." in uri
if (req.uri.path.indexOf('..') >= 0 || uri.filename.substr(1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
function respondWithStatic() {
var content_type = config.mimetypes[uri.ext] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
var promise = posix.cat(config.documentRoot + uri.filename, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
res.header('Content-Length', res.encoding === 'utf8' ?
encodeURIComponent(data).replace(/%../g, 'x').length :
data.length);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function() {
sys.puts("Error 404: " + uri.filename);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
function respondWithPhp() {
res.body = '';
var params = ['parp.php', uri.filename, '--dir=' + config.documentRoot];
for (var param in req.params)
params.push(escape(param) + "=" + escape(req.params[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
"application/xml" : "text/html")
res.header("Content-Length", res.body.length);;
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
req.params = req.uri.params;
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function () {
- if (req.headers['content-type'] == "application/x-www-form-urlencoded") {
+ var ct = req.headers['content-type'];
+ if (ct) ct = ct.split(';')[0];
+ if (ct == "application/x-www-form-urlencoded") {
var form = wwwforms.decodeForm(req.body);
for (var param in form)
req.params[param] = form[param];
+ } else if (ct == "application/json") {
+ req.json = JSON.parse(req.body);
+ process.mixin(req.params, req.json);
}
if (uri.ext == "php") {
respondWithPhp();
+
} else if (uri.filename.substr(-7) == "-rpc.js") {
// TODO: use conf file to distinguish client & server js
try {
var script = require(config.documentRoot + uri.basename);
// TODO: don't have fetch call respond - just set body
var len = script.fetch(req, res);
sys.puts(req.requestLine + " " + len);
} catch (e) {
res.status = 404
res.respond("404: In absentia. Or elsewhere.\n" +
sys.inspect(e));
}
+
} else if (uri.ext == "md") {
sys.exec("Markdown.pl < " + config.documentRoot + uri.filename)
.addCallback(function (stdout, stderr) {
res.respond(stdout);})
.addErrback(function (code, stdout, stderr) {
res.status = 404;
res.respond("404: Mark my words. No such file.");
});
+
} else {
respondWithStatic();
}
});
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
config.documentRoot);
|
grumdrig/woses
|
67a02e9135d736b93e52b2d22908557c3027b392
|
Use POST params in js rpc. Test forms.
|
diff --git a/doc/.woses-conf.js b/doc/.woses-conf.js
index bb988e6..76f903e 100644
--- a/doc/.woses-conf.js
+++ b/doc/.woses-conf.js
@@ -1,7 +1,7 @@
exports.mimetypes = {
gif: "image/gif"
}
//exports.port = 8111;
-//exports.logRequestHeaders = true;
\ No newline at end of file
+exports.logRequestHeaders = true;
\ No newline at end of file
diff --git a/doc/index.html b/doc/index.html
index 0d48d8a..6f8fd1e 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,45 +1,52 @@
<head>
<title>Woses Documentation/Test</title>
<link rel="stylesheet" href="main.css"/>
<script src="main.js"></script>
</head>
<body onLoad="doSomething()">
<h1> ⚉
<!--☶ ☁ ⎈ 𐂷 ☃-->
Woses
<img class=right src=wose.png>
<img class=right src=sceltictree.jpg>
</h1>
<p>
<a href=index.html>HTML</a>
⚉
<a href=not-here.html>404</a>
<p>
<a href=README.md>Markdown README</a>
⚉
<a href=not-here.md>404</a>
-<p>
-
+<form action=test.php method=post>
<a href=test.php?one=param&two=potato>Test PHP</a>
⚉
<a href=not-here.php>404</a>
+⚉
+ <input type=text name=box value=text>
+ <input type=submit>
+</form>
<p>
-
+<form action=test-rpc.js method=post>
<a href="test-rpc.js?this=that">Test JS RPC</a>
⚉
<a href=not-here-rpc.js>404</a>
+⚉
+ <input type=text name=boxy value=words>
+ <input type=submit>
+</form>
<p>
Missing image: <img src=not-here.jpg>
<p id=something>Script should strike this out.</p>
diff --git a/doc/main.css b/doc/main.css
index d85ab5b..4288f04 100644
--- a/doc/main.css
+++ b/doc/main.css
@@ -1,7 +1,11 @@
* {
font-family: Helvetica;
}
-.rigght {
+.right {
float:right;
+}
+
+form, input {
+ display: inline;
}
\ No newline at end of file
diff --git a/doc/test-rpc.js b/doc/test-rpc.js
index 48c03f8..2529089 100644
--- a/doc/test-rpc.js
+++ b/doc/test-rpc.js
@@ -1,7 +1,8 @@
var sys = require("sys");
exports.fetch = function (request, response) {
response.header("content-type", "text/html");
//sys.p(repsonse.headers);
response.body = "Got it. <pre>" + sys.inspect(request.uri.params);
+ return response.respond();
}
diff --git a/parp.php b/parp.php
index 9e213a4..d83028a 100644
--- a/parp.php
+++ b/parp.php
@@ -1,67 +1,67 @@
<?
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// Command-line use of PHP files as if from a webserver.
//
// Usage: php parp.php file.php arg1=value1 arg2=value2...
// Simulates HTTP request for /file.php?arg1=value1&arg2=value2...
// Opts:
// -r Subsequent key=value pairs are stored in $_REQUEST (default)
// -s Subsequent key=value pairs are stored in $_SERVER
// -S Subsequent key=value pairs are stored in $_SESSION
// --dir=DIR Change directory to specified document root DIR
//fputs(STDERR, var_export($argv, TRUE));
session_start();
$_SESSION['nickname'] = 'Nicholas'; // TODO:
$_SESSION['player'] = 1; // TEMPORARY
$target =& $_REQUEST;
for ($i = 2; $i < count($argv); ++$i) {
if ($argv[$i] == "-s") {
$target =& $_SERVER;
} else if ($argv[$i] == "-r") {
$target =& $_REQUEST;
} else if ($argv[$i] == "-S") {
$target =& $_SESSION;
} else {
$v = explode("=", $argv[$i]);
if ($v[0] == "--dir")
chdir($v[1]);
else
- $target[$v[0]] = $v[1];
+ $target[urldecode($v[0])] = urldecode($v[1]);
}
}
//ob_start();
$included = @include($argv[1]);
//$output = ob_get_contents();
//ob_end_clean();
//print $ouput;
if (!$included) {
print "404: No sign of it";
}
//fputs(STDERR, $output);
?>
\ No newline at end of file
diff --git a/woses.js b/woses.js
index eb922cd..96e8837 100644
--- a/woses.js
+++ b/woses.js
@@ -1,224 +1,222 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
wwwforms = require('./www-forms');
function parseUri(path) {
var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(path);
if (parts) {
return {
filename: parts[1],
basename: parts[2],
ext: parts[4]
};
}
}
var config = {
port: 8080,
documentRoot: "./",
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
},
validate: function () {
if (this.index.substr(0,1) != '/')
this.index = '/' + this.index;
if (this.documentRoot.substr(-1) != '/')
this.documentRoot += "/";
}
}
if (process.ARGV.length > 2) {
config.documentRoot = process.ARGV[2];
config.validate();
}
var confFile = config.documentRoot + ".woses-conf.js";
try {
var cf = require(config.documentRoot + ".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
if (req.uri.path == '/')
req.uri.path = config.index;
res.respond = function (body) {
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string')
this.body = JSON.encode(this.body);
+ var result = this.body ? this.body.length : 0;
this.sendBody(this.body, this.encoding || 'utf8');
this.finish();
+ return result;
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
var uri = parseUri(req.uri.path);
if (!uri) {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
// Exclude ".." in uri
if (req.uri.path.indexOf('..') >= 0 || uri.filename.substr(1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
function respondWithStatic() {
var content_type = config.mimetypes[uri.ext] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
var promise = posix.cat(config.documentRoot + uri.filename, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
res.header('Content-Length', res.encoding === 'utf8' ?
encodeURIComponent(data).replace(/%../g, 'x').length :
data.length);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function() {
sys.puts("Error 404: " + uri.filename);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
function respondWithPhp() {
res.body = '';
var params = ['parp.php', uri.filename, '--dir=' + config.documentRoot];
- for (var param in req.uri.params)
- params.push(param + "=" + req.uri.params[param]);
-
- var form = wwwforms.decodeForm(req.body);
- for (var param in form)
- params.push(param + "=" + form[param]);
+ for (var param in req.params)
+ params.push(escape(param) + "=" + escape(req.params[param]));
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
res.body += data;
} else {
res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
"application/xml" : "text/html")
res.header("Content-Length", res.body.length);;
sys.puts(req.requestLine + " (php) " + res.body.length);
if (res.body.match(/^404:/))
res.status = 404;
res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//return res.respond('500: Sombody said something shocking.');
}
});
}
- function finishUp() {
+ req.params = req.uri.params;
+ req.body = '';
+ req.addListener('body', function(chunk) {
+ req.pause();
+ req.body += chunk;
+ setTimeout(function() { req.resume(); });
+ });
+ req.addListener('complete', function () {
+ if (req.headers['content-type'] == "application/x-www-form-urlencoded") {
+ var form = wwwforms.decodeForm(req.body);
+ for (var param in form)
+ req.params[param] = form[param];
+ }
+
if (uri.ext == "php") {
respondWithPhp();
} else if (uri.filename.substr(-7) == "-rpc.js") {
// TODO: use conf file to distinguish client & server js
try {
var script = require(config.documentRoot + uri.basename);
- script.fetch(req, res);
- sys.puts(req.requestLine + " " + res.body.length);
- res.respond();
+ // TODO: don't have fetch call respond - just set body
+ var len = script.fetch(req, res);
+ sys.puts(req.requestLine + " " + len);
} catch (e) {
res.status = 404
res.respond("404: In absentia. Or elsewhere.\n" +
sys.inspect(e));
}
} else if (uri.ext == "md") {
sys.exec("Markdown.pl < " + config.documentRoot + uri.filename)
.addCallback(function (stdout, stderr) {
res.respond(stdout);})
.addErrback(function (code, stdout, stderr) {
res.status = 404;
res.respond("404: Mark my words. No such file.");
});
} else {
respondWithStatic();
}
- }
-
- var contentLength = parseInt(req.headers['content-length']);
- if (contentLength) {
- req.body = '';
- req.addListener('body', function(chunk) {
- req.pause();
- req.body += chunk;
- setTimeout(function() { req.resume(); });
- });
- req.addListener('complete', finishUp);
- } else {
- finishUp(); // Todo: does complete get called regardless?
- }
+ });
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
config.documentRoot);
|
grumdrig/woses
|
5f53a8783199beab2a534672edc5085311115973
|
Always recv req body
|
diff --git a/doc/.woses-conf.js b/doc/.woses-conf.js
index 76f903e..bb988e6 100644
--- a/doc/.woses-conf.js
+++ b/doc/.woses-conf.js
@@ -1,7 +1,7 @@
exports.mimetypes = {
gif: "image/gif"
}
//exports.port = 8111;
-exports.logRequestHeaders = true;
\ No newline at end of file
+//exports.logRequestHeaders = true;
\ No newline at end of file
diff --git a/doc/index.html b/doc/index.html
index 54966da..0d48d8a 100644
--- a/doc/index.html
+++ b/doc/index.html
@@ -1,26 +1,45 @@
-<img src=wose.png> Woses.
+<head>
+ <title>Woses Documentation/Test</title>
+ <link rel="stylesheet" href="main.css"/>
+ <script src="main.js"></script>
+</head>
+
+<body onLoad="doSomething()">
+
+<h1> ⚉
+<!--☶ ☁ ⎈ 𐂷 ☃-->
+Woses
+<img class=right src=wose.png>
+<img class=right src=sceltictree.jpg>
+</h1>
<p>
<a href=index.html>HTML</a>
+⚉
<a href=not-here.html>404</a>
<p>
<a href=README.md>Markdown README</a>
+⚉
<a href=not-here.md>404</a>
<p>
-<a href=test.php>Test PHP</a>
+<a href=test.php?one=param&two=potato>Test PHP</a>
+⚉
<a href=not-here.php>404</a>
<p>
-<a href=test-rpc.js>Test JS RPC</a>
+<a href="test-rpc.js?this=that">Test JS RPC</a>
+⚉
<a href=not-here-rpc.js>404</a>
<p>
-Missing image <img src=not-here.jpg>
+Missing image: <img src=not-here.jpg>
+
+<p id=something>Script should strike this out.</p>
diff --git a/doc/main.css b/doc/main.css
new file mode 100644
index 0000000..d85ab5b
--- /dev/null
+++ b/doc/main.css
@@ -0,0 +1,7 @@
+* {
+ font-family: Helvetica;
+}
+
+.rigght {
+ float:right;
+}
\ No newline at end of file
diff --git a/doc/main.js b/doc/main.js
new file mode 100644
index 0000000..6421429
--- /dev/null
+++ b/doc/main.js
@@ -0,0 +1,6 @@
+
+
+function doSomething() {
+ var s = document.getElementById("something");
+ s.innerHTML = "<s>" + s.innerHTML + "</s>";
+}
\ No newline at end of file
diff --git a/doc/sceltictree.jpg b/doc/sceltictree.jpg
new file mode 100644
index 0000000..ac2eb5b
Binary files /dev/null and b/doc/sceltictree.jpg differ
diff --git a/doc/test-rpc.js b/doc/test-rpc.js
index d094bc0..48c03f8 100644
--- a/doc/test-rpc.js
+++ b/doc/test-rpc.js
@@ -1,4 +1,7 @@
+var sys = require("sys");
exports.fetch = function (request, response) {
- response.respond("Got it");
+ response.header("content-type", "text/html");
+ //sys.p(repsonse.headers);
+ response.body = "Got it. <pre>" + sys.inspect(request.uri.params);
}
diff --git a/doc/test.php b/doc/test.php
index 2f3976f..1ab4cab 100644
--- a/doc/test.php
+++ b/doc/test.php
@@ -1,5 +1,10 @@
+PHP File!
<pre>
<?
-phpinfo();
+print "<table>";
+foreach ($_REQUEST as $key => $value) {
+ print "<tr><th>$key<td>$value";
+ }
+print "</table>";
?>
</pre>
\ No newline at end of file
diff --git a/woses.js b/woses.js
index e46394b..eb922cd 100644
--- a/woses.js
+++ b/woses.js
@@ -1,220 +1,224 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
wwwforms = require('./www-forms');
function parseUri(path) {
var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(path);
if (parts) {
return {
filename: parts[1],
basename: parts[2],
ext: parts[4]
};
}
}
var config = {
port: 8080,
documentRoot: "./",
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
},
validate: function () {
if (this.index.substr(0,1) != '/')
this.index = '/' + this.index;
if (this.documentRoot.substr(-1) != '/')
this.documentRoot += "/";
}
}
if (process.ARGV.length > 2) {
config.documentRoot = process.ARGV[2];
config.validate();
}
var confFile = config.documentRoot + ".woses-conf.js";
try {
var cf = require(config.documentRoot + ".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
if (req.uri.path == '/')
req.uri.path = config.index;
res.respond = function (body) {
- sys.p(this);
this.sendHeader(this.status || 200, this.headers);
this.body = body || this.body || "";
if (typeof this.body != 'string')
this.body = JSON.encode(this.body);
this.sendBody(this.body, this.encoding || 'utf8');
this.finish();
}
res.header = function(header, value) {
if (!this.headers) this.headers = [];
this.headers.push([header, value]);
}
var uri = parseUri(req.uri.path);
if (!uri) {
res.status = 400;
return res.respond("400: I have no idea what that is");
}
// Exclude ".." in uri
if (req.uri.path.indexOf('..') >= 0 || uri.filename.substr(1) == ".") {
res.status = 403;
return res.respond("403: Don't hack me, bro");
}
function respondWithStatic() {
var content_type = config.mimetypes[uri.ext] || "text/plain";
res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
var promise = posix.cat(config.documentRoot + uri.filename, res.encoding);
promise.addCallback(function(data) {
res.header('Content-Type', content_type);
res.header('Content-Length', res.encoding === 'utf8' ?
encodeURIComponent(data).replace(/%../g, 'x').length :
data.length);
sys.puts(req.requestLine + " " + data.length);
res.respond(data);
});
promise.addErrback(function() {
sys.puts("Error 404: " + uri.filename);
res.status = 404;
res.header('Content-Type', 'text/plain');
res.respond('404: I looked but did not find.');
});
}
function respondWithPhp() {
res.body = '';
-
var params = ['parp.php', uri.filename, '--dir=' + config.documentRoot];
for (var param in req.uri.params)
params.push(param + "=" + req.uri.params[param]);
- this.bytesTotal = req.headers['content-length'];
-
- req.body = '';
- req.addListener('body', function(chunk) {
+ var form = wwwforms.decodeForm(req.body);
+ for (var param in form)
+ params.push(param + "=" + form[param]);
+ params.push("-s");
+ params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
+ params.push("HTTP_HOST=" + req.headers['host']);
+ params.push("REQUEST_URI=" + req.uri.full);
+ var promise = process.createChildProcess("php", params);
+ promise.addListener("output", function (data) {
req.pause();
- req.body += chunk;
- setTimeout(function() { req.resume(); });
+ if (data != null) {
+ res.body += data;
+ } else {
+ res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
+ "application/xml" : "text/html")
+ res.header("Content-Length", res.body.length);;
+ sys.puts(req.requestLine + " (php) " + res.body.length);
+ if (res.body.match(/^404:/))
+ res.status = 404;
+ res.respond();
+ }
+ setTimeout(function(){req.resume();});
});
- req.addListener('complete', function() {
- var form = wwwforms.decodeForm(req.body);
- for (var param in form)
- params.push(param + "=" + form[param]);
- params.push("-s");
- params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
- params.push("HTTP_HOST=" + req.headers['host']);
- params.push("REQUEST_URI=" + req.uri.full);
- var promise = process.createChildProcess("php", params);
- promise.addListener("output", function (data) {
- req.pause();
- if (data != null) {
- res.body += data;
- } else {
- res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
- "application/xml" : "text/html")
- res.header("Content-Length", res.body.length);;
- sys.puts(req.requestLine + " (php) " + res.body.length);
- if (res.body.match(/^404:/))
- res.status = 404;
- res.respond();
- }
- setTimeout(function(){req.resume();});
- });
- promise.addListener("error", function(content) {
- if (content != null) {
- sys.puts("STDERR (php): " + content);
- //return res.respond('500: Sombody said something shocking.');
- }
- });
+ promise.addListener("error", function(content) {
+ if (content != null) {
+ sys.puts("STDERR (php): " + content);
+ //return res.respond('500: Sombody said something shocking.');
+ }
});
-
}
-
- if (uri.ext == "php") {
- respondWithPhp();
- } else if (uri.filename.substr(-7) == "-rpc.js") {
- // TODO: use conf file to distinguish client & server js
- try {
- var script = require(config.documentRoot + uri.basename);
- script.fetch(req, res);
- } catch (e) {
- res.status = 404
- res.respond("404: In absentia. Or elsewhere.\n" +
- sys.inspect(e));
+
+ function finishUp() {
+ if (uri.ext == "php") {
+ respondWithPhp();
+ } else if (uri.filename.substr(-7) == "-rpc.js") {
+ // TODO: use conf file to distinguish client & server js
+ try {
+ var script = require(config.documentRoot + uri.basename);
+ script.fetch(req, res);
+ sys.puts(req.requestLine + " " + res.body.length);
+ res.respond();
+ } catch (e) {
+ res.status = 404
+ res.respond("404: In absentia. Or elsewhere.\n" +
+ sys.inspect(e));
+ }
+ } else if (uri.ext == "md") {
+ sys.exec("Markdown.pl < " + config.documentRoot + uri.filename)
+ .addCallback(function (stdout, stderr) {
+ res.respond(stdout);})
+ .addErrback(function (code, stdout, stderr) {
+ res.status = 404;
+ res.respond("404: Mark my words. No such file.");
+ });
+ } else {
+ respondWithStatic();
}
- } else if (uri.ext == "md") {
- sys.exec("Markdown.pl < " + config.documentRoot + uri.filename)
- .addCallback(function (stdout, stderr) {
- res.respond(stdout);})
- .addErrback(function (code, stdout, stderr) {
- res.status = 404;
- res.respond("404: Mark my words. No such file.");
+ }
+
+ var contentLength = parseInt(req.headers['content-length']);
+ if (contentLength) {
+ req.body = '';
+ req.addListener('body', function(chunk) {
+ req.pause();
+ req.body += chunk;
+ setTimeout(function() { req.resume(); });
});
+ req.addListener('complete', finishUp);
} else {
- respondWithStatic();
+ finishUp(); // Todo: does complete get called regardless?
}
-
+
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
config.documentRoot);
|
grumdrig/woses
|
6b10aa8508acf50b2a83ec31fe6431177ed0471d
|
Refactor responding a little. Add doc/test dir.
|
diff --git a/doc/.woses-conf.js b/doc/.woses-conf.js
new file mode 100644
index 0000000..76f903e
--- /dev/null
+++ b/doc/.woses-conf.js
@@ -0,0 +1,7 @@
+exports.mimetypes = {
+ gif: "image/gif"
+}
+
+//exports.port = 8111;
+
+exports.logRequestHeaders = true;
\ No newline at end of file
diff --git a/README.md b/doc/README.md
similarity index 100%
rename from README.md
rename to doc/README.md
diff --git a/doc/index.html b/doc/index.html
new file mode 100644
index 0000000..54966da
--- /dev/null
+++ b/doc/index.html
@@ -0,0 +1,26 @@
+<img src=wose.png> Woses.
+
+<p>
+
+<a href=index.html>HTML</a>
+<a href=not-here.html>404</a>
+
+<p>
+
+<a href=README.md>Markdown README</a>
+<a href=not-here.md>404</a>
+
+<p>
+
+<a href=test.php>Test PHP</a>
+<a href=not-here.php>404</a>
+
+<p>
+
+<a href=test-rpc.js>Test JS RPC</a>
+<a href=not-here-rpc.js>404</a>
+
+<p>
+
+Missing image <img src=not-here.jpg>
+
diff --git a/doc/test-rpc.js b/doc/test-rpc.js
new file mode 100644
index 0000000..d094bc0
--- /dev/null
+++ b/doc/test-rpc.js
@@ -0,0 +1,4 @@
+
+exports.fetch = function (request, response) {
+ response.respond("Got it");
+}
diff --git a/doc/test.php b/doc/test.php
new file mode 100644
index 0000000..2f3976f
--- /dev/null
+++ b/doc/test.php
@@ -0,0 +1,5 @@
+<pre>
+<?
+phpinfo();
+?>
+</pre>
\ No newline at end of file
diff --git a/doc/wose.png b/doc/wose.png
new file mode 100644
index 0000000..2fc8147
Binary files /dev/null and b/doc/wose.png differ
diff --git a/serverloop.py b/serverloop.py
index 6323ed8..5d92581 100755
--- a/serverloop.py
+++ b/serverloop.py
@@ -1,43 +1,44 @@
#!/usr/bin/python
# Copyright (c) 2009, Eric Fredricksen <[email protected]>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
""" Run the server named herein or on command line, using node.
Whenever it changes, kill and restart. (See http://nodejs.org/)
This is useful during editing and testing of the server."""
import os, sys, time
-filenames = ["woses.js", ".woses-conf.js"]
+root = (sys.argv[1:] or ['.'])[0]
+filenames = ["woses.js", os.path.join(root, ".woses-conf.js")]
def handler():
print "\n\n"
os.system("killall -v node");
- os.spawnvp(os.P_NOWAIT, "node", ["node", "woses.js"] + sys.argv[1:])
+ os.spawnlp(os.P_NOWAIT, "node", "node", "woses.js", root);
mtime = []
while True:
m = [os.stat(filename).st_mtime for filename in filenames]
if mtime != m:
handler()
mtime = m
try:
time.sleep(1)
except KeyboardInterrupt:
print
os.system("killall -v node")
break
diff --git a/woses.js b/woses.js
index d63c51a..e46394b 100644
--- a/woses.js
+++ b/woses.js
@@ -1,202 +1,220 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
wwwforms = require('./www-forms');
function parseUri(path) {
- sys.p(path);
var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(path);
if (parts) {
return {
filename: parts[1],
basename: parts[2],
ext: parts[4]
};
}
}
var config = {
port: 8080,
documentRoot: "./",
index: "index.html",
mimetypes: {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
},
validate: function () {
if (this.index.substr(0,1) != '/')
this.index = '/' + this.index;
if (this.documentRoot.substr(-1) != '/')
this.documentRoot += "/";
}
}
if (process.ARGV.length > 2) {
config.documentRoot = process.ARGV[2];
config.validate();
}
var confFile = config.documentRoot + ".woses-conf.js";
try {
var cf = require(config.documentRoot + ".woses-conf");
if (cf.mimetypes) {
process.mixin(config.mimetypes, cf.mimetypes);
delete cf.mimetypes;
}
process.mixin(config, cf);
config.validate();
} catch (e) {
// No config file is OK
}
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
if (config.logRequestHeaders)
sys.p(req.headers);
if (req.uri.path == '/')
req.uri.path = config.index;
+
+ res.respond = function (body) {
+ sys.p(this);
+ this.sendHeader(this.status || 200, this.headers);
+ this.body = body || this.body || "";
+ if (typeof this.body != 'string')
+ this.body = JSON.encode(this.body);
+ this.sendBody(this.body, this.encoding || 'utf8');
+ this.finish();
+ }
+
+ res.header = function(header, value) {
+ if (!this.headers) this.headers = [];
+ this.headers.push([header, value]);
+ }
var uri = parseUri(req.uri.path);
- if (!uri)
- return respond(400, null, "400: I have no idea what that is");
+ if (!uri) {
+ res.status = 400;
+ return res.respond("400: I have no idea what that is");
+ }
// Exclude ".." in uri
- if (req.uri.path.indexOf('..') >= 0 || uri.filename.substr(1) == ".")
- return respond(403, null, "403: Don't hack me, bro");
+ if (req.uri.path.indexOf('..') >= 0 || uri.filename.substr(1) == ".") {
+ res.status = 403;
+ return res.respond("403: Don't hack me, bro");
+ }
- var content_type = config.mimetypes[uri.ext] || "text/plain";
-
- var encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
-
- function respondWithStatic(callback) {
- var promise = posix.cat(config.documentRoot + uri.filename, encoding);
+ function respondWithStatic() {
+ var content_type = config.mimetypes[uri.ext] || "text/plain";
+ res.encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
+ var promise = posix.cat(config.documentRoot + uri.filename, res.encoding);
promise.addCallback(function(data) {
- headers = [['Content-Type', content_type],
- ['Content-Length', encoding === 'utf8' ?
- encodeURIComponent(data).replace(/%../g, 'x').length :
- data.length]];
+ res.header('Content-Type', content_type);
+ res.header('Content-Length', res.encoding === 'utf8' ?
+ encodeURIComponent(data).replace(/%../g, 'x').length :
+ data.length);
sys.puts(req.requestLine + " " + data.length);
- callback(200, headers, data, encoding);
+ res.respond(data);
});
promise.addErrback(function() {
sys.puts("Error 404: " + uri.filename);
- callback(404, [['Content-Type', 'text/plain']],
- '404: I looked but did not find.');
+ res.status = 404;
+ res.header('Content-Type', 'text/plain');
+ res.respond('404: I looked but did not find.');
});
}
- function respondWithPhp(callback) {
- var body = '';
+ function respondWithPhp() {
+ res.body = '';
var params = ['parp.php', uri.filename, '--dir=' + config.documentRoot];
for (var param in req.uri.params)
params.push(param + "=" + req.uri.params[param]);
this.bytesTotal = req.headers['content-length'];
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function() {
var form = wwwforms.decodeForm(req.body);
for (var param in form)
params.push(param + "=" + form[param]);
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
- body += data;
+ res.body += data;
} else {
- if (body.indexOf("<?xml") == 0)
- content_type = "application/xml";
- else
- content_type = "text/html";
- headers = [['Content-Type', content_type],
- ['Content-Length', body.length]];
- sys.puts(req.requestLine + " (php) " + body.length);
- callback((body.indexOf("404:") == 0) ? 404 : 200,
- headers, body, encoding);
+ res.header("Content-Type", (res.body.indexOf("<?xml") == 0) ?
+ "application/xml" : "text/html")
+ res.header("Content-Length", res.body.length);;
+ sys.puts(req.requestLine + " (php) " + res.body.length);
+ if (res.body.match(/^404:/))
+ res.status = 404;
+ res.respond();
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
- //callback(500, null, '500: Sombody said something shocking.');
+ //return res.respond('500: Sombody said something shocking.');
}
});
});
}
-
- function respond(status, headers, body, encoding) {
- sys.p(res);
- res.sendHeader(status, headers);
- res.sendBody(body, encoding || 'utf8');
- res.finish();
- }
if (uri.ext == "php") {
- respondWithPhp(respond);
+ respondWithPhp();
} else if (uri.filename.substr(-7) == "-rpc.js") {
- // TODO: need a better way to distinguish client & server js
- var script = require("./" + uri.basename);
- script.fetch(req, res, respond);
+ // TODO: use conf file to distinguish client & server js
+ try {
+ var script = require(config.documentRoot + uri.basename);
+ script.fetch(req, res);
+ } catch (e) {
+ res.status = 404
+ res.respond("404: In absentia. Or elsewhere.\n" +
+ sys.inspect(e));
+ }
} else if (uri.ext == "md") {
- sys.exec("Markdown.pl < " + uri.filename).addCallback(function (out,err) {
- respond(200, [], out);
+ sys.exec("Markdown.pl < " + config.documentRoot + uri.filename)
+ .addCallback(function (stdout, stderr) {
+ res.respond(stdout);})
+ .addErrback(function (code, stdout, stderr) {
+ res.status = 404;
+ res.respond("404: Mark my words. No such file.");
});
} else {
- respondWithStatic(respond);
+ respondWithStatic();
}
}).listen(config.port);
sys.puts('Woses running at http://127.0.0.1:' +
config.port + '/ in ' +
config.documentRoot);
|
grumdrig/woses
|
7de0c0733ff5e584bcda46b25780ce9a216e0869
|
Configuration through a conf file .woses-conf.js
|
diff --git a/serverloop.py b/serverloop.py
index 8884e07..6323ed8 100755
--- a/serverloop.py
+++ b/serverloop.py
@@ -1,42 +1,43 @@
#!/usr/bin/python
# Copyright (c) 2009, Eric Fredricksen <[email protected]>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
""" Run the server named herein or on command line, using node.
Whenever it changes, kill and restart. (See http://nodejs.org/)
This is useful during editing and testing of the server."""
import os, sys, time
-filenames = sys.argv[1:] or ["woses.js"]
+filenames = ["woses.js", ".woses-conf.js"]
def handler():
print "\n\n"
- os.system("killall -v node; node woses.js . &")
+ os.system("killall -v node");
+ os.spawnvp(os.P_NOWAIT, "node", ["node", "woses.js"] + sys.argv[1:])
mtime = []
while True:
m = [os.stat(filename).st_mtime for filename in filenames]
if mtime != m:
handler()
mtime = m
try:
time.sleep(1)
except KeyboardInterrupt:
print
os.system("killall -v node")
break
diff --git a/woses.js b/woses.js
index 11fb224..d63c51a 100644
--- a/woses.js
+++ b/woses.js
@@ -1,190 +1,202 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
-// Usage: node woses.js [--port PORT] DOCUMENT_ROOT/
+// Usage: node woses.js DOCUMENT_ROOT
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
wwwforms = require('./www-forms');
-function getopt(argv) {
- // Presume all --opt flags have 1 argument, all -o flags don't
- var opts = {};
- var i = 0;
- for (; i < argv.length; ++i) {
- if (argv[i].substr(0,2) == "--") {
- opts[argv[i]] = argv[i+1];
- ++i;
- } else if (argv[i].substr(0,1) == "-") {
- opts[argv[i]] = (opts[argv[i]] || 0) + 1;
- } else {
- break;
- }
+function parseUri(path) {
+ sys.p(path);
+ var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(path);
+ if (parts) {
+ return {
+ filename: parts[1],
+ basename: parts[2],
+ ext: parts[4]
+ };
}
- return [opts, argv.slice(i)];
}
-var oa = getopt(process.ARGV.slice(2));
-var opts = oa[0];
-var args = oa[1];
-
-var port = opts['--port'] || 8080;
-var index = opts['--index'] || "/index.html";
-if (index.substr(0,1) != '/')
- index = '/' + index;
-var documentRoot = args[0];
-if (documentRoot.substr(-1) != '/')
- documentRoot += "/";
-
+var config = {
+ port: 8080,
+ documentRoot: "./",
+ index: "index.html",
+ mimetypes: {
+ "css" : "text/css",
+ "html": "text/html",
+ "ico" : "image/vnd.microsoft.icon",
+ "jpg" : "image/jpeg",
+ "js" : "application/javascript",
+ "png" : "image/png",
+ "xml" : "application/xml",
+ "xul" : "application/vnd.mozilla.xul+xml",
+ },
+ validate: function () {
+ if (this.index.substr(0,1) != '/')
+ this.index = '/' + this.index;
+ if (this.documentRoot.substr(-1) != '/')
+ this.documentRoot += "/";
+ }
+}
-var filetypes = {
- "css" : "text/css",
- "html": "text/html",
- "ico" : "image/vnd.microsoft.icon",
- "jpg" : "image/jpeg",
- "js" : "application/javascript",
- "png" : "image/png",
- "xml" : "application/xml",
- "xul" : "application/vnd.mozilla.xul+xml",
-};
+if (process.ARGV.length > 2) {
+ config.documentRoot = process.ARGV[2];
+ config.validate();
+}
+var confFile = config.documentRoot + ".woses-conf.js";
+try {
+ var cf = require(config.documentRoot + ".woses-conf");
+ if (cf.mimetypes) {
+ process.mixin(config.mimetypes, cf.mimetypes);
+ delete cf.mimetypes;
+ }
+ process.mixin(config, cf);
+ config.validate();
+} catch (e) {
+ // No config file is OK
+}
+
http.createServer(function(req, res) {
- req.requestLine = req.method + " " + req.uri.full +
- " HTTP/" + req.httpVersion;
+ req.requestLine = req.method + " " + req.uri.full +
+ " HTTP/" + req.httpVersion;
- //sys.puts(sys.inspect(req.headers));
+ if (config.logRequestHeaders)
+ sys.p(req.headers);
- if (req.uri.path == '/')
- req.uri.path = index;
+ if (req.uri.path == '/')
+ req.uri.path = config.index;
- // Exclude ".." in uri
- if (req.uri.path.indexOf('..') >= 0)
- return respond(403, null, "403: Don't hack me, bro");
+ var uri = parseUri(req.uri.path);
+ if (!uri)
+ return respond(400, null, "400: I have no idea what that is");
- var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(req.uri.path);
- if (!parts)
- return respond(400, null, "400: I have no idea what that is");
+ // Exclude ".." in uri
+ if (req.uri.path.indexOf('..') >= 0 || uri.filename.substr(1) == ".")
+ return respond(403, null, "403: Don't hack me, bro");
- var filename = parts[1];
- var basename = parts[2];
- var ext = parts[4];
- var content_type = filetypes[ext] || "text/plain";
+ var content_type = config.mimetypes[uri.ext] || "text/plain";
+
+ var encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
+
+ function respondWithStatic(callback) {
+ var promise = posix.cat(config.documentRoot + uri.filename, encoding);
+ promise.addCallback(function(data) {
+ headers = [['Content-Type', content_type],
+ ['Content-Length', encoding === 'utf8' ?
+ encodeURIComponent(data).replace(/%../g, 'x').length :
+ data.length]];
+ sys.puts(req.requestLine + " " + data.length);
+ callback(200, headers, data, encoding);
+ });
+ promise.addErrback(function() {
+ sys.puts("Error 404: " + uri.filename);
+ callback(404, [['Content-Type', 'text/plain']],
+ '404: I looked but did not find.');
+ });
+ }
+
+ function respondWithPhp(callback) {
+ var body = '';
- var encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
+ var params = ['parp.php', uri.filename, '--dir=' + config.documentRoot];
+ for (var param in req.uri.params)
+ params.push(param + "=" + req.uri.params[param]);
+
+ this.bytesTotal = req.headers['content-length'];
- function respondWithStatic(callback) {
- var promise = posix.cat(documentRoot + filename, encoding);
- promise.addCallback(function(data) {
+ req.body = '';
+ req.addListener('body', function(chunk) {
+ req.pause();
+ req.body += chunk;
+ setTimeout(function() { req.resume(); });
+ });
+ req.addListener('complete', function() {
+ var form = wwwforms.decodeForm(req.body);
+ for (var param in form)
+ params.push(param + "=" + form[param]);
+ params.push("-s");
+ params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
+ params.push("HTTP_HOST=" + req.headers['host']);
+ params.push("REQUEST_URI=" + req.uri.full);
+ var promise = process.createChildProcess("php", params);
+ promise.addListener("output", function (data) {
+ req.pause();
+ if (data != null) {
+ body += data;
+ } else {
+ if (body.indexOf("<?xml") == 0)
+ content_type = "application/xml";
+ else
+ content_type = "text/html";
headers = [['Content-Type', content_type],
- ['Content-Length', encoding === 'utf8' ?
- encodeURIComponent(data).replace(/%../g, 'x').length :
- data.length]];
- sys.puts(req.requestLine + " " + data.length);
- callback(200, headers, data, encoding);
- });
- promise.addErrback(function() {
- sys.puts("Error 404: " + filename);
- callback(404, [['Content-Type', 'text/plain']],
- '404: I looked but did not find.');
- });
- }
-
- function respondWithPhp(callback) {
- var body = '';
-
- var params = ['parp.php', filename, '--dir=' + documentRoot];
- for (var param in req.uri.params)
- params.push(param + "=" + req.uri.params[param]);
-
- this.bytesTotal = req.headers['content-length'];
-
- req.body = '';
- req.addListener('body', function(chunk) {
- req.pause();
- req.body += chunk;
- setTimeout(function() { req.resume(); });
- });
- req.addListener('complete', function() {
- var form = wwwforms.decodeForm(req.body);
- for (var param in form)
- params.push(param + "=" + form[param]);
- params.push("-s");
- params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
- params.push("HTTP_HOST=" + req.headers['host']);
- params.push("REQUEST_URI=" + req.uri.full);
- var promise = process.createChildProcess("php", params);
- promise.addListener("output", function (data) {
- req.pause();
- if (data != null) {
- body += data;
- } else {
- if (body.indexOf("<?xml") == 0)
- content_type = "application/xml";
- else
- content_type = "text/html";
- headers = [['Content-Type', content_type],
- ['Content-Length', body.length]];
- sys.puts(req.requestLine + " (php) " + body.length);
- callback((body.indexOf("404:") == 0) ? 404 : 200,
- headers, body, encoding);
- }
- setTimeout(function(){req.resume();});
- });
- promise.addListener("error", function(content) {
- if (content != null) {
- sys.puts("STDERR (php): " + content);
- //callback(500, null, '500: Sombody said something shocking.');
- }
- });
- });
-
- }
-
- function respond(status, headers, body, encoding) {
- res.sendHeader(status, headers);
- res.sendBody(body, encoding || 'utf8');
- res.finish();
- }
-
- if (ext == "php") {
- respondWithPhp(respond);
- } else if (filename.substr(-7) == "-rpc.js") {
- // TODO: need a better way to distinguish client & server js
- var script = require("./" + basename);
- script.fetch(req, res, respond);
- } else if (ext == "md") {
- sys.exec("Markdown.pl < " + filename).addCallback(function (out,err) {
- respond(200, [], out);
+ ['Content-Length', body.length]];
+ sys.puts(req.requestLine + " (php) " + body.length);
+ callback((body.indexOf("404:") == 0) ? 404 : 200,
+ headers, body, encoding);
+ }
+ setTimeout(function(){req.resume();});
});
- } else {
- respondWithStatic(respond);
- }
+ promise.addListener("error", function(content) {
+ if (content != null) {
+ sys.puts("STDERR (php): " + content);
+ //callback(500, null, '500: Sombody said something shocking.');
+ }
+ });
+ });
- }).listen(port);
+ }
+
+ function respond(status, headers, body, encoding) {
+ sys.p(res);
+ res.sendHeader(status, headers);
+ res.sendBody(body, encoding || 'utf8');
+ res.finish();
+ }
+
+ if (uri.ext == "php") {
+ respondWithPhp(respond);
+ } else if (uri.filename.substr(-7) == "-rpc.js") {
+ // TODO: need a better way to distinguish client & server js
+ var script = require("./" + uri.basename);
+ script.fetch(req, res, respond);
+ } else if (uri.ext == "md") {
+ sys.exec("Markdown.pl < " + uri.filename).addCallback(function (out,err) {
+ respond(200, [], out);
+ });
+ } else {
+ respondWithStatic(respond);
+ }
+
+}).listen(config.port);
-sys.puts('Woses running at http://127.0.0.1:' + port + '/ in ' + documentRoot);
+sys.puts('Woses running at http://127.0.0.1:' +
+ config.port + '/ in ' +
+ config.documentRoot);
|
grumdrig/woses
|
5418124f2bfb979b10e69044211f19c8387e6337
|
Process Markdown files
|
diff --git a/README.md b/README.md
index b2de01c..412757d 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,10 @@
woses
=====
-HTTP server for static and PHP files via Node.js (See nodejs.org)
+HTTP server for static and PHP files via [Node](http://nodejs.org/)
Usage
-----
`$ node woses.js`
diff --git a/woses.js b/woses.js
index ab2daaa..11fb224 100644
--- a/woses.js
+++ b/woses.js
@@ -1,186 +1,190 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js [--port PORT] DOCUMENT_ROOT/
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
wwwforms = require('./www-forms');
function getopt(argv) {
// Presume all --opt flags have 1 argument, all -o flags don't
var opts = {};
var i = 0;
for (; i < argv.length; ++i) {
if (argv[i].substr(0,2) == "--") {
opts[argv[i]] = argv[i+1];
++i;
} else if (argv[i].substr(0,1) == "-") {
opts[argv[i]] = (opts[argv[i]] || 0) + 1;
} else {
break;
}
}
return [opts, argv.slice(i)];
}
var oa = getopt(process.ARGV.slice(2));
var opts = oa[0];
var args = oa[1];
var port = opts['--port'] || 8080;
var index = opts['--index'] || "/index.html";
if (index.substr(0,1) != '/')
index = '/' + index;
var documentRoot = args[0];
if (documentRoot.substr(-1) != '/')
documentRoot += "/";
var filetypes = {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
};
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
//sys.puts(sys.inspect(req.headers));
if (req.uri.path == '/')
req.uri.path = index;
// Exclude ".." in uri
if (req.uri.path.indexOf('..') >= 0)
return respond(403, null, "403: Don't hack me, bro");
var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(req.uri.path);
if (!parts)
return respond(400, null, "400: I have no idea what that is");
var filename = parts[1];
var basename = parts[2];
var ext = parts[4];
var content_type = filetypes[ext] || "text/plain";
var encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
function respondWithStatic(callback) {
var promise = posix.cat(documentRoot + filename, encoding);
promise.addCallback(function(data) {
headers = [['Content-Type', content_type],
['Content-Length', encoding === 'utf8' ?
encodeURIComponent(data).replace(/%../g, 'x').length :
data.length]];
sys.puts(req.requestLine + " " + data.length);
callback(200, headers, data, encoding);
});
promise.addErrback(function() {
sys.puts("Error 404: " + filename);
callback(404, [['Content-Type', 'text/plain']],
'404: I looked but did not find.');
});
}
function respondWithPhp(callback) {
var body = '';
var params = ['parp.php', filename, '--dir=' + documentRoot];
for (var param in req.uri.params)
params.push(param + "=" + req.uri.params[param]);
this.bytesTotal = req.headers['content-length'];
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function() {
var form = wwwforms.decodeForm(req.body);
for (var param in form)
params.push(param + "=" + form[param]);
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
body += data;
} else {
if (body.indexOf("<?xml") == 0)
content_type = "application/xml";
else
content_type = "text/html";
headers = [['Content-Type', content_type],
['Content-Length', body.length]];
sys.puts(req.requestLine + " (php) " + body.length);
callback((body.indexOf("404:") == 0) ? 404 : 200,
headers, body, encoding);
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//callback(500, null, '500: Sombody said something shocking.');
}
});
});
}
function respond(status, headers, body, encoding) {
res.sendHeader(status, headers);
res.sendBody(body, encoding || 'utf8');
res.finish();
}
if (ext == "php") {
respondWithPhp(respond);
} else if (filename.substr(-7) == "-rpc.js") {
// TODO: need a better way to distinguish client & server js
var script = require("./" + basename);
script.fetch(req, res, respond);
+ } else if (ext == "md") {
+ sys.exec("Markdown.pl < " + filename).addCallback(function (out,err) {
+ respond(200, [], out);
+ });
} else {
respondWithStatic(respond);
}
}).listen(port);
sys.puts('Woses running at http://127.0.0.1:' + port + '/ in ' + documentRoot);
|
grumdrig/woses
|
0ab9f8c9f0f816fd557ed236474cb4bc5cf41d4c
|
RPC mechanism for js
|
diff --git a/serverloop.py b/serverloop.py
index 2e8aff5..8884e07 100755
--- a/serverloop.py
+++ b/serverloop.py
@@ -1,42 +1,42 @@
#!/usr/bin/python
# Copyright (c) 2009, Eric Fredricksen <[email protected]>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
""" Run the server named herein or on command line, using node.
Whenever it changes, kill and restart. (See http://nodejs.org/)
This is useful during editing and testing of the server."""
import os, sys, time
filenames = sys.argv[1:] or ["woses.js"]
def handler():
print "\n\n"
- os.system("killall -v node; node woses.js ../pq9x/ &")
+ os.system("killall -v node; node woses.js . &")
mtime = []
while True:
m = [os.stat(filename).st_mtime for filename in filenames]
if mtime != m:
handler()
mtime = m
try:
time.sleep(1)
except KeyboardInterrupt:
print
os.system("killall -v node")
break
diff --git a/woses.js b/woses.js
index 81e8f48..ab2daaa 100644
--- a/woses.js
+++ b/woses.js
@@ -1,182 +1,186 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js [--port PORT] DOCUMENT_ROOT/
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
wwwforms = require('./www-forms');
function getopt(argv) {
// Presume all --opt flags have 1 argument, all -o flags don't
var opts = {};
var i = 0;
for (; i < argv.length; ++i) {
if (argv[i].substr(0,2) == "--") {
opts[argv[i]] = argv[i+1];
++i;
} else if (argv[i].substr(0,1) == "-") {
opts[argv[i]] = (opts[argv[i]] || 0) + 1;
} else {
break;
}
}
return [opts, argv.slice(i)];
}
var oa = getopt(process.ARGV.slice(2));
var opts = oa[0];
var args = oa[1];
var port = opts['--port'] || 8080;
var index = opts['--index'] || "/index.html";
if (index.substr(0,1) != '/')
index = '/' + index;
var documentRoot = args[0];
if (documentRoot.substr(-1) != '/')
documentRoot += "/";
var filetypes = {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
};
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
//sys.puts(sys.inspect(req.headers));
if (req.uri.path == '/')
req.uri.path = index;
// Exclude ".." in uri
if (req.uri.path.indexOf('..') >= 0)
return respond(403, null, "403: Don't hack me, bro");
- var parts = RegExp("^/(.+?(\\.([a-z]+))?)$")(req.uri.path);
+ var parts = RegExp("^/((.+?)(\\.([a-z]+))?)$")(req.uri.path);
if (!parts)
return respond(400, null, "400: I have no idea what that is");
var filename = parts[1];
- var ext = parts[3];
+ var basename = parts[2];
+ var ext = parts[4];
var content_type = filetypes[ext] || "text/plain";
var encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
function respondWithStatic(callback) {
var promise = posix.cat(documentRoot + filename, encoding);
promise.addCallback(function(data) {
headers = [['Content-Type', content_type],
['Content-Length', encoding === 'utf8' ?
encodeURIComponent(data).replace(/%../g, 'x').length :
data.length]];
sys.puts(req.requestLine + " " + data.length);
callback(200, headers, data, encoding);
});
promise.addErrback(function() {
sys.puts("Error 404: " + filename);
callback(404, [['Content-Type', 'text/plain']],
'404: I looked but did not find.');
});
}
-
function respondWithPhp(callback) {
var body = '';
var params = ['parp.php', filename, '--dir=' + documentRoot];
for (var param in req.uri.params)
params.push(param + "=" + req.uri.params[param]);
this.bytesTotal = req.headers['content-length'];
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function() {
var form = wwwforms.decodeForm(req.body);
for (var param in form)
params.push(param + "=" + form[param]);
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
body += data;
} else {
if (body.indexOf("<?xml") == 0)
content_type = "application/xml";
else
content_type = "text/html";
headers = [['Content-Type', content_type],
['Content-Length', body.length]];
sys.puts(req.requestLine + " (php) " + body.length);
callback((body.indexOf("404:") == 0) ? 404 : 200,
headers, body, encoding);
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//callback(500, null, '500: Sombody said something shocking.');
}
});
});
}
function respond(status, headers, body, encoding) {
res.sendHeader(status, headers);
res.sendBody(body, encoding || 'utf8');
res.finish();
}
if (ext == "php") {
respondWithPhp(respond);
+ } else if (filename.substr(-7) == "-rpc.js") {
+ // TODO: need a better way to distinguish client & server js
+ var script = require("./" + basename);
+ script.fetch(req, res, respond);
} else {
respondWithStatic(respond);
}
}).listen(port);
sys.puts('Woses running at http://127.0.0.1:' + port + '/ in ' + documentRoot);
|
grumdrig/woses
|
5be1043f2fd10a2bf761212ee76ccbe6524b0d5d
|
Command-line flag to specify a directory index
|
diff --git a/woses.js b/woses.js
index bca21c3..81e8f48 100644
--- a/woses.js
+++ b/woses.js
@@ -1,179 +1,182 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//
// HTTP server for static and PHP files via Node.js (nodejs.org)
// See http://bitbucket.org/grumdrig/woses/wiki/Home
//
// Usage: node woses.js [--port PORT] DOCUMENT_ROOT/
//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
wwwforms = require('./www-forms');
function getopt(argv) {
// Presume all --opt flags have 1 argument, all -o flags don't
var opts = {};
var i = 0;
for (; i < argv.length; ++i) {
if (argv[i].substr(0,2) == "--") {
opts[argv[i]] = argv[i+1];
++i;
} else if (argv[i].substr(0,1) == "-") {
opts[argv[i]] = (opts[argv[i]] || 0) + 1;
} else {
break;
}
}
return [opts, argv.slice(i)];
}
var oa = getopt(process.ARGV.slice(2));
var opts = oa[0];
var args = oa[1];
var port = opts['--port'] || 8080;
+var index = opts['--index'] || "/index.html";
+if (index.substr(0,1) != '/')
+ index = '/' + index;
var documentRoot = args[0];
if (documentRoot.substr(-1) != '/')
documentRoot += "/";
var filetypes = {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
};
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
//sys.puts(sys.inspect(req.headers));
if (req.uri.path == '/')
- req.uri.path = '/index.php';
+ req.uri.path = index;
// Exclude ".." in uri
if (req.uri.path.indexOf('..') >= 0)
return respond(403, null, "403: Don't hack me, bro");
var parts = RegExp("^/(.+?(\\.([a-z]+))?)$")(req.uri.path);
if (!parts)
return respond(400, null, "400: I have no idea what that is");
var filename = parts[1];
var ext = parts[3];
var content_type = filetypes[ext] || "text/plain";
var encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
function respondWithStatic(callback) {
var promise = posix.cat(documentRoot + filename, encoding);
promise.addCallback(function(data) {
headers = [['Content-Type', content_type],
['Content-Length', encoding === 'utf8' ?
encodeURIComponent(data).replace(/%../g, 'x').length :
data.length]];
sys.puts(req.requestLine + " " + data.length);
callback(200, headers, data, encoding);
});
promise.addErrback(function() {
sys.puts("Error 404: " + filename);
callback(404, [['Content-Type', 'text/plain']],
'404: I looked but did not find.');
});
}
function respondWithPhp(callback) {
var body = '';
var params = ['parp.php', filename, '--dir=' + documentRoot];
for (var param in req.uri.params)
params.push(param + "=" + req.uri.params[param]);
this.bytesTotal = req.headers['content-length'];
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function() {
var form = wwwforms.decodeForm(req.body);
for (var param in form)
params.push(param + "=" + form[param]);
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
body += data;
} else {
if (body.indexOf("<?xml") == 0)
content_type = "application/xml";
else
content_type = "text/html";
headers = [['Content-Type', content_type],
['Content-Length', body.length]];
sys.puts(req.requestLine + " (php) " + body.length);
callback((body.indexOf("404:") == 0) ? 404 : 200,
headers, body, encoding);
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//callback(500, null, '500: Sombody said something shocking.');
}
});
});
}
function respond(status, headers, body, encoding) {
res.sendHeader(status, headers);
res.sendBody(body, encoding || 'utf8');
res.finish();
}
if (ext == "php") {
respondWithPhp(respond);
} else {
respondWithStatic(respond);
}
}).listen(port);
sys.puts('Woses running at http://127.0.0.1:' + port + '/ in ' + documentRoot);
|
grumdrig/woses
|
3363458bfd0bf1f2d54d399f9ad793b653b0a3f3
|
Better handling of error conditions, command line args
|
diff --git a/parp.php b/parp.php
index 646b669..9e213a4 100644
--- a/parp.php
+++ b/parp.php
@@ -1,63 +1,67 @@
<?
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// Command-line use of PHP files as if from a webserver.
//
// Usage: php parp.php file.php arg1=value1 arg2=value2...
// Simulates HTTP request for /file.php?arg1=value1&arg2=value2...
// Opts:
// -r Subsequent key=value pairs are stored in $_REQUEST (default)
// -s Subsequent key=value pairs are stored in $_SERVER
// -S Subsequent key=value pairs are stored in $_SESSION
// --dir=DIR Change directory to specified document root DIR
//fputs(STDERR, var_export($argv, TRUE));
session_start();
$_SESSION['nickname'] = 'Nicholas'; // TODO:
$_SESSION['player'] = 1; // TEMPORARY
$target =& $_REQUEST;
for ($i = 2; $i < count($argv); ++$i) {
if ($argv[$i] == "-s") {
$target =& $_SERVER;
} else if ($argv[$i] == "-r") {
$target =& $_REQUEST;
} else if ($argv[$i] == "-S") {
$target =& $_SESSION;
} else {
$v = explode("=", $argv[$i]);
if ($v[0] == "--dir")
chdir($v[1]);
else
$target[$v[0]] = $v[1];
}
}
//ob_start();
-include($argv[1]);
+$included = @include($argv[1]);
//$output = ob_get_contents();
//ob_end_clean();
//print $ouput;
+if (!$included) {
+ print "404: No sign of it";
+}
+
//fputs(STDERR, $output);
?>
\ No newline at end of file
diff --git a/serverloop.py b/serverloop.py
index ebfc803..2e8aff5 100755
--- a/serverloop.py
+++ b/serverloop.py
@@ -1,42 +1,42 @@
#!/usr/bin/python
# Copyright (c) 2009, Eric Fredricksen <[email protected]>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
""" Run the server named herein or on command line, using node.
Whenever it changes, kill and restart. (See http://nodejs.org/)
This is useful during editing and testing of the server."""
import os, sys, time
filenames = sys.argv[1:] or ["woses.js"]
def handler():
print "\n\n"
- os.system("killall -v node; node %s &" % filenames[0])
+ os.system("killall -v node; node woses.js ../pq9x/ &")
mtime = []
while True:
m = [os.stat(filename).st_mtime for filename in filenames]
if mtime != m:
handler()
mtime = m
try:
time.sleep(1)
except KeyboardInterrupt:
print
os.system("killall -v node")
break
diff --git a/woses.js b/woses.js
index c7a654a..bca21c3 100644
--- a/woses.js
+++ b/woses.js
@@ -1,146 +1,179 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
+//
// HTTP server for static and PHP files via Node.js (nodejs.org)
-// Usage: node woses.js
-// Configure by editing the two lines below:
-
-var port = 8080;
-var documentRoot = "../pq9x/";
+// See http://bitbucket.org/grumdrig/woses/wiki/Home
+//
+// Usage: node woses.js [--port PORT] DOCUMENT_ROOT/
+//
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
wwwforms = require('./www-forms');
+function getopt(argv) {
+ // Presume all --opt flags have 1 argument, all -o flags don't
+ var opts = {};
+ var i = 0;
+ for (; i < argv.length; ++i) {
+ if (argv[i].substr(0,2) == "--") {
+ opts[argv[i]] = argv[i+1];
+ ++i;
+ } else if (argv[i].substr(0,1) == "-") {
+ opts[argv[i]] = (opts[argv[i]] || 0) + 1;
+ } else {
+ break;
+ }
+ }
+ return [opts, argv.slice(i)];
+}
+
+
+var oa = getopt(process.ARGV.slice(2));
+var opts = oa[0];
+var args = oa[1];
+
+var port = opts['--port'] || 8080;
+var documentRoot = args[0];
+if (documentRoot.substr(-1) != '/')
+ documentRoot += "/";
+
+
+var filetypes = {
+ "css" : "text/css",
+ "html": "text/html",
+ "ico" : "image/vnd.microsoft.icon",
+ "jpg" : "image/jpeg",
+ "js" : "application/javascript",
+ "png" : "image/png",
+ "xml" : "application/xml",
+ "xul" : "application/vnd.mozilla.xul+xml",
+};
+
+
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
//sys.puts(sys.inspect(req.headers));
if (req.uri.path == '/')
req.uri.path = '/index.php';
- // TODO: exclude ".." in uri
- var parts = RegExp("^/(.+?\\.([a-z]+))$")(req.uri.path);
- if (!parts) {
- res.sendHeader(404);
- res.sendBody("404: I have no idea what you're talking about", 'utf8');
- res.finish();
- return;
- }
+ // Exclude ".." in uri
+ if (req.uri.path.indexOf('..') >= 0)
+ return respond(403, null, "403: Don't hack me, bro");
+
+ var parts = RegExp("^/(.+?(\\.([a-z]+))?)$")(req.uri.path);
+ if (!parts)
+ return respond(400, null, "400: I have no idea what that is");
+
var filename = parts[1];
- var ext = parts[2];
-
- var filetypes = {
- "css" : "text/css",
- "html": "text/html",
- "ico" : "image/vnd.microsoft.icon",
- "jpg" : "image/jpeg",
- "js" : "application/javascript",
- "png" : "image/png",
- "xml" : "application/xml",
- "xul" : "application/vnd.mozilla.xul+xml",
- };
- var content_type = filetypes[ext] || "text/html";
+ var ext = parts[3];
+ var content_type = filetypes[ext] || "text/plain";
var encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
function respondWithStatic(callback) {
var promise = posix.cat(documentRoot + filename, encoding);
promise.addCallback(function(data) {
headers = [['Content-Type', content_type],
['Content-Length', encoding === 'utf8' ?
encodeURIComponent(data).replace(/%../g, 'x').length :
data.length]];
sys.puts(req.requestLine + " " + data.length);
callback(200, headers, data, encoding);
});
promise.addErrback(function() {
sys.puts("Error 404: " + filename);
callback(404, [['Content-Type', 'text/plain']],
'404: I looked but did not find.');
});
}
function respondWithPhp(callback) {
var body = '';
var params = ['parp.php', filename, '--dir=' + documentRoot];
for (var param in req.uri.params)
params.push(param + "=" + req.uri.params[param]);
this.bytesTotal = req.headers['content-length'];
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function() {
var form = wwwforms.decodeForm(req.body);
for (var param in form)
params.push(param + "=" + form[param]);
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
body += data;
} else {
- if (body.match("^<\\?xml"))
+ if (body.indexOf("<?xml") == 0)
content_type = "application/xml";
+ else
+ content_type = "text/html";
headers = [['Content-Type', content_type],
['Content-Length', body.length]];
sys.puts(req.requestLine + " (php) " + body.length);
- callback(200, headers, body, encoding);
+ callback((body.indexOf("404:") == 0) ? 404 : 200,
+ headers, body, encoding);
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//callback(500, null, '500: Sombody said something shocking.');
}
});
});
}
function respond(status, headers, body, encoding) {
res.sendHeader(status, headers);
res.sendBody(body, encoding || 'utf8');
res.finish();
}
if (ext == "php") {
respondWithPhp(respond);
} else {
respondWithStatic(respond);
}
}).listen(port);
-sys.puts('Woses running at http://127.0.0.1:' + port + '/');
+
+sys.puts('Woses running at http://127.0.0.1:' + port + '/ in ' + documentRoot);
|
grumdrig/woses
|
4a72f3079e487667ebac5eabd615d284a6f41684
|
Fix race condition. Point to www-forms.
|
diff --git a/woses.js b/woses.js
index 16daea5..c7a654a 100644
--- a/woses.js
+++ b/woses.js
@@ -1,145 +1,146 @@
/*
Copyright (c) 2009, Eric Fredricksen <[email protected]>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// HTTP server for static and PHP files via Node.js (nodejs.org)
// Usage: node woses.js
// Configure by editing the two lines below:
var port = 8080;
var documentRoot = "../pq9x/";
var
sys = require('sys'),
posix = require('posix'),
http = require('http'),
- wwwforms = require('./coltrane/module/www-forms');
+ wwwforms = require('./www-forms');
http.createServer(function(req, res) {
req.requestLine = req.method + " " + req.uri.full +
" HTTP/" + req.httpVersion;
//sys.puts(sys.inspect(req.headers));
if (req.uri.path == '/')
req.uri.path = '/index.php';
- var parts = RegExp("^/([a-z\\.]+?\\.([a-z]+))$")(req.uri.path);
+ // TODO: exclude ".." in uri
+ var parts = RegExp("^/(.+?\\.([a-z]+))$")(req.uri.path);
if (!parts) {
res.sendHeader(404);
res.sendBody("404: I have no idea what you're talking about", 'utf8');
res.finish();
return;
}
var filename = parts[1];
var ext = parts[2];
- filetypes = {
+ var filetypes = {
"css" : "text/css",
"html": "text/html",
"ico" : "image/vnd.microsoft.icon",
"jpg" : "image/jpeg",
"js" : "application/javascript",
"png" : "image/png",
"xml" : "application/xml",
"xul" : "application/vnd.mozilla.xul+xml",
};
- content_type = filetypes[ext] || "text/html";
+ var content_type = filetypes[ext] || "text/html";
var encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
function respondWithStatic(callback) {
var promise = posix.cat(documentRoot + filename, encoding);
promise.addCallback(function(data) {
headers = [['Content-Type', content_type],
['Content-Length', encoding === 'utf8' ?
encodeURIComponent(data).replace(/%../g, 'x').length :
data.length]];
sys.puts(req.requestLine + " " + data.length);
callback(200, headers, data, encoding);
});
promise.addErrback(function() {
sys.puts("Error 404: " + filename);
callback(404, [['Content-Type', 'text/plain']],
'404: I looked but did not find.');
});
}
function respondWithPhp(callback) {
- body = '';
+ var body = '';
var params = ['parp.php', filename, '--dir=' + documentRoot];
for (var param in req.uri.params)
params.push(param + "=" + req.uri.params[param]);
this.bytesTotal = req.headers['content-length'];
req.body = '';
req.addListener('body', function(chunk) {
req.pause();
req.body += chunk;
setTimeout(function() { req.resume(); });
});
req.addListener('complete', function() {
var form = wwwforms.decodeForm(req.body);
for (var param in form)
params.push(param + "=" + form[param]);
params.push("-s");
params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
params.push("HTTP_HOST=" + req.headers['host']);
params.push("REQUEST_URI=" + req.uri.full);
var promise = process.createChildProcess("php", params);
promise.addListener("output", function (data) {
req.pause();
if (data != null) {
body += data;
} else {
if (body.match("^<\\?xml"))
content_type = "application/xml";
headers = [['Content-Type', content_type],
['Content-Length', body.length]];
sys.puts(req.requestLine + " (php) " + body.length);
callback(200, headers, body, encoding);
}
setTimeout(function(){req.resume();});
});
promise.addListener("error", function(content) {
if (content != null) {
sys.puts("STDERR (php): " + content);
//callback(500, null, '500: Sombody said something shocking.');
}
});
});
}
function respond(status, headers, body, encoding) {
res.sendHeader(status, headers);
res.sendBody(body, encoding || 'utf8');
res.finish();
}
if (ext == "php") {
respondWithPhp(respond);
} else {
respondWithStatic(respond);
}
}).listen(port);
sys.puts('Woses running at http://127.0.0.1:' + port + '/');
|
grumdrig/woses
|
f3d859cd0ea79876a7eac737201bb4252167bfab
|
Adding required www-forms file
|
diff --git a/www-forms.js b/www-forms.js
new file mode 100644
index 0000000..022a5be
--- /dev/null
+++ b/www-forms.js
@@ -0,0 +1,61 @@
+/*
+Copyright (c) 2009 Hagen Overdick
+
+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.
+*/
+
+function decode(token) {
+ return decodeURIComponent(token.replace(/\+/g, " "));
+}
+
+function parseToken(token) {
+ return token.split("=").map(decode);
+}
+
+function internalSetValue(target, key, value, force) {
+ var arrayTest = key.match(/(.+?)\[(.*)\]/);
+ if (arrayTest) {
+ target = (target[arrayTest[1]] = target[arrayTest[1]] || []);
+ target = target[arrayTest[2]] = value;
+ } else {
+ target = (target[key] = force ? value : target[key] || value);
+ }
+ return target;
+}
+
+function setValue(target, key, value) {
+ var subkeys = key.split(".");
+ var valueKey = subkeys.pop();
+
+ for (var ii = 0; ii < subkeys.length; ii++) {
+ target = internalSetValue(target, subkeys[ii], {}, false);
+ }
+
+ internalSetValue(target, valueKey, value, true);
+}
+
+exports.decodeForm = function(data) {
+ var result = {};
+ if (data && data.split) {
+ data.split("&").map(parseToken).forEach(function(token) {
+ setValue(result, token[0], token[1]);
+ })
+ }
+ return result;
+}
\ No newline at end of file
|
grumdrig/woses
|
73b7ceb5fafe65ec2a50c190a2096294ad4582f5
|
Added README
|
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..b2de01c
--- /dev/null
+++ b/README.md
@@ -0,0 +1,10 @@
+woses
+=====
+
+HTTP server for static and PHP files via Node.js (See nodejs.org)
+
+Usage
+-----
+
+`$ node woses.js`
+
|
grumdrig/woses
|
1397ee2199efc4cc83463569eac03d56da056b99
|
Inital commit of woses: node-based static and PHP webserver
|
diff --git a/parp.php b/parp.php
new file mode 100644
index 0000000..646b669
--- /dev/null
+++ b/parp.php
@@ -0,0 +1,63 @@
+<?
+/*
+Copyright (c) 2009, Eric Fredricksen <[email protected]>
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+*/
+
+// Command-line use of PHP files as if from a webserver.
+//
+// Usage: php parp.php file.php arg1=value1 arg2=value2...
+// Simulates HTTP request for /file.php?arg1=value1&arg2=value2...
+// Opts:
+// -r Subsequent key=value pairs are stored in $_REQUEST (default)
+// -s Subsequent key=value pairs are stored in $_SERVER
+// -S Subsequent key=value pairs are stored in $_SESSION
+// --dir=DIR Change directory to specified document root DIR
+
+
+//fputs(STDERR, var_export($argv, TRUE));
+
+session_start();
+
+$_SESSION['nickname'] = 'Nicholas'; // TODO:
+$_SESSION['player'] = 1; // TEMPORARY
+
+$target =& $_REQUEST;
+
+for ($i = 2; $i < count($argv); ++$i) {
+ if ($argv[$i] == "-s") {
+ $target =& $_SERVER;
+ } else if ($argv[$i] == "-r") {
+ $target =& $_REQUEST;
+ } else if ($argv[$i] == "-S") {
+ $target =& $_SESSION;
+ } else {
+ $v = explode("=", $argv[$i]);
+ if ($v[0] == "--dir")
+ chdir($v[1]);
+ else
+ $target[$v[0]] = $v[1];
+ }
+}
+
+//ob_start();
+include($argv[1]);
+//$output = ob_get_contents();
+//ob_end_clean();
+
+//print $ouput;
+
+//fputs(STDERR, $output);
+
+?>
\ No newline at end of file
diff --git a/serverloop.py b/serverloop.py
new file mode 100755
index 0000000..ebfc803
--- /dev/null
+++ b/serverloop.py
@@ -0,0 +1,42 @@
+#!/usr/bin/python
+
+# Copyright (c) 2009, Eric Fredricksen <[email protected]>
+#
+# Permission to use, copy, modify, and/or distribute this software for any
+# purpose with or without fee is hereby granted, provided that the above
+# copyright notice and this permission notice appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+""" Run the server named herein or on command line, using node.
+Whenever it changes, kill and restart. (See http://nodejs.org/)
+
+This is useful during editing and testing of the server."""
+
+
+import os, sys, time
+
+filenames = sys.argv[1:] or ["woses.js"]
+
+def handler():
+ print "\n\n"
+ os.system("killall -v node; node %s &" % filenames[0])
+
+mtime = []
+while True:
+ m = [os.stat(filename).st_mtime for filename in filenames]
+ if mtime != m:
+ handler()
+ mtime = m
+ try:
+ time.sleep(1)
+ except KeyboardInterrupt:
+ print
+ os.system("killall -v node")
+ break
diff --git a/woses.js b/woses.js
new file mode 100644
index 0000000..16daea5
--- /dev/null
+++ b/woses.js
@@ -0,0 +1,145 @@
+/*
+Copyright (c) 2009, Eric Fredricksen <[email protected]>
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+*/
+
+// HTTP server for static and PHP files via Node.js (nodejs.org)
+// Usage: node woses.js
+// Configure by editing the two lines below:
+
+var port = 8080;
+var documentRoot = "../pq9x/";
+
+var
+ sys = require('sys'),
+ posix = require('posix'),
+ http = require('http'),
+ wwwforms = require('./coltrane/module/www-forms');
+
+
+http.createServer(function(req, res) {
+
+ req.requestLine = req.method + " " + req.uri.full +
+ " HTTP/" + req.httpVersion;
+
+ //sys.puts(sys.inspect(req.headers));
+
+ if (req.uri.path == '/')
+ req.uri.path = '/index.php';
+
+ var parts = RegExp("^/([a-z\\.]+?\\.([a-z]+))$")(req.uri.path);
+ if (!parts) {
+ res.sendHeader(404);
+ res.sendBody("404: I have no idea what you're talking about", 'utf8');
+ res.finish();
+ return;
+ }
+ var filename = parts[1];
+ var ext = parts[2];
+
+ filetypes = {
+ "css" : "text/css",
+ "html": "text/html",
+ "ico" : "image/vnd.microsoft.icon",
+ "jpg" : "image/jpeg",
+ "js" : "application/javascript",
+ "png" : "image/png",
+ "xml" : "application/xml",
+ "xul" : "application/vnd.mozilla.xul+xml",
+ };
+ content_type = filetypes[ext] || "text/html";
+
+ var encoding = (content_type.slice(0,4) === 'text' ? 'utf8' : 'binary');
+
+ function respondWithStatic(callback) {
+ var promise = posix.cat(documentRoot + filename, encoding);
+ promise.addCallback(function(data) {
+ headers = [['Content-Type', content_type],
+ ['Content-Length', encoding === 'utf8' ?
+ encodeURIComponent(data).replace(/%../g, 'x').length :
+ data.length]];
+ sys.puts(req.requestLine + " " + data.length);
+ callback(200, headers, data, encoding);
+ });
+ promise.addErrback(function() {
+ sys.puts("Error 404: " + filename);
+ callback(404, [['Content-Type', 'text/plain']],
+ '404: I looked but did not find.');
+ });
+ }
+
+
+ function respondWithPhp(callback) {
+ body = '';
+
+ var params = ['parp.php', filename, '--dir=' + documentRoot];
+ for (var param in req.uri.params)
+ params.push(param + "=" + req.uri.params[param]);
+
+ this.bytesTotal = req.headers['content-length'];
+
+ req.body = '';
+ req.addListener('body', function(chunk) {
+ req.pause();
+ req.body += chunk;
+ setTimeout(function() { req.resume(); });
+ });
+ req.addListener('complete', function() {
+ var form = wwwforms.decodeForm(req.body);
+ for (var param in form)
+ params.push(param + "=" + form[param]);
+ params.push("-s");
+ params.push("HTTP_USER_AGENT=" + req.headers['user-agent']);
+ params.push("HTTP_HOST=" + req.headers['host']);
+ params.push("REQUEST_URI=" + req.uri.full);
+ var promise = process.createChildProcess("php", params);
+ promise.addListener("output", function (data) {
+ req.pause();
+ if (data != null) {
+ body += data;
+ } else {
+ if (body.match("^<\\?xml"))
+ content_type = "application/xml";
+ headers = [['Content-Type', content_type],
+ ['Content-Length', body.length]];
+ sys.puts(req.requestLine + " (php) " + body.length);
+ callback(200, headers, body, encoding);
+ }
+ setTimeout(function(){req.resume();});
+ });
+ promise.addListener("error", function(content) {
+ if (content != null) {
+ sys.puts("STDERR (php): " + content);
+ //callback(500, null, '500: Sombody said something shocking.');
+ }
+ });
+ });
+
+ }
+
+ function respond(status, headers, body, encoding) {
+ res.sendHeader(status, headers);
+ res.sendBody(body, encoding || 'utf8');
+ res.finish();
+ }
+
+ if (ext == "php") {
+ respondWithPhp(respond);
+ } else {
+ respondWithStatic(respond);
+ }
+
+ }).listen(port);
+
+sys.puts('Woses running at http://127.0.0.1:' + port + '/');
|
markpasc/mt-plugin-action-streams
|
b267a2fdb91912c795bf38239ed32886478f03b1
|
Fix the Delicious profile; Bumped to version 2.2.1.
|
diff --git a/plugins/ActionStreams/config.yaml b/plugins/ActionStreams/config.yaml
index b73551f..fc42b70 100644
--- a/plugins/ActionStreams/config.yaml
+++ b/plugins/ActionStreams/config.yaml
@@ -1,198 +1,198 @@
name: Action Streams
id: ActionStreams
key: ActionStreams
author_link: http://www.sixapart.com/
author_name: Six Apart Ltd.
description: <MT_TRANS phrase="Manages authors' accounts and actions on sites elsewhere around the web">
schema_version: 16
-version: 2.2
+version: 2.2.1
plugin_link: http://www.sixapart.com/
settings:
rebuild_for_action_stream_events:
Default: 0
Scope: blog
l10n_class: ActionStreams::L10N
blog_config_template: blog_config_template.tmpl
init_app: $ActionStreams::ActionStreams::Init::init_app
applications:
cms:
methods:
list_profileevent: $ActionStreams::ActionStreams::Plugin::list_profileevent
other_profiles: $ActionStreams::ActionStreams::Plugin::other_profiles
dialog_add_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile
dialog_edit_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile
add_other_profile: $ActionStreams::ActionStreams::Plugin::add_other_profile
edit_other_profile: $ActionStreams::ActionStreams::Plugin::edit_other_profile
remove_other_profile: $ActionStreams::ActionStreams::Plugin::remove_other_profile
itemset_update_profiles: $ActionStreams::ActionStreams::Plugin::itemset_update_profiles
itemset_hide_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_events
itemset_show_events: $ActionStreams::ActionStreams::Plugin::itemset_show_events
itemset_hide_all_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events
itemset_show_all_events: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events
community:
methods:
profile_add_external_profile: $ActionStreams::ActionStreams::Plugin::profile_add_external_profile
profile_delete_external_profile: $ActionStreams::ActionStreams::Plugin::profile_delete_external_profile
callbacks:
post_add_profile: $ActionStreams::ActionStreams::Plugin::profile_first_update_events
callbacks:
MT::App::CMS::template_param.edit_author: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::template_param.list_member: $ActionStreams::ActionStreams::Plugin::param_list_member
MT::App::CMS::template_param.other_profiles: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::template_param.list_profileevent: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::post_add_profile: $ActionStreams::ActionStreams::Plugin::first_profile_update
post_action_streams_task: $ActionStreams::ActionStreams::Plugin::rebuild_action_stream_blogs
pre_build_action_streams_event.flickr_favorites: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail
pre_build_action_streams_event.flickr_photos: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail
pre_build_action_streams_event.gametap_scores: $ActionStreams::ActionStreams::Fix::gametap_score_stuff
pre_build_action_streams_event.googlereader_links: $ActionStreams::ActionStreams::Fix::googlereader_link_links
pre_build_action_streams_event.identica_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name
pre_build_action_streams_event.iminta_links: $ActionStreams::ActionStreams::Fix::iminta_link_title
pre_build_action_streams_event.instructables_favorites: $ActionStreams::ActionStreams::Fix::instructables_favorites_thumbnails
pre_build_action_streams_event.iusethis_events: $ActionStreams::ActionStreams::Fix::iusethis_event_title
pre_build_action_streams_event.kongregate_achievements: $ActionStreams::ActionStreams::Fix::kongregate_achievement_title_thumb
pre_build_action_streams_event.magnolia_links: $ActionStreams::ActionStreams::Fix::magnolia_link_notes
pre_build_action_streams_event.metafilter_favorites: $ActionStreams::ActionStreams::Fix::metafilter_favorites_titles
pre_build_action_streams_event.netflix_queue: $ActionStreams::ActionStreams::Fix::netflix_queue_prefix_thumb
pre_build_action_streams_event.netflix_recent: $ActionStreams::ActionStreams::Fix::netflix_recent_prefix_thumb
pre_build_action_streams_event.p0pulist_stuff: $ActionStreams::ActionStreams::Fix::p0pulist_stuff_urls
pre_build_action_streams_event.twitter_favorites: $ActionStreams::ActionStreams::Fix::twitter_favorite_author
pre_build_action_streams_event.twitter_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name
pre_build_action_streams_event.typepad_comments: $ActionStreams::ActionStreams::Fix::typepad_comment_titles
pre_build_action_streams_event.wists_wists: $ActionStreams::ActionStreams::Fix::wists_thumb
filter_action_streams_event.nytimes_links: $ActionStreams::ActionStreams::Fix::nytimes_links_titles
object_types:
profileevent: ActionStreams::Event
as: ActionStreams::Event
as_ua_cache: ActionStreams::UserAgent::Cache
list_actions:
profileevent:
hide_all:
label: Hide All
order: 100
js: finishPluginActionAll
code: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events
continue_prompt_handler: >
sub { MT->translate('Are you sure you want to hide EVERY event in EVERY action stream?') }
show_all:
label: Show All
order: 200
js: finishPluginActionAll
code: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events
continue_prompt_handler: >
sub { MT->translate('Are you sure you want to show EVERY event in EVERY action stream?') }
delete:
label: Delete
order: 300
code: $core::MT::App::CMS::delete
continue_prompt_handler: >
sub { MT->translate('Deleted events that are still available from the remote service will be added back in the next scan. Only events that are no longer available from your profile will remain deleted. Are you sure you want to delete the selected event(s)?') }
tags:
function:
StreamAction: $ActionStreams::ActionStreams::Tags::stream_action
StreamActionID: $ActionStreams::ActionStreams::Tags::stream_action_id
StreamActionVar: $ActionStreams::ActionStreams::Tags::stream_action_var
StreamActionDate: $ActionStreams::ActionStreams::Tags::stream_action_date
StreamActionModifiedDate: $ActionStreams::ActionStreams::Tags::stream_action_modified_date
StreamActionTitle: $ActionStreams::ActionStreams::Tags::stream_action_title
StreamActionURL: $ActionStreams::ActionStreams::Tags::stream_action_url
StreamActionThumbnailURL: $ActionStreams::ActionStreams::Tags::stream_action_thumbnail_url
StreamActionVia: $ActionStreams::ActionStreams::Tags::stream_action_via
OtherProfileVar: $ActionStreams::ActionStreams::Tags::other_profile_var
block:
ActionStreams: $ActionStreams::ActionStreams::Tags::action_streams
StreamActionTags: $ActionStreams::ActionStreams::Tags::stream_action_tags
OtherProfiles: $ActionStreams::ActionStreams::Tags::other_profiles
ProfileServices: $ActionStreams::ActionStreams::Tags::profile_services
StreamActionRollup: $ActionStreams::ActionStreams::Tags::stream_action_rollup
tasks:
UpdateEvents:
frequency: 1800
label: Poll for new events
code: $ActionStreams::ActionStreams::Plugin::update_events
task_workers:
UpdateEvents:
label: Update Events
class: ActionStreams::Worker
widgets:
asotd:
label: Recent Actions
template: widget_recent.mtml
permission: post
singular: 1
set: sidebar
handler: $ActionStreams::ActionStreams::Plugin::widget_recent
condition: $ActionStreams::ActionStreams::Plugin::widget_blog_dashboard_only
template_sets:
streams:
label: Action Stream
base_path: 'blog_tmpl'
base_css: themes-base/blog.css
order: 100
templates:
index:
main_index:
label: Main Index (Recent Actions)
outfile: index.html
rebuild_me: 1
archive:
label: Action Archive
outfile: archive.html
rebuild_me: 1
styles:
label: Stylesheet
outfile: styles.css
rebuild_me: 1
feed_recent:
label: Feed - Recent Activity
outfile: atom.xml
rebuild_me: 1
module:
html_head:
label: HTML Head
banner_header:
label: Banner Header
banner_footer:
label: Banner Footer
sidebar:
label: Sidebar
widget:
elsewhere:
label: Find Authors Elsewhere
actions:
label: Recent Actions
widgetset:
2column_layout_sidebar:
label: 2-column layout - Sidebar
widgets:
- Find Authors Elsewhere
upgrade_functions:
enable_existing_streams:
version_limit: 9
updater:
type: author
label: Enabling default action streams for selected profiles...
code: $ActionStreams::ActionStreams::Upgrade::enable_existing_streams
reclass_actions:
version_limit: 15
handler: $ActionStreams::ActionStreams::Upgrade::reclass_actions
priority: 8
rename_action_metadata:
version_limit: 15
handler: $ActionStreams::ActionStreams::Upgrade::rename_action_metadata
priority: 9
upgrade_data:
reclass_actions:
twitter_tweets: twitter_statuses
pownce_notes: pownce_statuses
googlereader_shared: googlereader_links
rename_action_metadata:
- action_type: delicious_links
old: annotation
new: note
- action_type: googlereader_links
old: annotation
new: note
profile_services: services.yaml
action_streams: streams.yaml
diff --git a/plugins/ActionStreams/streams.yaml b/plugins/ActionStreams/streams.yaml
index 6322090..1b8fa8f 100644
--- a/plugins/ActionStreams/streams.yaml
+++ b/plugins/ActionStreams/streams.yaml
@@ -1,655 +1,655 @@
oneup:
playing:
name: Currently Playing
description: The games in your collection you're currently playing
class: OneupPlaying
backtype:
comments:
name: Comments
description: Comments you have made on the web
fields:
- queue
html_form: '[_1] commented on <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.backtype.com/{{ident}}'
rss: 1
identifier: url
blurst:
achievements:
name: Achievements
description: Achievements earned in Blurst games
fields:
- game_title
- game_url
html_form: '[_1] won achievement <a href="[_2]">[_3]</a> in <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- game_url
- game_title
class: BlurstAchievements
colourlovers:
colors:
name: Colors
description: Colors you saved
fields:
- queue
html_form: '[_1] saved the color <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/colors/new?lover={{ident}}'
xpath:
foreach: //color
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
palettes:
name: Palettes
description: Palettes you saved
fields:
- queue
html_form: '[_1] saved the palette <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/palettes/new?lover={{ident}}'
xpath:
foreach: //palette
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
patterns:
name: Patterns
description: Patterns you saved
fields:
- queue
html_form: '[_1] saved the pattern <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/patterns/new?lover={{ident}}'
xpath:
foreach: //pattern
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
favpalettes:
name: Favorite Palettes
description: Palettes you saved as favorites
fields:
- queue
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite palette'
html_params:
- url
- title
url: 'http://www.colourlovers.com/rss/lover/{{ident}}/palettes/favorites'
rss: 1
corkd:
reviews:
name: Reviews
description: Your wine reviews
fields:
- review
html_form: '[_1] reviewed <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/journal/{{ident}}'
rss: 1
cellar:
name: Cellar
description: Wines you own
fields:
- wine
html_form: '[_1] owns <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/cellar/{{ident}}'
rss: 1
list:
name: Shopping List
description: Wines you want to buy
fields:
- wine
html_form: '[_1] wants <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/shoppinglist/{{ident}}'
rss: 1
delicious:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
- url: 'http://feeds.delicious.com/v2/rss/{{ident}}?plain'
+ url: 'http://delicious.com/v2/rss/{{ident}}'
identifier: url
rss:
note: description
tags: category/child::text()
digg:
links:
name: Dugg
description: Links you dugg
html_form: '[_1] dugg the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://digg.com/users/{{ident}}/history/diggs.rss'
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
submitted:
name: Submissions
description: Links you submitted
html_form: '[_1] submitted the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://digg.com/users/{{ident}}/history/submissions.rss
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
ffffound:
favorites:
name: Found
description: Photos you found
html_form: '[_1] ffffound <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://ffffound.com/home/{{ident}}/found/feed
rss: 1
flickr:
favorites:
name: Favorites
description: Photos you marked as favorites
fields:
- by
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite photo'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_faves.gne?nsid={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
by: author/name
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_public.gne?id={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
friendfeed:
likes:
name: Likes
description: Things from your friends that you "like"
html_form: '[_1] likes <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://friendfeed.com/{{ident}}/likes?format=atom'
atom:
url: link/@href
gametap:
scores:
name: Leaderboard scores
description: Your high scores in games with leaderboards
fields:
- score
html_form: '[_1] scored <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- score
- url
- title
url: http://www.gametap.com/profile/leaderboards.do?sn={{ident}}
identifier: title,score
scraper:
foreach: 'div.buddy-leaderboards div.tr'
get:
url:
- 'div.name a'
- '@href'
title:
- 'div.name strong'
- TEXT
score:
- 'div.name div'
- TEXT
goodreads:
toread:
name: To read
description: Books on your "to-read" shelf
fields:
- by
html_form: '[_1] saved <a href="[_2]"><i>[_3]</i> by [_4]</a> to read'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=to-read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
reading:
name: Reading
description: Books on your "currently-reading" shelf
fields:
- by
html_form: '[_1] started reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=currently-reading'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
read:
name: Read
description: Books on your "read" shelf
fields:
- by
html_form: '[_1] finished reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
googlereader:
links:
name: Shared
description: Your shared items
fields:
- note
- source_title
- source_url
- summary
html_form: '[_1] shared <a href="[_2]">[_3]</a> from <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- source_url
- source_title
url: "http://www.google.com/reader/public/atom/user/{{ident}}/state/com.google/broadcast"
atom:
summary: summary
enclosure: "link[@rel='enclosure']/@href"
source_title: source/title
source_url: "source/link[@rel='alternate']/@href"
note: gr:annotation/content
created_on: ''
modified_on: ''
iconbuffet:
icons:
name: Deliveries
description: Icon sets you were delivered
html_form: '[_1] received the icon set <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.iconbuffet.com/people/{{ident}};received_packages'
identifier: url
scraper:
foreach: 'div#icons div.preview-sm'
get:
title:
- a span
- TEXT
url:
- a
- '@href'
identica:
statuses:
name: Notices
description: Notices you posted
html_form: '[_1] <a href="[_2]">said</a>, “[_3]”'
html_params:
- url
- title
url: 'http://identi.ca/{{ident}}/rss'
rss:
created_on: dc:date
class: Identica
iminta:
links:
name: Intas
description: Links you saved
html_form: '[_1] is inta <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://iminta.com/people/{{ident}}/rss.xml?inta_source_id=11'
rss: 1
instructables:
favorites:
name: Favorites
description: Instructables you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite'
html_params:
- url
- title
url: http://www.instructables.com/member/{{ident}}/rss.xml?show=good
rss:
created_on: ''
modified_on: ''
thumbnail: imageThumb
istockphoto:
photos:
name: Photos
description: Photos you posted that were approved
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.istockphoto.com/webservices/feeds/?feedFormat=IStockAtom_1_0&feedName=istockfeed.image.newestUploads&feedParams=UserID={{ident}}'
identifier: url
atom:
thumbnail: content/div/a/img/@src
iusethis:
events:
name: Recent events
description: Events from your recent events feed
html_form: '[_1] <a href="[_2]">[_3]</a>'
html_params:
- url
- title
rss: 1
url: 'http://osx.iusethis.com/user/feed.rss/{{ident}}?following=0'
osxapps:
name: Apps you use
description: The applications you saved as ones you use
fields:
- favorite
html_form: '[_1] started using <a href="[_2]">[_3]</a>[quant,_4, (and loves it),,]'
html_params:
- url
- title
- favorite
url: 'http://osx.iusethis.com/user/{{ident}}'
iwatchthis:
favorites:
name: Favorites
description: Videos you saved as watched
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video'
html_params:
- url
- title
url: 'http://iwatchthis.com/rss/{{ident}}'
rss: 1
jaiku:
jaikus:
name: Jaikus
description: Jaikus you posted
html_form: '[_1] <a href="[_2]">jaiku''d</a>, "[_3]"'
html_params:
- url
- title
url: 'http://{{ident}}.jaiku.com/feed/atom'
atom: 1
kongregate:
favorites:
name: Favorites
description: Games you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite game'
html_params:
- url
- title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url
scraper:
foreach: #favorites dl
get:
url:
- dd a
- '@href'
title:
- dd a
- TEXT
thumbnail:
- dt img
- '@src'
achievements:
name: Achievements
description: Achievements you won
fields:
- game_title
html_form: '[_1] won the <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- title
- url
- game_title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url,title
scraper:
foreach: #achievements .badge_details
get:
url:
- dt.badge_img a
- '@href'
thumbnail:
- dt.badge_img img
- '@style'
title:
- dd.badge_name
- TEXT
game_title:
- a.badge_game
- TEXT
lastfm:
tracks:
name: Tracks
description: Songs you recently listened to (High spam potential!)
html_form: '[_1] heard <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/recenttracks.rss'
rss: 1
lovedtracks:
name: Loved Tracks
description: Songs you marked as "loved"
fields:
- artist
html_form: '[_1] loved <a href="[_2]">[_3]</a> by [_4]'
html_params:
- url
- title
- artist
url: 'http://pipes.yahoo.com/pipes/pipe.run?_id=4smlkvMW3RGPpBPfTqoASA&_render=rss&lastFM_UserName={{ident}}'
identifier: url
rss:
artist: description
journalentries:
name: Journal Entries
description: Your recent journal entries
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/journals.rss'
rss: 1
events:
name: Events
description: The events you said you'll be attending
html_form: '[_1] is attending <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/events.rss'
rss: 1
livejournal:
posts:
name: Posts
description: Your public posts to your journal
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://users.livejournal.com/{{ident}}/data/atom'
atom: 1
magnolia:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ma.gnolia.com/atom/full/people/{{ident}}'
identifier: url
atom:
tags: "category[@scheme='http://ma.gnolia.com/tags']/@term"
note: content
metafilter:
favorites:
name: Favorites
description: Posts you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite'
html_params:
- url
- title
url: 'http://www.metafilter.com/favorites/{{ident}}/posts/rss'
rss:
created_on: ''
netflix:
queue:
name: Queue
description: Movies you added to your rental queue
fields:
- queue
html_form: '[_1] queued <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/QueueRSS?id={{ident}}'
rss:
thumbnail: description
recent:
name: Recent Movies
description: Recent Rental Activity
fields:
- recent
html_form: '[_1] is watching <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/TrackingRSS?id={{ident}}'
rss:
thumbnail: description
netvibes:
links:
name: Links
description: Links you saved
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www2.netvibes.com/rest/account/{{ident}}/timeline?format=atom'
atom: 1
nytimes:
links:
name: Recommendations
description: Recommendations in your TimesPeople activities
html_form: '[_1] recommended <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://timespeople.nytimes.com/view/user/{{ident}}/rss.xml'
rss: 1
ohloh:
kudos:
name: Kudos
description: Kudos you have received
html_form: '[_1] received kudos from <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.ohloh.net/accounts/{{ident}}/kudos'
identifier: url
scraper:
foreach: 'div.received_kudo'
get:
url:
- a
- '@href'
title:
- a
- TEXT
pandora:
favorites:
name: Favorite Songs
description: Songs you marked as favorites
fields:
- album_art
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite song'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favorites.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
|
markpasc/mt-plugin-action-streams
|
9f73868423239bb0c672d6236452387d3cdfa3a3
|
ActionStreams::Event::build_results did not check to make sure that the identifier was less than or equal to 200 characters in length. I added two minor fixes to address that.
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm
index b2ce484..163491d 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm
@@ -1,850 +1,850 @@
package ActionStreams::Event;
use strict;
use base qw( MT::Object MT::Taggable MT::Scorable );
our @EXPORT_OK = qw( classes_for_type );
use HTTP::Date qw( str2time );
use MT::Util qw( encode_html encode_url );
use MT::I18N;
use ActionStreams::Scraper;
our $hide_timeless = 0;
__PACKAGE__->install_properties({
column_defs => {
id => 'integer not null auto_increment',
identifier => 'string(200)',
author_id => 'integer not null',
visible => 'integer not null',
},
defaults => {
visible => 1,
},
indexes => {
identifier => 1,
author_id => 1,
created_on => 1,
created_by => 1,
},
class_type => 'event',
audit => 1,
meta => 1,
datasource => 'profileevent',
primary_key => 'id',
});
__PACKAGE__->install_meta({
columns => [ qw(
title
url
thumbnail
via
via_id
) ],
});
# Oracle does not like an identifier of more than 30 characters.
sub datasource {
my $class = shift;
my $r = MT->request;
my $ds = $r->cache('as_event_ds');
return $ds if $ds;
my $dss_oracle = qr/(db[id]::)?oracle/;
if ( my $type = MT->config('ObjectDriver') ) {
if ((lc $type) =~ m/^$dss_oracle$/) {
$ds = 'as';
}
}
$ds = $class->properties->{datasource}
unless $ds;
$r->cache('as_event_ds', $ds);
return $ds;
}
sub encode_field_for_html {
my $event = shift;
my ($field) = @_;
return encode_html( $event->$field() );
}
sub as_html {
my $event = shift;
my %params = @_;
my $stream = $event->registry_entry or return '';
# How many spaces are there in the form?
my $form = $params{form} || $stream->{html_form} || q{};
my @nums = $form =~ m{ \[ _ (\d+) \] }xmsg;
my $max = shift @nums;
for my $num (@nums) {
$max = $num if $max < $num;
}
# Do we need to supply the author name?
my @content = map { $event->encode_field_for_html($_) }
@{ $stream->{html_params} };
if ($max > scalar @content) {
my $name = defined $params{name} ? $params{name}
: $event->author->nickname
;
unshift @content, encode_html($name);
}
return MT->translate($form, @content);
}
sub update_events_loggily {
my $class = shift;
my %profile = @_;
# Keep this option out of band so we don't have to count on
# implementations of update_events() passing it through.
local $hide_timeless = delete $profile{hide_timeless} ? 1 : 0;
my $warn = $SIG{__WARN__} || sub { print STDERR $_[0] };
local $SIG{__WARN__} = sub {
my ($msg) = @_;
$msg =~ s{ \n \z }{}xms;
$msg = MT->component('ActionStreams')->translate(
'[_1] updating [_2] events for [_3]',
$msg, $profile{type}, $profile{author}->name,
);
$warn->("$msg\n");
};
eval {
$class->update_events(%profile);
};
if (my $err = $@) {
my $plugin = MT->component('ActionStreams');
my $err_msg = $plugin->translate("Error updating events for [_1]'s [_2] stream (type [_3] ident [_4]): [_5]",
$profile{author}->name, $class->properties->{class_type},
$profile{type}, $profile{ident}, $err);
MT->log($err_msg);
die $err; # re-throw so we can handle from job invocation
}
}
sub update_events {
my $class = shift;
my %profile = @_;
my $author = delete $profile{author};
my $stream = $class->registry_entry or return;
my $fetch = $stream->{fetch} || {};
local $profile{url} = $stream->{url};
die "Oops, no url?" if !$profile{url};
die "Oops, no ident?" if !$profile{ident};
require MT::I18N;
my $ident = encode_url(MT::I18N::encode_text($profile{ident}, undef, 'utf-8'));
$profile{url} =~ s/ {{ident}} / $ident /xmsge;
my $items;
if (my $xpath_params = $stream->{xpath}) {
$items = $class->fetch_xpath(
%$xpath_params,
%$fetch,
%profile,
);
}
elsif (my $atom_params = $stream->{atom}) {
my $get = {
created_on => 'published',
modified_on => 'updated',
title => 'title',
url => q{link[@rel='alternate']/@href},
via => q{link[@rel='alternate']/@href},
via_id => 'id',
identifier => 'id',
};
$atom_params = {} if !ref $atom_params;
@$get{keys %$atom_params} = values %$atom_params;
$items = $class->fetch_xpath(
foreach => '//entry',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $rss_params = $stream->{rss}) {
my $get = {
title => 'title',
url => 'link',
via => 'link',
created_on => 'pubDate',
thumbnail => 'media:thumbnail/@url',
via_id => 'guid',
identifier => 'guid',
};
$rss_params = {} if !ref $rss_params;
@$get{keys %$rss_params} = values %$rss_params;
$items = $class->fetch_xpath(
foreach => '//item',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $scraper_params = $stream->{scraper}) {
my ($foreach, $get) = @$scraper_params{qw( foreach get )};
my $scraper = scraper {
process $foreach, 'res[]' => scraper {
while (my ($field, $sel) = each %$get) {
process $sel->[0], $field => $sel->[1];
}
};
result 'res';
};
$items = $class->fetch_scraper(
scraper => $scraper,
%$fetch,
%profile,
);
}
return if !$items;
$class->build_results(
items => $items,
stream => $stream,
author => $author,
profile => \%profile,
);
}
sub registry_entry {
my $event = shift;
my ($type, $stream) = split /_/, $event->properties->{class_type}, 2;
my $reg = MT->instance->registry('action_streams') or return;
my $service = $reg->{$type} or return;
$service->{$stream};
}
sub author {
my $event = shift;
my $author_id = $event->author_id
or return;
return MT->instance->model('author')->lookup($author_id);
}
sub blog_id { 0 }
sub classes_for_type {
my $class = shift;
my ($type) = @_;
my $prevts = MT->instance->registry('action_streams');
my $prevt = $prevts->{$type};
return if !$prevt;
my @classes;
PACKAGE: while (my ($stream_id, $stream) = each %$prevt) {
next if 'HASH' ne ref $stream;
next if !$stream->{class} && !$stream->{url};
# This check intentionally fails a lot, so ignore any DIE handler we
# might have.
my $has_props = sub {
my $pkg = shift;
return eval { local $SIG{__DIE__}; $pkg->properties };
};
my $pkg;
if ($pkg = $stream->{class}) {
$pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms;
if (!$has_props->($pkg)) {
if (!eval "require $pkg; 1") {
my $error = $@ || q{};
my $pl = MT->component('ActionStreams');
MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]',
$pkg, $type, $stream_id, $error));
next PACKAGE;
}
}
}
else {
$pkg = join q{::}, $class, 'Auto', ucfirst $type,
ucfirst $stream_id;
if (!$has_props->($pkg)) {
eval "package $pkg; use base qw( $class ); 1" or next PACKAGE;
my $class_type = join q{_}, $type, $stream_id;
$pkg->install_properties({ class_type => $class_type });
$pkg->install_meta({ columns => $stream->{fields} })
if $stream->{fields};
}
}
push @classes, $pkg;
}
return @classes;
}
my $ua;
sub ua {
my $class = shift;
my %params = @_;
$ua ||= MT->new_ua({
paranoid => 1,
timeout => 10,
});
$ua->max_size(250_000) if $ua->can('max_size');
$ua->agent($params{default_useragent} ? $ua->_agent
: "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version);
return $ua if $class->class_type eq 'event';
return $ua if $params{unconditional};
require ActionStreams::UserAgent::Adapter;
my $adapter = ActionStreams::UserAgent::Adapter->new(
ua => $ua,
action_type => $class->class_type,
die_on_not_modified => $params{die_on_not_modified} || 0,
);
return $adapter;
}
sub set_values {
my $event = shift;
my ($values) = @_;
for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) {
my $meta_val = delete $values->{$meta_col};
$event->$meta_col($meta_val) if defined $meta_val;
}
$event->SUPER::set_values($values);
}
sub fetch_xpath {
my $class = shift;
my %params = @_;
my $url = $params{url} || '';
if (!$url) {
MT->log(
MT->component('ActionStreams')->translate(
"No URL to fetch for [_1] results", $class));
return;
}
my $ua = $class->ua(%params);
my $res = $ua->get($url);
if (!$res->is_success()) {
MT->log(
MT->component('ActionStreams')->translate(
"Could not fetch [_1]: [_2]", $url, $res->status_line()))
if $res->code != 304;
return;
}
# Do not continue if contents is incomplete.
if (my $abort = $res->{_headers}{'client-aborted'}) {
MT->log(
MT->component('ActionStreams')->translate(
'Aborted fetching [_1]: [_2]', $url, $abort));
return;
}
# Strip leading whitespace, since the parser doesn't like it.
# TODO: confirm we got xml?
my $content = $res->content;
$content =~ s{ \A \s+ }{}xms;
require XML::XPath;
my $x = XML::XPath->new( xml => $content );
my @items;
ITEM: for my $item ($x->findnodes($params{foreach})) {
my %item_data;
VALUE: while (my ($key, $val) = each %{ $params{get} }) {
next VALUE if !$val;
if ($key eq 'tags') {
my @outvals = $item->findnodes($val)
or next VALUE;
$item_data{$key} = [ grep { $_ } map { MT::I18N::utf8_off($_->getNodeValue) } @outvals ];
}
else {
my $outval = $item->findvalue($val)
or next VALUE;
$outval = MT::I18N::utf8_off("$outval");
if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) {
# try both RFC 822/1123 and ISO 8601 formats
my $out_timestamp;
if (my $epoch = str2time($outval)) {
$out_timestamp = MT::Util::epoch2ts(undef, $epoch);
}
# The epoch2ts may have failed too.
if (!defined $out_timestamp) {
$out_timestamp = MT::Util::iso2ts(undef, $outval);
}
# Whether it's defined or not, that's our new outval.
$outval = $out_timestamp;
}
$item_data{$key} = $outval if $outval;
}
}
push @items, \%item_data;
}
return \@items;
}
sub build_results {
my $class = shift;
my %params = @_;
my ($author, $items, $profile, $stream) =
@params{qw( author items profile stream )};
my $mt = MT->app;
ITEM: for my $item (@$items) {
my $event;
my $identifier = delete $item->{identifier};
if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) {
$identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} };
}
if (defined $identifier) {
$identifier = "$identifier";
($event) = $class->search({
author_id => $author->id,
- identifier => $identifier,
+ identifier => substr($identifier, 0, 200),
});
}
$event ||= $class->new;
$mt->run_callbacks('filter_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile)
or return;
$mt->run_callbacks('pre_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
my $tags = delete $item->{tags};
$event->set_values({
author_id => $author->id,
- identifier => $identifier,
+ identifier => substr($identifier, 0, 200),
%$item,
});
$event->tags(@$tags) if $tags && @$tags;
if ($hide_timeless && !$event->created_on) {
$event->visible(0);
}
$mt->run_callbacks('post_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
$event->save() or MT->log($event->errstr);
}
1;
}
sub save {
my $event = shift;
# Built-in audit field setting will set a local time, so do it ourselves.
if (!$event->created_on) {
my $ts = MT::Util::epoch2ts(undef, time);
$event->created_on($ts);
$event->modified_on($ts);
}
return $event->SUPER::save(@_);
}
sub fetch_scraper {
my $class = shift;
my %params = @_;
my ($url, $scraper) = @params{qw( url scraper )};
$scraper->user_agent( $class->ua( %params, die_on_not_modified => 1 ) );
my $uri_obj = URI->new($url);
my $items = eval { $scraper->scrape($uri_obj) };
# Ignore Web::Scraper errors due to 304 Not Modified responses.
if (!$items && $@ && !UNIVERSAL::isa($@, 'ActionStreams::UserAgent::NotModified')) {
die; # rethrow
}
# we're only being used for our scraper.
return if !$items;
return $items if !ref $items;
return $items if 'ARRAY' ne ref $items;
ITEM: for my $item (@$items) {
next ITEM if !ref $item || ref $item ne 'HASH';
for my $field (keys %$item) {
if ($field eq 'tags') {
$item->{$field} = [ map { MT::I18N::utf8_off( "$_" ) } @{ $item->{$field} } ];
}
elsif (defined $item->{$field}) {
$item->{$field} = MT::I18N::utf8_off( q{} . $item->{$field} );
}
else {
delete $item->{$field};
}
}
}
return $items;
}
sub backup_terms_args {
my $class = shift;
my ($blog_ids) = @_;
return { terms => { 'class' => '*' }, args => undef };
}
1;
__END__
=head1 NAME
ActionStreams::Event - an Action Streams stream definition
=head1 SYNOPSIS
# in plugin's config.yaml
profile_services:
example:
streamid:
name: Dice Example
description: A simple die rolling Perl stream example.
html_form: [_1] rolled a [_2]!
html_params:
- title
class: My::Stream
# in plugin's lib/My/Stream.pm
package My::Stream;
use base qw( ActionStreams::Event );
__PACKAGE__->install_properties({
class_type => 'example_streamid',
});
sub update_events {
my $class = shift;
my %profile = @_;
# trivial example: save a random number
my $die_roll = int rand 20;
my %item = (
title => $die_roll,
identifier => $die_roll,
);
return $class->build_results(
author => $profile{author},
items => [ \%item ],
);
}
1;
=head1 DESCRIPTION
I<ActionStreams::Event> provides the basic implementation of an action stream.
Stream definitions are engines for turning web resources into I<actions> (also
called I<events>). This base class produces actions based on generic stream
recipes defined in the MT registry, as well as providing the internal machinery
for you to implement your own streams in Perl code.
=head1 METHODS TO IMPLEMENT
These are the methods one commonly implements (overrides) when implementing a
stream subclass.
=head2 C<$class-E<gt>update_events(%profile)>
Fetches the web resource specified by the profile parameters, collects data
from it into actions, and saves the action records for use later. Required
members of C<%profile> are:
=over 4
=item * C<author>
The C<MT::Author> instance for whom events should be collected.
=item * C<ident>
The author's identifier on the given service.
=back
Other information about the stream, such as the URL pattern into which the
C<ident> parameter can be replaced, is available through the
C<$class-E<gt>registry_entry()> method.
=head2 C<$self-E<gt>as_html(%params)>
Returns the HTML version of the action, suitable for display to readers.
The default implementation uses the stream's registry definition to construct
the action: the author's name and the action's values as named in
C<html_params> are replaced into the stream's C<html_form> setting. You need
override it only if you have more complex requirements.
Optional members of C<%params> are:
=over 4
=item * C<form>
The formatting string to use. If not given, the C<html_form> specified for
this stream in the registry is used.
=item * C<name>
The text to use as the author's name if C<as_html> needs to provide it
automatically in the result. Author names are provided if there are more
tokens in C<html_form> than there are fields specified in C<html_params>.
If not given, the event's author's nickname is provided. Note that a defined
but empty name (such as C<q{}>) I<will> be used; in this case, the name will
appear to be omitted from the result of the C<as_html> call.
=back
=head1 AVAILABLE METHODS
These are the methods provided by I<ActionStreams::Event> to perform common
tasks. Call them from your overridden methods.
=head2 C<$self-E<gt>set_values(\%values)>
Stores the data given in C<%values> as members of this event.
=head2 C<$class-E<gt>fetch_xpath(%param)>
Returns the items discovered by scanning a web resource by the given XPath
recipe. Required members of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be a
valid XML document.
=item * C<foreach>
The XPath selector with which to select the individual events from the
resource.
=item * C<get>
A hashref containing the XPath selectors with which to collect individual data
for each item, keyed on the names of the fields to contain the data.
=back
C<%param> may also contain additional arguments for the C<ua()> method.
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
=head2 C<$class-E<gt>fetch_scraper(%param)>
Returns the items discovered by scanning by the given recipe. Required members
of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be an
HTML or XML document suitable for analysis by the C<Web::Scraper> module.
=item * C<scraper>
The C<Web::Scraper> scraper with which to extract item data from the specified
web resource. See L<Web::Scraper> for information on how to construct a
scraper.
=back
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
See also the below I<NOTE ON WEB::SCRAPER>.
=head2 C<$class-E<gt>build_results(%param)>
Converts a set of collected items into saved action records of type C<$class>.
The required members of C<%param> are:
=over 4
=item * C<author>
The C<MT::Author> instance whose action the items represent.
=item * C<items>
An arrayref of items to save as actions. Each item is a hashref containing the
action data, keyed on the names of the fields containing the data.
=back
Optional parameters are:
=over 4
=item * C<profile>
An arrayref describing the data for the author's profile for the associated
stream, such as is returned by the C<MT::Author::other_profile()> method
supplied by the Action Streams plugin.
The profile member is not used directly by C<build_results()>; they are only
passed to callbacks.
=item * C<stream>
A hashref containing the settings from the registry about the stream, such as
is returned from the C<registry_entry()> method.
=back
=head2 C<$class-E<gt>ua(%param)>
Returns the common HTTP user-agent, an instance of C<LWP::UserAgent>, with
which you can fetch web resources.
The resulting user agent may provide automatic conditional HTTP support when
you call its C<get> method. A UA with conditional HTTP support enabled will
store the values of the conditional HTTP headers (C<ETag> and
C<Last-Modified>) received in responses as C<ActionStreams::UserAgent::Cache>
objects and, on subsequent requests of the same URL, automatically supply the
header values. When the remote HTTP server reports that such a resource has
not changed, the C<HTTP::Response> will be a C<304 Not Modified> response; the
user agent does not itself store and supply the resource content. Using other
C<LWP::UserAgent> methods such as C<post> or C<request> will I<not> trigger
automatic conditional HTTP support.
No arguments are required; possible optional parameters are:
=over 4
=item * C<default_useragent>
If set, the returned HTTP user-agent will use C<LWP::UserAgent>'s default
identifier in the HTTP C<User-Agent> header. If omitted, the UA will use the
Action Streams identifier of C<mt-actionstreams-lwp/I<version>>.
=item * C<unconditional>
If set, the return HTTP user-agent will I<not> automatically use conditional
HTTP to avoid requesting old content from compliant servers. That is, if
omitted, the UA I<will> automatically use conditional HTTP when you call its
C<get> method.
=item * C<die_on_not_modified>
If set, when the response of the HTTP user-agent's C<get> method is a
conditional HTTP C<304 Not Modified> response, throw an exception instead of
returning the response. (Use this option to return control to yourself when
passing UAs with conditional HTTP support to other Perl modules that don't
expect 304 responses.)
The thrown exception is an C<ActionStreams::UserAgent::NotModified> exception.
=back
=head2 C<$self-E<gt>author()>
Returns the C<MT::Author> instance associated with this event, if its
C<author_id> field has been set.
=head2 C<$class-E<gt>install_properties(\%properties)>
I<TODO>
=head2 C<$class-E<gt>install_meta(\%properties)>
I<TODO>
=head2 C<$class-E<gt>registry_entry()>
Returns the registry data for the stream represented by C<$class>.
=head2 C<$class-E<gt>classes_for_type($service_id)>
Given a profile service ID (that is, a key from the C<profile_services> section
of the registry), returns a list of stream classes for scanning that service's
streams.
=head2 C<$class-E<gt>backup_terms_args($blog_ids)>
Used in backup. Backup function calls the method to generate $terms and
$args for the class to load objects. ActionStream::Event does not have
blog_id and does use class_column, the nature the class has to tell
backup function to properly load all the target objects of the class
to be backed up.
See I<MT::BackupRestore> for more detail.
=head1 NOTE ON WEB::SCRAPER
The C<Web::Scraper> module is powerful, but it has complex dependencies. While
its pure Perl requirements are bundled with the Action Streams plugin, it also
requires a compiled XML module. Also, because of how its syntax works, you must
directly C<use> the module in your own code, contrary to the Movable Type idiom
of using C<require> so that modules are loaded only when they are sure to be
used.
If you attempt load C<Web::Scraper> in the normal way, but C<Web::Scraper> is
unable to load due to its missing requirement, whenever the plugin attempts to
load your scraper, the entire plugin will fail to load.
Therefore the C<ActionStreams::Scraper> wrapper module is provided for you. If
you need to load C<Web::Scraper> so as to make a scraper to pass
C<ActionStreams::Event::fetch_scraper()> method, instead write in your module:
use ActionStreams::Scraper;
This module provides the C<Web::Scraper> interface, but if C<Web::Scraper> is
unable to load, the error will be thrown when your module tries to I<use> it,
rather than when you I<load> it. That is, if C<Web::Scraper> can't load, no
errors will be thrown to end users until they try to use your stream.
=head1 AUTHOR
Mark Paschal E<lt>[email protected]<gt>
=cut
|
markpasc/mt-plugin-action-streams
|
037b016a46cb47a10ee20eb07e0b42cb997d76f3
|
Avoid doing a deprecated scalar split (thanks, Brendan)
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event/Steam.pm b/plugins/ActionStreams/lib/ActionStreams/Event/Steam.pm
index d37883f..3b5759d 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event/Steam.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event/Steam.pm
@@ -1,116 +1,117 @@
package ActionStreams::Event::Steam;
use strict;
use base qw( ActionStreams::Event );
use ActionStreams::Scraper;
__PACKAGE__->install_properties({
class_type => 'steam_achievements',
});
__PACKAGE__->install_meta({
columns => [ qw(
gametitle
gamecode
ident
description
) ],
});
my %game_for_code = (
Portal => 'Portal',
TF2 => 'Team Fortress 2',
'HL2:EP2' => 'Half-Life 2: Episode Two',
'DOD:S' => 'Day of Defeat: Source',
);
sub game {
my $event = shift;
return $event->gametitle || $game_for_code{$event->gamecode}
|| $event->gamecode;
}
sub update_events {
my $class = shift;
my %profile = @_;
my ($ident, $author) = @profile{qw( ident author )};
my $achv_scraper = scraper {
process q{div#BG_top h2},
'title' => 'TEXT';
process q{html},
'html' => 'HTML';
process q{//div[@class='achieveTxtHolder']},
'achvs[]' => scraper {
process 'h3', 'title' => 'TEXT';
process 'h5', 'description' => 'TEXT';
process 'img', 'thumbnail' => '@src';
};
};
my $games = $class->fetch_scraper(
url => "http://steamcommunity.com/id/$ident/games",
scraper => scraper {
process q{div#mainContents a.linkStandard},
'urls[]' => '@href';
result 'urls';
},
);
return if !$games;
URL: for my $url (@$games) {
my $gamecode = "$url";
$gamecode =~ s{ \A .* / }{}xms;
$url = "$url?tab=achievements"; # TF2's stats page has tabs
next URL if $url !~ m{ \Q$ident\E }xms;
my $items = $class->fetch_scraper(
url => $url,
scraper => $achv_scraper,
);
next URL if !$items;
my ($title, $html, $achvs) = @$items{qw( title html achvs )};
$title =~ s{ \s* Stats \z }{}xmsi;
next URL if ($title =~ /Global Gameplay/i);
# So we have the full source code in $html; we need to count how many achievements are before
# the critical <br /><br /><br /> line dividing achieved from unachieved.
next URL if ($html !~ /\<br\ \/\>\<br\ \/\>\<br\ \/\>.+/); # If the line isn't there, they don't have any achievements yet.
$html =~ s/\<br\ \/\>\<br\ \/\>\<br\ \/\>.+//;
- my $count = scalar split(/achieveTxtHolder/, $html);
+ my @splitlist = split(/achieveTxtHolder/, $html);
+ my $count = scalar @splitlist;
$count = $count - 2; #This method ends up with one too many, always, and we want the last valid *INDEX* number.
my @achievements = @$achvs;
$#achievements = $count; # Truncates the array
for my $item (@achievements) {
$item->{gametitle} = $title;
$item->{ident} = $ident;
$item->{gamecode} = $gamecode;
$item->{url} = $url;
# Stringify thumbnail url as our complicated structure
# prevents fetch_scraper() from stringifying it for us.
$item->{thumbnail} = q{} . $item->{thumbnail};
}
$class->build_results(
author => $author,
items => \@achievements,
identifier => 'ident,gamecode,title',
);
}
1;
}
1;
|
markpasc/mt-plugin-action-streams
|
722c9677fcb72eda794d4c499a17c8701f183a87
|
Fix Steam achievement stream for new HTML (thanks, Brendan O'Connor for the patch!)
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event/Steam.pm b/plugins/ActionStreams/lib/ActionStreams/Event/Steam.pm
index 986f5b6..d37883f 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event/Steam.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event/Steam.pm
@@ -1,100 +1,116 @@
package ActionStreams::Event::Steam;
use strict;
use base qw( ActionStreams::Event );
use ActionStreams::Scraper;
__PACKAGE__->install_properties({
class_type => 'steam_achievements',
});
__PACKAGE__->install_meta({
columns => [ qw(
gametitle
gamecode
ident
description
) ],
});
my %game_for_code = (
Portal => 'Portal',
TF2 => 'Team Fortress 2',
'HL2:EP2' => 'Half-Life 2: Episode Two',
'DOD:S' => 'Day of Defeat: Source',
);
sub game {
my $event = shift;
return $event->gametitle || $game_for_code{$event->gamecode}
|| $event->gamecode;
}
sub update_events {
my $class = shift;
my %profile = @_;
my ($ident, $author) = @profile{qw( ident author )};
my $achv_scraper = scraper {
process q{div#BG_top h2},
'title' => 'TEXT';
- process q{//div[@class='achievementClosed']},
+ process q{html},
+ 'html' => 'HTML';
+ process q{//div[@class='achieveTxtHolder']},
'achvs[]' => scraper {
process 'h3', 'title' => 'TEXT';
process 'h5', 'description' => 'TEXT';
process 'img', 'thumbnail' => '@src';
};
};
my $games = $class->fetch_scraper(
url => "http://steamcommunity.com/id/$ident/games",
scraper => scraper {
process q{div#mainContents a.linkStandard},
'urls[]' => '@href';
result 'urls';
},
);
return if !$games;
URL: for my $url (@$games) {
my $gamecode = "$url";
$gamecode =~ s{ \A .* / }{}xms;
$url = "$url?tab=achievements"; # TF2's stats page has tabs
next URL if $url !~ m{ \Q$ident\E }xms;
my $items = $class->fetch_scraper(
url => $url,
scraper => $achv_scraper,
);
next URL if !$items;
- my ($title, $achvs) = @$items{qw( title achvs )};
+ my ($title, $html, $achvs) = @$items{qw( title html achvs )};
$title =~ s{ \s* Stats \z }{}xmsi;
- for my $item (@$achvs) {
+ next URL if ($title =~ /Global Gameplay/i);
+
+ # So we have the full source code in $html; we need to count how many achievements are before
+ # the critical <br /><br /><br /> line dividing achieved from unachieved.
+
+ next URL if ($html !~ /\<br\ \/\>\<br\ \/\>\<br\ \/\>.+/); # If the line isn't there, they don't have any achievements yet.
+
+ $html =~ s/\<br\ \/\>\<br\ \/\>\<br\ \/\>.+//;
+ my $count = scalar split(/achieveTxtHolder/, $html);
+ $count = $count - 2; #This method ends up with one too many, always, and we want the last valid *INDEX* number.
+
+ my @achievements = @$achvs;
+ $#achievements = $count; # Truncates the array
+
+ for my $item (@achievements) {
$item->{gametitle} = $title;
$item->{ident} = $ident;
$item->{gamecode} = $gamecode;
$item->{url} = $url;
# Stringify thumbnail url as our complicated structure
# prevents fetch_scraper() from stringifying it for us.
$item->{thumbnail} = q{} . $item->{thumbnail};
}
$class->build_results(
author => $author,
- items => $achvs,
+ items => \@achievements,
identifier => 'ident,gamecode,title',
);
}
1;
}
1;
|
markpasc/mt-plugin-action-streams
|
563c2ab485b73fbabf00f39544d7481153481f76
|
Don't change the google reader items' identifiers after we check them for uniqueness
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Fix.pm b/plugins/ActionStreams/lib/ActionStreams/Fix.pm
index a8c1ade..b40f3a5 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Fix.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Fix.pm
@@ -1,164 +1,163 @@
package ActionStreams::Fix;
use strict;
use warnings;
use ActionStreams::Scraper;
sub _twitter_add_tags_to_item {
my ($item) = @_;
if (my @tags = $item->{title} =~ m{
(?: \A | \s ) # BOT or whitespace
\# # hash
(\w\S*\w) # tag
(?<! 's ) # but don't end with 's
}xmsg) {
$item->{tags} = \@tags;
}
}
sub twitter_tweet_name {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the Twitter username from the front of the tweet.
my $ident = $profile->{ident};
$item->{title} =~ s{ \A \s* \Q$ident\E : \s* }{}xmsi;
_twitter_add_tags_to_item($item);
}
sub twitter_favorite_author {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the Twitter username from the front of the tweet.
if ($item->{title} =~ s{ \A \s* ([^\s:]+) : \s* }{}xms) {
$item->{tweet_author} = $1;
}
_twitter_add_tags_to_item($item);
}
sub flickr_photo_thumbnail {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Extract just the URL, and use the _t size thumbnail, not the _m size image.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ (http://farm[^\.]+\.static\.flickr\.com .*? _m.jpg) }xms) {
$thumb = $1;
$thumb =~ s{ _m.jpg \z }{_t.jpg}xms;
$item->{thumbnail} = $thumb;
}
}
sub googlereader_link_links {
my ($cb, $app, $item, $event, $author, $profile) = @_;
my $enclosure = delete $item->{enclosure};
$item->{url} ||= $enclosure || q{};
- $item->{identifier} = $item->{url} if $item->{url};
}
sub iminta_link_title {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the username for when we add it back in later.
$item->{title} =~ s{ (?: \s* :: [^:]+ ){2} \z }{}xms;
}
sub instructables_favorites_thumbnails {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{thumbnail} = URI->new_abs($item->{thumbnail}, 'http://www.instructables.com/')
if $item->{thumbnail};
}
sub iusethis_event_title {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the username for when we add it back in later.
$item->{title} =~ s{ \A \w+ \s* }{}xms;
}
sub metafilter_favorites_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{title} =~ s{ \A [^:]+ : \s* }{}xms;
}
sub netflix_recent_prefix_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the 'Shipped:' or 'Received:' prefix.
$item->{title} =~ s{ \A [^:]*: \s* }{}xms;
# Extract thumbnail from description.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m/ <img src="([^"]+)"} /xms) {
$item->{thumbnail} = $1;
}
}
sub netflix_queue_prefix_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the item number.
$item->{title} =~ s{ \A \d+ [\W\S] \s* }{}xms;
# Extract thumbnail from description.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m/ <img src="([^"]+)"} /xms) {
$item->{thumbnail} = $1;
}
}
sub nytimes_links_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
return $item->{title} =~ s{ \A [^:]* recommended [^:]* : \s* }{}xms ? 1 : 0;
}
sub p0pulist_stuff_urls {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{url} =~ s{ \A / }{http://p0pulist.com/}xms;
}
sub kongregate_achievement_title_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the parenthetical from the end of the title.
$item->{title} =~ s{ \( [^)]* \) \z }{}xms;
# Pick the actual achievement badge out of the inline CSS.
my $thumb = delete $item->{thumbnail} || q{};
if ($thumb =~ m{ background-image: \s* url\( ([^)]+) }xms) {
$item->{thumbnail} = $1;
}
}
sub wists_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Grab the wists thumbnail out.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ (http://cache.wists.com/thumbnails/ [^"]+ ) }xms) {
$item->{thumbnail} = $1;
}
}
sub gametap_score_stuff {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{score} =~ s{ \D }{}xmsg;
$item->{url} = q{} . $item->{url};
$item->{url} =~ s{ \A / }{http://www.gametap.com/}xms;
}
sub typepad_comment_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{title} =~ s{ \A .*? ' }{}xms;
$item->{title} =~ s{ ' \z }{}xms;
}
sub magnolia_link_notes {
my ($cb, $app, $item, $event, $author, $profile) = @_;
my $scraper = scraper {
process '//p[position()=2]', note => 'TEXT';
};
my $result = $scraper->scrape(\$item->{note});
if ($result->{note}) {
$item->{note} = $result->{note};
}
else {
delete $item->{note};
}
}
1;
|
markpasc/mt-plugin-action-streams
|
be30bb2162889e1aa0c47ab4ae6dc7bd67e1a827
|
Switch the Google Reader stream to a yaml recipe instead of a class based definition
|
diff --git a/plugins/ActionStreams/config.yaml b/plugins/ActionStreams/config.yaml
index eed97e1..b73551f 100644
--- a/plugins/ActionStreams/config.yaml
+++ b/plugins/ActionStreams/config.yaml
@@ -1,197 +1,198 @@
name: Action Streams
id: ActionStreams
key: ActionStreams
author_link: http://www.sixapart.com/
author_name: Six Apart Ltd.
description: <MT_TRANS phrase="Manages authors' accounts and actions on sites elsewhere around the web">
schema_version: 16
version: 2.2
plugin_link: http://www.sixapart.com/
settings:
rebuild_for_action_stream_events:
Default: 0
Scope: blog
l10n_class: ActionStreams::L10N
blog_config_template: blog_config_template.tmpl
init_app: $ActionStreams::ActionStreams::Init::init_app
applications:
cms:
methods:
list_profileevent: $ActionStreams::ActionStreams::Plugin::list_profileevent
other_profiles: $ActionStreams::ActionStreams::Plugin::other_profiles
dialog_add_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile
dialog_edit_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile
add_other_profile: $ActionStreams::ActionStreams::Plugin::add_other_profile
edit_other_profile: $ActionStreams::ActionStreams::Plugin::edit_other_profile
remove_other_profile: $ActionStreams::ActionStreams::Plugin::remove_other_profile
itemset_update_profiles: $ActionStreams::ActionStreams::Plugin::itemset_update_profiles
itemset_hide_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_events
itemset_show_events: $ActionStreams::ActionStreams::Plugin::itemset_show_events
itemset_hide_all_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events
itemset_show_all_events: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events
community:
methods:
profile_add_external_profile: $ActionStreams::ActionStreams::Plugin::profile_add_external_profile
profile_delete_external_profile: $ActionStreams::ActionStreams::Plugin::profile_delete_external_profile
callbacks:
post_add_profile: $ActionStreams::ActionStreams::Plugin::profile_first_update_events
callbacks:
MT::App::CMS::template_param.edit_author: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::template_param.list_member: $ActionStreams::ActionStreams::Plugin::param_list_member
MT::App::CMS::template_param.other_profiles: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::template_param.list_profileevent: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::post_add_profile: $ActionStreams::ActionStreams::Plugin::first_profile_update
post_action_streams_task: $ActionStreams::ActionStreams::Plugin::rebuild_action_stream_blogs
pre_build_action_streams_event.flickr_favorites: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail
pre_build_action_streams_event.flickr_photos: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail
pre_build_action_streams_event.gametap_scores: $ActionStreams::ActionStreams::Fix::gametap_score_stuff
+ pre_build_action_streams_event.googlereader_links: $ActionStreams::ActionStreams::Fix::googlereader_link_links
pre_build_action_streams_event.identica_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name
pre_build_action_streams_event.iminta_links: $ActionStreams::ActionStreams::Fix::iminta_link_title
pre_build_action_streams_event.instructables_favorites: $ActionStreams::ActionStreams::Fix::instructables_favorites_thumbnails
pre_build_action_streams_event.iusethis_events: $ActionStreams::ActionStreams::Fix::iusethis_event_title
pre_build_action_streams_event.kongregate_achievements: $ActionStreams::ActionStreams::Fix::kongregate_achievement_title_thumb
pre_build_action_streams_event.magnolia_links: $ActionStreams::ActionStreams::Fix::magnolia_link_notes
pre_build_action_streams_event.metafilter_favorites: $ActionStreams::ActionStreams::Fix::metafilter_favorites_titles
pre_build_action_streams_event.netflix_queue: $ActionStreams::ActionStreams::Fix::netflix_queue_prefix_thumb
pre_build_action_streams_event.netflix_recent: $ActionStreams::ActionStreams::Fix::netflix_recent_prefix_thumb
pre_build_action_streams_event.p0pulist_stuff: $ActionStreams::ActionStreams::Fix::p0pulist_stuff_urls
pre_build_action_streams_event.twitter_favorites: $ActionStreams::ActionStreams::Fix::twitter_favorite_author
pre_build_action_streams_event.twitter_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name
pre_build_action_streams_event.typepad_comments: $ActionStreams::ActionStreams::Fix::typepad_comment_titles
pre_build_action_streams_event.wists_wists: $ActionStreams::ActionStreams::Fix::wists_thumb
filter_action_streams_event.nytimes_links: $ActionStreams::ActionStreams::Fix::nytimes_links_titles
object_types:
profileevent: ActionStreams::Event
as: ActionStreams::Event
as_ua_cache: ActionStreams::UserAgent::Cache
list_actions:
profileevent:
hide_all:
label: Hide All
order: 100
js: finishPluginActionAll
code: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events
continue_prompt_handler: >
sub { MT->translate('Are you sure you want to hide EVERY event in EVERY action stream?') }
show_all:
label: Show All
order: 200
js: finishPluginActionAll
code: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events
continue_prompt_handler: >
sub { MT->translate('Are you sure you want to show EVERY event in EVERY action stream?') }
delete:
label: Delete
order: 300
code: $core::MT::App::CMS::delete
continue_prompt_handler: >
sub { MT->translate('Deleted events that are still available from the remote service will be added back in the next scan. Only events that are no longer available from your profile will remain deleted. Are you sure you want to delete the selected event(s)?') }
tags:
function:
StreamAction: $ActionStreams::ActionStreams::Tags::stream_action
StreamActionID: $ActionStreams::ActionStreams::Tags::stream_action_id
StreamActionVar: $ActionStreams::ActionStreams::Tags::stream_action_var
StreamActionDate: $ActionStreams::ActionStreams::Tags::stream_action_date
StreamActionModifiedDate: $ActionStreams::ActionStreams::Tags::stream_action_modified_date
StreamActionTitle: $ActionStreams::ActionStreams::Tags::stream_action_title
StreamActionURL: $ActionStreams::ActionStreams::Tags::stream_action_url
StreamActionThumbnailURL: $ActionStreams::ActionStreams::Tags::stream_action_thumbnail_url
StreamActionVia: $ActionStreams::ActionStreams::Tags::stream_action_via
OtherProfileVar: $ActionStreams::ActionStreams::Tags::other_profile_var
block:
ActionStreams: $ActionStreams::ActionStreams::Tags::action_streams
StreamActionTags: $ActionStreams::ActionStreams::Tags::stream_action_tags
OtherProfiles: $ActionStreams::ActionStreams::Tags::other_profiles
ProfileServices: $ActionStreams::ActionStreams::Tags::profile_services
StreamActionRollup: $ActionStreams::ActionStreams::Tags::stream_action_rollup
tasks:
UpdateEvents:
frequency: 1800
label: Poll for new events
code: $ActionStreams::ActionStreams::Plugin::update_events
task_workers:
UpdateEvents:
label: Update Events
class: ActionStreams::Worker
widgets:
asotd:
label: Recent Actions
template: widget_recent.mtml
permission: post
singular: 1
set: sidebar
handler: $ActionStreams::ActionStreams::Plugin::widget_recent
condition: $ActionStreams::ActionStreams::Plugin::widget_blog_dashboard_only
template_sets:
streams:
label: Action Stream
base_path: 'blog_tmpl'
base_css: themes-base/blog.css
order: 100
templates:
index:
main_index:
label: Main Index (Recent Actions)
outfile: index.html
rebuild_me: 1
archive:
label: Action Archive
outfile: archive.html
rebuild_me: 1
styles:
label: Stylesheet
outfile: styles.css
rebuild_me: 1
feed_recent:
label: Feed - Recent Activity
outfile: atom.xml
rebuild_me: 1
module:
html_head:
label: HTML Head
banner_header:
label: Banner Header
banner_footer:
label: Banner Footer
sidebar:
label: Sidebar
widget:
elsewhere:
label: Find Authors Elsewhere
actions:
label: Recent Actions
widgetset:
2column_layout_sidebar:
label: 2-column layout - Sidebar
widgets:
- Find Authors Elsewhere
upgrade_functions:
enable_existing_streams:
version_limit: 9
updater:
type: author
label: Enabling default action streams for selected profiles...
code: $ActionStreams::ActionStreams::Upgrade::enable_existing_streams
reclass_actions:
version_limit: 15
handler: $ActionStreams::ActionStreams::Upgrade::reclass_actions
priority: 8
rename_action_metadata:
version_limit: 15
handler: $ActionStreams::ActionStreams::Upgrade::rename_action_metadata
priority: 9
upgrade_data:
reclass_actions:
twitter_tweets: twitter_statuses
pownce_notes: pownce_statuses
googlereader_shared: googlereader_links
rename_action_metadata:
- action_type: delicious_links
old: annotation
new: note
- action_type: googlereader_links
old: annotation
new: note
profile_services: services.yaml
action_streams: streams.yaml
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event/GoogleReader.pm b/plugins/ActionStreams/lib/ActionStreams/Event/GoogleReader.pm
deleted file mode 100644
index 6af243d..0000000
--- a/plugins/ActionStreams/lib/ActionStreams/Event/GoogleReader.pm
+++ /dev/null
@@ -1,49 +0,0 @@
-
-package ActionStreams::Event::GoogleReader;
-
-use strict;
-use base qw( ActionStreams::Event );
-
-__PACKAGE__->install_properties({
- class_type => 'googlereader_links',
-});
-
-__PACKAGE__->install_meta({
- columns => [ qw(
- summary
- source_title
- source_url
- note
- ) ],
-});
-
-sub update_events {
- my $class = shift;
- my %profile = @_;
- my ($ident, $author) = @profile{qw( ident author )};
-
- my $items = $class->fetch_xpath(
- url => "http://www.google.com/reader/public/atom/user/$ident/state/com.google/broadcast",
- foreach => '//entry',
- get => {
- title => 'title/child::text()',
- summary => 'summary/child::text()',
- url => q(link[@rel='alternate']/@href),
- enclosure => q(link[@rel='enclosure']/@href),
- source_title => 'source/title/child::text()',
- source_url => q(source/link[@rel='alternate']/@href),
- note => 'gr:annotation/content/child::text()',
- },
- );
- return if !$items;
-
- for my $item (@$items) {
- my $enclosure = delete $item->{enclosure};
- $item->{url} ||= $enclosure;
- $item->{identifier} = $item->{url};
- }
-
- $class->build_results( author => $author, items => $items );
-}
-
-1;
diff --git a/plugins/ActionStreams/lib/ActionStreams/Fix.pm b/plugins/ActionStreams/lib/ActionStreams/Fix.pm
index 1d24ba6..a8c1ade 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Fix.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Fix.pm
@@ -1,157 +1,164 @@
package ActionStreams::Fix;
use strict;
use warnings;
use ActionStreams::Scraper;
sub _twitter_add_tags_to_item {
my ($item) = @_;
if (my @tags = $item->{title} =~ m{
(?: \A | \s ) # BOT or whitespace
\# # hash
(\w\S*\w) # tag
(?<! 's ) # but don't end with 's
}xmsg) {
$item->{tags} = \@tags;
}
}
sub twitter_tweet_name {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the Twitter username from the front of the tweet.
my $ident = $profile->{ident};
$item->{title} =~ s{ \A \s* \Q$ident\E : \s* }{}xmsi;
_twitter_add_tags_to_item($item);
}
sub twitter_favorite_author {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the Twitter username from the front of the tweet.
if ($item->{title} =~ s{ \A \s* ([^\s:]+) : \s* }{}xms) {
$item->{tweet_author} = $1;
}
_twitter_add_tags_to_item($item);
}
sub flickr_photo_thumbnail {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Extract just the URL, and use the _t size thumbnail, not the _m size image.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ (http://farm[^\.]+\.static\.flickr\.com .*? _m.jpg) }xms) {
$thumb = $1;
$thumb =~ s{ _m.jpg \z }{_t.jpg}xms;
$item->{thumbnail} = $thumb;
}
}
+sub googlereader_link_links {
+ my ($cb, $app, $item, $event, $author, $profile) = @_;
+ my $enclosure = delete $item->{enclosure};
+ $item->{url} ||= $enclosure || q{};
+ $item->{identifier} = $item->{url} if $item->{url};
+}
+
sub iminta_link_title {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the username for when we add it back in later.
$item->{title} =~ s{ (?: \s* :: [^:]+ ){2} \z }{}xms;
}
sub instructables_favorites_thumbnails {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{thumbnail} = URI->new_abs($item->{thumbnail}, 'http://www.instructables.com/')
if $item->{thumbnail};
}
sub iusethis_event_title {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the username for when we add it back in later.
$item->{title} =~ s{ \A \w+ \s* }{}xms;
}
sub metafilter_favorites_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{title} =~ s{ \A [^:]+ : \s* }{}xms;
}
sub netflix_recent_prefix_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the 'Shipped:' or 'Received:' prefix.
$item->{title} =~ s{ \A [^:]*: \s* }{}xms;
# Extract thumbnail from description.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m/ <img src="([^"]+)"} /xms) {
$item->{thumbnail} = $1;
}
}
sub netflix_queue_prefix_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the item number.
$item->{title} =~ s{ \A \d+ [\W\S] \s* }{}xms;
# Extract thumbnail from description.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m/ <img src="([^"]+)"} /xms) {
$item->{thumbnail} = $1;
}
}
sub nytimes_links_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
return $item->{title} =~ s{ \A [^:]* recommended [^:]* : \s* }{}xms ? 1 : 0;
}
sub p0pulist_stuff_urls {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{url} =~ s{ \A / }{http://p0pulist.com/}xms;
}
sub kongregate_achievement_title_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the parenthetical from the end of the title.
$item->{title} =~ s{ \( [^)]* \) \z }{}xms;
# Pick the actual achievement badge out of the inline CSS.
my $thumb = delete $item->{thumbnail} || q{};
if ($thumb =~ m{ background-image: \s* url\( ([^)]+) }xms) {
$item->{thumbnail} = $1;
}
}
sub wists_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Grab the wists thumbnail out.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ (http://cache.wists.com/thumbnails/ [^"]+ ) }xms) {
$item->{thumbnail} = $1;
}
}
sub gametap_score_stuff {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{score} =~ s{ \D }{}xmsg;
$item->{url} = q{} . $item->{url};
$item->{url} =~ s{ \A / }{http://www.gametap.com/}xms;
}
sub typepad_comment_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{title} =~ s{ \A .*? ' }{}xms;
$item->{title} =~ s{ ' \z }{}xms;
}
sub magnolia_link_notes {
my ($cb, $app, $item, $event, $author, $profile) = @_;
my $scraper = scraper {
process '//p[position()=2]', note => 'TEXT';
};
my $result = $scraper->scrape(\$item->{note});
if ($result->{note}) {
$item->{note} = $result->{note};
}
else {
delete $item->{note};
}
}
1;
diff --git a/plugins/ActionStreams/streams.yaml b/plugins/ActionStreams/streams.yaml
index c22e911..6322090 100644
--- a/plugins/ActionStreams/streams.yaml
+++ b/plugins/ActionStreams/streams.yaml
@@ -1,836 +1,849 @@
oneup:
playing:
name: Currently Playing
description: The games in your collection you're currently playing
class: OneupPlaying
backtype:
comments:
name: Comments
description: Comments you have made on the web
fields:
- queue
html_form: '[_1] commented on <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.backtype.com/{{ident}}'
rss: 1
identifier: url
blurst:
achievements:
name: Achievements
description: Achievements earned in Blurst games
fields:
- game_title
- game_url
html_form: '[_1] won achievement <a href="[_2]">[_3]</a> in <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- game_url
- game_title
class: BlurstAchievements
colourlovers:
colors:
name: Colors
description: Colors you saved
fields:
- queue
html_form: '[_1] saved the color <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/colors/new?lover={{ident}}'
xpath:
foreach: //color
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
palettes:
name: Palettes
description: Palettes you saved
fields:
- queue
html_form: '[_1] saved the palette <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/palettes/new?lover={{ident}}'
xpath:
foreach: //palette
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
patterns:
name: Patterns
description: Patterns you saved
fields:
- queue
html_form: '[_1] saved the pattern <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/patterns/new?lover={{ident}}'
xpath:
foreach: //pattern
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
favpalettes:
name: Favorite Palettes
description: Palettes you saved as favorites
fields:
- queue
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite palette'
html_params:
- url
- title
url: 'http://www.colourlovers.com/rss/lover/{{ident}}/palettes/favorites'
rss: 1
corkd:
reviews:
name: Reviews
description: Your wine reviews
fields:
- review
html_form: '[_1] reviewed <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/journal/{{ident}}'
rss: 1
cellar:
name: Cellar
description: Wines you own
fields:
- wine
html_form: '[_1] owns <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/cellar/{{ident}}'
rss: 1
list:
name: Shopping List
description: Wines you want to buy
fields:
- wine
html_form: '[_1] wants <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/shoppinglist/{{ident}}'
rss: 1
delicious:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.delicious.com/v2/rss/{{ident}}?plain'
identifier: url
rss:
note: description
tags: category/child::text()
digg:
links:
name: Dugg
description: Links you dugg
html_form: '[_1] dugg the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://digg.com/users/{{ident}}/history/diggs.rss'
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
submitted:
name: Submissions
description: Links you submitted
html_form: '[_1] submitted the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://digg.com/users/{{ident}}/history/submissions.rss
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
ffffound:
favorites:
name: Found
description: Photos you found
html_form: '[_1] ffffound <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://ffffound.com/home/{{ident}}/found/feed
rss: 1
flickr:
favorites:
name: Favorites
description: Photos you marked as favorites
fields:
- by
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite photo'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_faves.gne?nsid={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
by: author/name
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_public.gne?id={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
friendfeed:
likes:
name: Likes
description: Things from your friends that you "like"
html_form: '[_1] likes <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://friendfeed.com/{{ident}}/likes?format=atom'
atom:
url: link/@href
gametap:
scores:
name: Leaderboard scores
description: Your high scores in games with leaderboards
fields:
- score
html_form: '[_1] scored <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- score
- url
- title
url: http://www.gametap.com/profile/leaderboards.do?sn={{ident}}
identifier: title,score
scraper:
foreach: 'div.buddy-leaderboards div.tr'
get:
url:
- 'div.name a'
- '@href'
title:
- 'div.name strong'
- TEXT
score:
- 'div.name div'
- TEXT
goodreads:
toread:
name: To read
description: Books on your "to-read" shelf
fields:
- by
html_form: '[_1] saved <a href="[_2]"><i>[_3]</i> by [_4]</a> to read'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=to-read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
reading:
name: Reading
description: Books on your "currently-reading" shelf
fields:
- by
html_form: '[_1] started reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=currently-reading'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
read:
name: Read
description: Books on your "read" shelf
fields:
- by
html_form: '[_1] finished reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
googlereader:
links:
name: Shared
description: Your shared items
+ fields:
+ - note
+ - source_title
+ - source_url
+ - summary
html_form: '[_1] shared <a href="[_2]">[_3]</a> from <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- source_url
- source_title
- class: GoogleReader
+ url: "http://www.google.com/reader/public/atom/user/{{ident}}/state/com.google/broadcast"
+ atom:
+ summary: summary
+ enclosure: "link[@rel='enclosure']/@href"
+ source_title: source/title
+ source_url: "source/link[@rel='alternate']/@href"
+ note: gr:annotation/content
+ created_on: ''
+ modified_on: ''
iconbuffet:
icons:
name: Deliveries
description: Icon sets you were delivered
html_form: '[_1] received the icon set <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.iconbuffet.com/people/{{ident}};received_packages'
identifier: url
scraper:
foreach: 'div#icons div.preview-sm'
get:
title:
- a span
- TEXT
url:
- a
- '@href'
identica:
statuses:
name: Notices
description: Notices you posted
html_form: '[_1] <a href="[_2]">said</a>, “[_3]”'
html_params:
- url
- title
url: 'http://identi.ca/{{ident}}/rss'
rss:
created_on: dc:date
class: Identica
iminta:
links:
name: Intas
description: Links you saved
html_form: '[_1] is inta <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://iminta.com/people/{{ident}}/rss.xml?inta_source_id=11'
rss: 1
instructables:
favorites:
name: Favorites
description: Instructables you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite'
html_params:
- url
- title
url: http://www.instructables.com/member/{{ident}}/rss.xml?show=good
rss:
created_on: ''
modified_on: ''
thumbnail: imageThumb
istockphoto:
photos:
name: Photos
description: Photos you posted that were approved
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.istockphoto.com/webservices/feeds/?feedFormat=IStockAtom_1_0&feedName=istockfeed.image.newestUploads&feedParams=UserID={{ident}}'
identifier: url
atom:
thumbnail: content/div/a/img/@src
iusethis:
events:
name: Recent events
description: Events from your recent events feed
html_form: '[_1] <a href="[_2]">[_3]</a>'
html_params:
- url
- title
rss: 1
url: 'http://osx.iusethis.com/user/feed.rss/{{ident}}?following=0'
osxapps:
name: Apps you use
description: The applications you saved as ones you use
fields:
- favorite
html_form: '[_1] started using <a href="[_2]">[_3]</a>[quant,_4, (and loves it),,]'
html_params:
- url
- title
- favorite
url: 'http://osx.iusethis.com/user/{{ident}}'
iwatchthis:
favorites:
name: Favorites
description: Videos you saved as watched
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video'
html_params:
- url
- title
url: 'http://iwatchthis.com/rss/{{ident}}'
rss: 1
jaiku:
jaikus:
name: Jaikus
description: Jaikus you posted
html_form: '[_1] <a href="[_2]">jaiku''d</a>, "[_3]"'
html_params:
- url
- title
url: 'http://{{ident}}.jaiku.com/feed/atom'
atom: 1
kongregate:
favorites:
name: Favorites
description: Games you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite game'
html_params:
- url
- title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url
scraper:
foreach: #favorites dl
get:
url:
- dd a
- '@href'
title:
- dd a
- TEXT
thumbnail:
- dt img
- '@src'
achievements:
name: Achievements
description: Achievements you won
fields:
- game_title
html_form: '[_1] won the <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- title
- url
- game_title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url,title
scraper:
foreach: #achievements .badge_details
get:
url:
- dt.badge_img a
- '@href'
thumbnail:
- dt.badge_img img
- '@style'
title:
- dd.badge_name
- TEXT
game_title:
- a.badge_game
- TEXT
lastfm:
tracks:
name: Tracks
description: Songs you recently listened to (High spam potential!)
html_form: '[_1] heard <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/recenttracks.rss'
rss: 1
lovedtracks:
name: Loved Tracks
description: Songs you marked as "loved"
fields:
- artist
html_form: '[_1] loved <a href="[_2]">[_3]</a> by [_4]'
html_params:
- url
- title
- artist
url: 'http://pipes.yahoo.com/pipes/pipe.run?_id=4smlkvMW3RGPpBPfTqoASA&_render=rss&lastFM_UserName={{ident}}'
identifier: url
rss:
artist: description
journalentries:
name: Journal Entries
description: Your recent journal entries
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/journals.rss'
rss: 1
events:
name: Events
description: The events you said you'll be attending
html_form: '[_1] is attending <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/events.rss'
rss: 1
livejournal:
posts:
name: Posts
description: Your public posts to your journal
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://users.livejournal.com/{{ident}}/data/atom'
atom: 1
magnolia:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ma.gnolia.com/atom/full/people/{{ident}}'
identifier: url
atom:
tags: "category[@scheme='http://ma.gnolia.com/tags']/@term"
note: content
metafilter:
favorites:
name: Favorites
description: Posts you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite'
html_params:
- url
- title
url: 'http://www.metafilter.com/favorites/{{ident}}/posts/rss'
rss:
created_on: ''
netflix:
queue:
name: Queue
description: Movies you added to your rental queue
fields:
- queue
html_form: '[_1] queued <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/QueueRSS?id={{ident}}'
rss:
thumbnail: description
recent:
name: Recent Movies
description: Recent Rental Activity
fields:
- recent
html_form: '[_1] is watching <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/TrackingRSS?id={{ident}}'
rss:
thumbnail: description
netvibes:
links:
name: Links
description: Links you saved
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www2.netvibes.com/rest/account/{{ident}}/timeline?format=atom'
atom: 1
nytimes:
links:
name: Recommendations
description: Recommendations in your TimesPeople activities
html_form: '[_1] recommended <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://timespeople.nytimes.com/view/user/{{ident}}/rss.xml'
rss: 1
ohloh:
kudos:
name: Kudos
description: Kudos you have received
html_form: '[_1] received kudos from <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.ohloh.net/accounts/{{ident}}/kudos'
identifier: url
scraper:
foreach: 'div.received_kudo'
get:
url:
- a
- '@href'
title:
- a
- TEXT
pandora:
favorites:
name: Favorite Songs
description: Songs you marked as favorites
fields:
- album_art
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite song'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favorites.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
album_art: pandora:albumArtUrl
favoriteartists:
name: Favorite Artists
description: Artists you marked as favorites
fields:
- artist-photo-url
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite artist'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favoriteartists.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
artist-photo-url: pandora:stationImageUrl
stations:
name: Stations
description: Radio stations you added
fields:
- guid
- station-image-url
html_form: '[_1] added a new radio station named <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/stations.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: pandora:stationLink
station-image-url: pandora:stationImageUrl
picasaweb:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://picasaweb.google.com/data/feed/api/user/{{ident}}?kind=photo&max-results=15'
atom:
thumbnail: media:group/media:thumbnail[position()=2]/@url
p0pulist:
stuff:
name: List
description: Things you put in your list
html_form: '[_1] is enjoying <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://p0p.com/list/hot_list/{{ident}}.rss'
rss:
thumbnail: image/url
pownce:
statuses:
name: Notes
description: Your public notes
fields:
- note
html_form: '[_1] <a href="[_2]">posted</a>, "[_3]"'
html_params:
- url
- note
url: 'http://pownce.com/feeds/public/{{ident}}/'
atom:
note: summary
reddit:
comments:
name: Comments
description: Comments you posted
html_form: '[_1] commented on <a href="[_2]">[_3]</a> at Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/comments/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
submitted:
name: Submissions
description: Articles you submitted
html_form: '[_1] submitted <a href="[_2]">[_3]</a> to Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/submitted/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
favorites:
name: Likes
description: Articles you liked (your votes must be public)
html_form: '[_1] liked <a href="[_2]">[_3]</a> from Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/liked/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
dislikes:
name: Dislikes
description: Articles you disliked (your votes must be public)
html_form: '[_1] disliked <a href="[_2]">[_3]</a> on Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/disliked/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
slideshare:
favorites:
name: Favorites
description: Slideshows you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite slideshow'
html_params:
- url
- title
url: 'http://www.slideshare.net/rss/user/{{ident}}/favorites'
rss:
thumbnail: media:content/media:thumbnail/@url
created_on: ''
slideshows:
name: Slideshows
description: Slideshows you posted
html_form: '[_1] posted the slideshow <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.slideshare.net/rss/user/{{ident}}'
rss:
thumbnail: media:content/media:thumbnail/@url
smugmug:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">a photo</a>'
html_params:
- url
url: 'http://www.smugmug.com/hack/feed.mg?Type=nicknameRecentPhotos&Data={{ident}}&format=atom10&ImageCount=15'
atom:
thumbnail: id
steam:
achievements:
name: Achievements
description: Your achievements for achievement-enabled games
html_form: '[_1] won the <strong>[_2]</strong> achievement in <a href="http://steamcommunity.com/id/[_3]/stats/[_4]?tab=achievements">[_5]</a>'
html_params:
- title
- ident
- gamecode
- game
class: Steam
tumblr:
events:
|
markpasc/mt-plugin-action-streams
|
5919284afcb0a00f732cd4229ee9daabfa32ace1
|
Only look at personalized pages for Steam achievements (to avoid UUVs)
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event/Steam.pm b/plugins/ActionStreams/lib/ActionStreams/Event/Steam.pm
index 5e5c486..986f5b6 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event/Steam.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event/Steam.pm
@@ -1,97 +1,100 @@
package ActionStreams::Event::Steam;
use strict;
use base qw( ActionStreams::Event );
use ActionStreams::Scraper;
__PACKAGE__->install_properties({
class_type => 'steam_achievements',
});
__PACKAGE__->install_meta({
columns => [ qw(
gametitle
gamecode
ident
description
) ],
});
my %game_for_code = (
Portal => 'Portal',
TF2 => 'Team Fortress 2',
'HL2:EP2' => 'Half-Life 2: Episode Two',
'DOD:S' => 'Day of Defeat: Source',
);
sub game {
my $event = shift;
return $event->gametitle || $game_for_code{$event->gamecode}
|| $event->gamecode;
}
sub update_events {
my $class = shift;
my %profile = @_;
my ($ident, $author) = @profile{qw( ident author )};
my $achv_scraper = scraper {
process q{div#BG_top h2},
'title' => 'TEXT';
process q{//div[@class='achievementClosed']},
'achvs[]' => scraper {
process 'h3', 'title' => 'TEXT';
process 'h5', 'description' => 'TEXT';
process 'img', 'thumbnail' => '@src';
};
};
my $games = $class->fetch_scraper(
url => "http://steamcommunity.com/id/$ident/games",
scraper => scraper {
process q{div#mainContents a.linkStandard},
'urls[]' => '@href';
result 'urls';
},
);
return if !$games;
- for my $url (@$games) {
+ URL: for my $url (@$games) {
my $gamecode = "$url";
$gamecode =~ s{ \A .* / }{}xms;
$url = "$url?tab=achievements"; # TF2's stats page has tabs
+
+ next URL if $url !~ m{ \Q$ident\E }xms;
+
my $items = $class->fetch_scraper(
url => $url,
scraper => $achv_scraper,
);
- next if !$items;
+ next URL if !$items;
my ($title, $achvs) = @$items{qw( title achvs )};
$title =~ s{ \s* Stats \z }{}xmsi;
for my $item (@$achvs) {
$item->{gametitle} = $title;
$item->{ident} = $ident;
$item->{gamecode} = $gamecode;
$item->{url} = $url;
# Stringify thumbnail url as our complicated structure
# prevents fetch_scraper() from stringifying it for us.
$item->{thumbnail} = q{} . $item->{thumbnail};
}
$class->build_results(
author => $author,
items => $achvs,
identifier => 'ident,gamecode,title',
);
}
1;
}
1;
|
markpasc/mt-plugin-action-streams
|
7efee61b1afcd9ea2ed6b6812e1bd9e59a65aa93
|
Don't look for a thumbnail URL where there isn't one (prevents UUV in Kongregate achievements stream)
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Fix.pm b/plugins/ActionStreams/lib/ActionStreams/Fix.pm
index ba4905c..1d24ba6 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Fix.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Fix.pm
@@ -1,157 +1,157 @@
package ActionStreams::Fix;
use strict;
use warnings;
use ActionStreams::Scraper;
sub _twitter_add_tags_to_item {
my ($item) = @_;
if (my @tags = $item->{title} =~ m{
(?: \A | \s ) # BOT or whitespace
\# # hash
(\w\S*\w) # tag
(?<! 's ) # but don't end with 's
}xmsg) {
$item->{tags} = \@tags;
}
}
sub twitter_tweet_name {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the Twitter username from the front of the tweet.
my $ident = $profile->{ident};
$item->{title} =~ s{ \A \s* \Q$ident\E : \s* }{}xmsi;
_twitter_add_tags_to_item($item);
}
sub twitter_favorite_author {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the Twitter username from the front of the tweet.
if ($item->{title} =~ s{ \A \s* ([^\s:]+) : \s* }{}xms) {
$item->{tweet_author} = $1;
}
_twitter_add_tags_to_item($item);
}
sub flickr_photo_thumbnail {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Extract just the URL, and use the _t size thumbnail, not the _m size image.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ (http://farm[^\.]+\.static\.flickr\.com .*? _m.jpg) }xms) {
$thumb = $1;
$thumb =~ s{ _m.jpg \z }{_t.jpg}xms;
$item->{thumbnail} = $thumb;
}
}
sub iminta_link_title {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the username for when we add it back in later.
$item->{title} =~ s{ (?: \s* :: [^:]+ ){2} \z }{}xms;
}
sub instructables_favorites_thumbnails {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{thumbnail} = URI->new_abs($item->{thumbnail}, 'http://www.instructables.com/')
if $item->{thumbnail};
}
sub iusethis_event_title {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the username for when we add it back in later.
$item->{title} =~ s{ \A \w+ \s* }{}xms;
}
sub metafilter_favorites_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{title} =~ s{ \A [^:]+ : \s* }{}xms;
}
sub netflix_recent_prefix_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the 'Shipped:' or 'Received:' prefix.
$item->{title} =~ s{ \A [^:]*: \s* }{}xms;
# Extract thumbnail from description.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m/ <img src="([^"]+)"} /xms) {
$item->{thumbnail} = $1;
}
}
sub netflix_queue_prefix_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the item number.
$item->{title} =~ s{ \A \d+ [\W\S] \s* }{}xms;
# Extract thumbnail from description.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m/ <img src="([^"]+)"} /xms) {
$item->{thumbnail} = $1;
}
}
sub nytimes_links_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
return $item->{title} =~ s{ \A [^:]* recommended [^:]* : \s* }{}xms ? 1 : 0;
}
sub p0pulist_stuff_urls {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{url} =~ s{ \A / }{http://p0pulist.com/}xms;
}
sub kongregate_achievement_title_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the parenthetical from the end of the title.
$item->{title} =~ s{ \( [^)]* \) \z }{}xms;
# Pick the actual achievement badge out of the inline CSS.
- my $thumb = delete $item->{thumbnail};
+ my $thumb = delete $item->{thumbnail} || q{};
if ($thumb =~ m{ background-image: \s* url\( ([^)]+) }xms) {
$item->{thumbnail} = $1;
}
}
sub wists_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Grab the wists thumbnail out.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ (http://cache.wists.com/thumbnails/ [^"]+ ) }xms) {
$item->{thumbnail} = $1;
}
}
sub gametap_score_stuff {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{score} =~ s{ \D }{}xmsg;
$item->{url} = q{} . $item->{url};
$item->{url} =~ s{ \A / }{http://www.gametap.com/}xms;
}
sub typepad_comment_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{title} =~ s{ \A .*? ' }{}xms;
$item->{title} =~ s{ ' \z }{}xms;
}
sub magnolia_link_notes {
my ($cb, $app, $item, $event, $author, $profile) = @_;
my $scraper = scraper {
process '//p[position()=2]', note => 'TEXT';
};
my $result = $scraper->scrape(\$item->{note});
if ($result->{note}) {
$item->{note} = $result->{note};
}
else {
delete $item->{note};
}
}
1;
|
markpasc/mt-plugin-action-streams
|
937661b96da36cf289670d8a7110f1dbd9bab207
|
I guess the grep block is explicitly required
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm
index 7db3326..b2ce484 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm
@@ -1,850 +1,850 @@
package ActionStreams::Event;
use strict;
use base qw( MT::Object MT::Taggable MT::Scorable );
our @EXPORT_OK = qw( classes_for_type );
use HTTP::Date qw( str2time );
use MT::Util qw( encode_html encode_url );
use MT::I18N;
use ActionStreams::Scraper;
our $hide_timeless = 0;
__PACKAGE__->install_properties({
column_defs => {
id => 'integer not null auto_increment',
identifier => 'string(200)',
author_id => 'integer not null',
visible => 'integer not null',
},
defaults => {
visible => 1,
},
indexes => {
identifier => 1,
author_id => 1,
created_on => 1,
created_by => 1,
},
class_type => 'event',
audit => 1,
meta => 1,
datasource => 'profileevent',
primary_key => 'id',
});
__PACKAGE__->install_meta({
columns => [ qw(
title
url
thumbnail
via
via_id
) ],
});
# Oracle does not like an identifier of more than 30 characters.
sub datasource {
my $class = shift;
my $r = MT->request;
my $ds = $r->cache('as_event_ds');
return $ds if $ds;
my $dss_oracle = qr/(db[id]::)?oracle/;
if ( my $type = MT->config('ObjectDriver') ) {
if ((lc $type) =~ m/^$dss_oracle$/) {
$ds = 'as';
}
}
$ds = $class->properties->{datasource}
unless $ds;
$r->cache('as_event_ds', $ds);
return $ds;
}
sub encode_field_for_html {
my $event = shift;
my ($field) = @_;
return encode_html( $event->$field() );
}
sub as_html {
my $event = shift;
my %params = @_;
my $stream = $event->registry_entry or return '';
# How many spaces are there in the form?
my $form = $params{form} || $stream->{html_form} || q{};
my @nums = $form =~ m{ \[ _ (\d+) \] }xmsg;
my $max = shift @nums;
for my $num (@nums) {
$max = $num if $max < $num;
}
# Do we need to supply the author name?
my @content = map { $event->encode_field_for_html($_) }
@{ $stream->{html_params} };
if ($max > scalar @content) {
my $name = defined $params{name} ? $params{name}
: $event->author->nickname
;
unshift @content, encode_html($name);
}
return MT->translate($form, @content);
}
sub update_events_loggily {
my $class = shift;
my %profile = @_;
# Keep this option out of band so we don't have to count on
# implementations of update_events() passing it through.
local $hide_timeless = delete $profile{hide_timeless} ? 1 : 0;
my $warn = $SIG{__WARN__} || sub { print STDERR $_[0] };
local $SIG{__WARN__} = sub {
my ($msg) = @_;
$msg =~ s{ \n \z }{}xms;
$msg = MT->component('ActionStreams')->translate(
'[_1] updating [_2] events for [_3]',
$msg, $profile{type}, $profile{author}->name,
);
$warn->("$msg\n");
};
eval {
$class->update_events(%profile);
};
if (my $err = $@) {
my $plugin = MT->component('ActionStreams');
my $err_msg = $plugin->translate("Error updating events for [_1]'s [_2] stream (type [_3] ident [_4]): [_5]",
$profile{author}->name, $class->properties->{class_type},
$profile{type}, $profile{ident}, $err);
MT->log($err_msg);
die $err; # re-throw so we can handle from job invocation
}
}
sub update_events {
my $class = shift;
my %profile = @_;
my $author = delete $profile{author};
my $stream = $class->registry_entry or return;
my $fetch = $stream->{fetch} || {};
local $profile{url} = $stream->{url};
die "Oops, no url?" if !$profile{url};
die "Oops, no ident?" if !$profile{ident};
require MT::I18N;
my $ident = encode_url(MT::I18N::encode_text($profile{ident}, undef, 'utf-8'));
$profile{url} =~ s/ {{ident}} / $ident /xmsge;
my $items;
if (my $xpath_params = $stream->{xpath}) {
$items = $class->fetch_xpath(
%$xpath_params,
%$fetch,
%profile,
);
}
elsif (my $atom_params = $stream->{atom}) {
my $get = {
created_on => 'published',
modified_on => 'updated',
title => 'title',
url => q{link[@rel='alternate']/@href},
via => q{link[@rel='alternate']/@href},
via_id => 'id',
identifier => 'id',
};
$atom_params = {} if !ref $atom_params;
@$get{keys %$atom_params} = values %$atom_params;
$items = $class->fetch_xpath(
foreach => '//entry',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $rss_params = $stream->{rss}) {
my $get = {
title => 'title',
url => 'link',
via => 'link',
created_on => 'pubDate',
thumbnail => 'media:thumbnail/@url',
via_id => 'guid',
identifier => 'guid',
};
$rss_params = {} if !ref $rss_params;
@$get{keys %$rss_params} = values %$rss_params;
$items = $class->fetch_xpath(
foreach => '//item',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $scraper_params = $stream->{scraper}) {
my ($foreach, $get) = @$scraper_params{qw( foreach get )};
my $scraper = scraper {
process $foreach, 'res[]' => scraper {
while (my ($field, $sel) = each %$get) {
process $sel->[0], $field => $sel->[1];
}
};
result 'res';
};
$items = $class->fetch_scraper(
scraper => $scraper,
%$fetch,
%profile,
);
}
return if !$items;
$class->build_results(
items => $items,
stream => $stream,
author => $author,
profile => \%profile,
);
}
sub registry_entry {
my $event = shift;
my ($type, $stream) = split /_/, $event->properties->{class_type}, 2;
my $reg = MT->instance->registry('action_streams') or return;
my $service = $reg->{$type} or return;
$service->{$stream};
}
sub author {
my $event = shift;
my $author_id = $event->author_id
or return;
return MT->instance->model('author')->lookup($author_id);
}
sub blog_id { 0 }
sub classes_for_type {
my $class = shift;
my ($type) = @_;
my $prevts = MT->instance->registry('action_streams');
my $prevt = $prevts->{$type};
return if !$prevt;
my @classes;
PACKAGE: while (my ($stream_id, $stream) = each %$prevt) {
next if 'HASH' ne ref $stream;
next if !$stream->{class} && !$stream->{url};
# This check intentionally fails a lot, so ignore any DIE handler we
# might have.
my $has_props = sub {
my $pkg = shift;
return eval { local $SIG{__DIE__}; $pkg->properties };
};
my $pkg;
if ($pkg = $stream->{class}) {
$pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms;
if (!$has_props->($pkg)) {
if (!eval "require $pkg; 1") {
my $error = $@ || q{};
my $pl = MT->component('ActionStreams');
MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]',
$pkg, $type, $stream_id, $error));
next PACKAGE;
}
}
}
else {
$pkg = join q{::}, $class, 'Auto', ucfirst $type,
ucfirst $stream_id;
if (!$has_props->($pkg)) {
eval "package $pkg; use base qw( $class ); 1" or next PACKAGE;
my $class_type = join q{_}, $type, $stream_id;
$pkg->install_properties({ class_type => $class_type });
$pkg->install_meta({ columns => $stream->{fields} })
if $stream->{fields};
}
}
push @classes, $pkg;
}
return @classes;
}
my $ua;
sub ua {
my $class = shift;
my %params = @_;
$ua ||= MT->new_ua({
paranoid => 1,
timeout => 10,
});
$ua->max_size(250_000) if $ua->can('max_size');
$ua->agent($params{default_useragent} ? $ua->_agent
: "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version);
return $ua if $class->class_type eq 'event';
return $ua if $params{unconditional};
require ActionStreams::UserAgent::Adapter;
my $adapter = ActionStreams::UserAgent::Adapter->new(
ua => $ua,
action_type => $class->class_type,
die_on_not_modified => $params{die_on_not_modified} || 0,
);
return $adapter;
}
sub set_values {
my $event = shift;
my ($values) = @_;
for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) {
my $meta_val = delete $values->{$meta_col};
$event->$meta_col($meta_val) if defined $meta_val;
}
$event->SUPER::set_values($values);
}
sub fetch_xpath {
my $class = shift;
my %params = @_;
my $url = $params{url} || '';
if (!$url) {
MT->log(
MT->component('ActionStreams')->translate(
"No URL to fetch for [_1] results", $class));
return;
}
my $ua = $class->ua(%params);
my $res = $ua->get($url);
if (!$res->is_success()) {
MT->log(
MT->component('ActionStreams')->translate(
"Could not fetch [_1]: [_2]", $url, $res->status_line()))
if $res->code != 304;
return;
}
# Do not continue if contents is incomplete.
if (my $abort = $res->{_headers}{'client-aborted'}) {
MT->log(
MT->component('ActionStreams')->translate(
'Aborted fetching [_1]: [_2]', $url, $abort));
return;
}
# Strip leading whitespace, since the parser doesn't like it.
# TODO: confirm we got xml?
my $content = $res->content;
$content =~ s{ \A \s+ }{}xms;
require XML::XPath;
my $x = XML::XPath->new( xml => $content );
my @items;
ITEM: for my $item ($x->findnodes($params{foreach})) {
my %item_data;
VALUE: while (my ($key, $val) = each %{ $params{get} }) {
next VALUE if !$val;
if ($key eq 'tags') {
my @outvals = $item->findnodes($val)
or next VALUE;
- $item_data{$key} = [ grep map { MT::I18N::utf8_off( $_->getNodeValue ) } @outvals ];
+ $item_data{$key} = [ grep { $_ } map { MT::I18N::utf8_off($_->getNodeValue) } @outvals ];
}
else {
my $outval = $item->findvalue($val)
or next VALUE;
$outval = MT::I18N::utf8_off("$outval");
if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) {
# try both RFC 822/1123 and ISO 8601 formats
my $out_timestamp;
if (my $epoch = str2time($outval)) {
$out_timestamp = MT::Util::epoch2ts(undef, $epoch);
}
# The epoch2ts may have failed too.
if (!defined $out_timestamp) {
$out_timestamp = MT::Util::iso2ts(undef, $outval);
}
# Whether it's defined or not, that's our new outval.
$outval = $out_timestamp;
}
$item_data{$key} = $outval if $outval;
}
}
push @items, \%item_data;
}
return \@items;
}
sub build_results {
my $class = shift;
my %params = @_;
my ($author, $items, $profile, $stream) =
@params{qw( author items profile stream )};
my $mt = MT->app;
ITEM: for my $item (@$items) {
my $event;
my $identifier = delete $item->{identifier};
if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) {
$identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} };
}
if (defined $identifier) {
$identifier = "$identifier";
($event) = $class->search({
author_id => $author->id,
identifier => $identifier,
});
}
$event ||= $class->new;
$mt->run_callbacks('filter_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile)
or return;
$mt->run_callbacks('pre_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
my $tags = delete $item->{tags};
$event->set_values({
author_id => $author->id,
identifier => $identifier,
%$item,
});
$event->tags(@$tags) if $tags && @$tags;
if ($hide_timeless && !$event->created_on) {
$event->visible(0);
}
$mt->run_callbacks('post_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
$event->save() or MT->log($event->errstr);
}
1;
}
sub save {
my $event = shift;
# Built-in audit field setting will set a local time, so do it ourselves.
if (!$event->created_on) {
my $ts = MT::Util::epoch2ts(undef, time);
$event->created_on($ts);
$event->modified_on($ts);
}
return $event->SUPER::save(@_);
}
sub fetch_scraper {
my $class = shift;
my %params = @_;
my ($url, $scraper) = @params{qw( url scraper )};
$scraper->user_agent( $class->ua( %params, die_on_not_modified => 1 ) );
my $uri_obj = URI->new($url);
my $items = eval { $scraper->scrape($uri_obj) };
# Ignore Web::Scraper errors due to 304 Not Modified responses.
if (!$items && $@ && !UNIVERSAL::isa($@, 'ActionStreams::UserAgent::NotModified')) {
die; # rethrow
}
# we're only being used for our scraper.
return if !$items;
return $items if !ref $items;
return $items if 'ARRAY' ne ref $items;
ITEM: for my $item (@$items) {
next ITEM if !ref $item || ref $item ne 'HASH';
for my $field (keys %$item) {
if ($field eq 'tags') {
$item->{$field} = [ map { MT::I18N::utf8_off( "$_" ) } @{ $item->{$field} } ];
}
elsif (defined $item->{$field}) {
$item->{$field} = MT::I18N::utf8_off( q{} . $item->{$field} );
}
else {
delete $item->{$field};
}
}
}
return $items;
}
sub backup_terms_args {
my $class = shift;
my ($blog_ids) = @_;
return { terms => { 'class' => '*' }, args => undef };
}
1;
__END__
=head1 NAME
ActionStreams::Event - an Action Streams stream definition
=head1 SYNOPSIS
# in plugin's config.yaml
profile_services:
example:
streamid:
name: Dice Example
description: A simple die rolling Perl stream example.
html_form: [_1] rolled a [_2]!
html_params:
- title
class: My::Stream
# in plugin's lib/My/Stream.pm
package My::Stream;
use base qw( ActionStreams::Event );
__PACKAGE__->install_properties({
class_type => 'example_streamid',
});
sub update_events {
my $class = shift;
my %profile = @_;
# trivial example: save a random number
my $die_roll = int rand 20;
my %item = (
title => $die_roll,
identifier => $die_roll,
);
return $class->build_results(
author => $profile{author},
items => [ \%item ],
);
}
1;
=head1 DESCRIPTION
I<ActionStreams::Event> provides the basic implementation of an action stream.
Stream definitions are engines for turning web resources into I<actions> (also
called I<events>). This base class produces actions based on generic stream
recipes defined in the MT registry, as well as providing the internal machinery
for you to implement your own streams in Perl code.
=head1 METHODS TO IMPLEMENT
These are the methods one commonly implements (overrides) when implementing a
stream subclass.
=head2 C<$class-E<gt>update_events(%profile)>
Fetches the web resource specified by the profile parameters, collects data
from it into actions, and saves the action records for use later. Required
members of C<%profile> are:
=over 4
=item * C<author>
The C<MT::Author> instance for whom events should be collected.
=item * C<ident>
The author's identifier on the given service.
=back
Other information about the stream, such as the URL pattern into which the
C<ident> parameter can be replaced, is available through the
C<$class-E<gt>registry_entry()> method.
=head2 C<$self-E<gt>as_html(%params)>
Returns the HTML version of the action, suitable for display to readers.
The default implementation uses the stream's registry definition to construct
the action: the author's name and the action's values as named in
C<html_params> are replaced into the stream's C<html_form> setting. You need
override it only if you have more complex requirements.
Optional members of C<%params> are:
=over 4
=item * C<form>
The formatting string to use. If not given, the C<html_form> specified for
this stream in the registry is used.
=item * C<name>
The text to use as the author's name if C<as_html> needs to provide it
automatically in the result. Author names are provided if there are more
tokens in C<html_form> than there are fields specified in C<html_params>.
If not given, the event's author's nickname is provided. Note that a defined
but empty name (such as C<q{}>) I<will> be used; in this case, the name will
appear to be omitted from the result of the C<as_html> call.
=back
=head1 AVAILABLE METHODS
These are the methods provided by I<ActionStreams::Event> to perform common
tasks. Call them from your overridden methods.
=head2 C<$self-E<gt>set_values(\%values)>
Stores the data given in C<%values> as members of this event.
=head2 C<$class-E<gt>fetch_xpath(%param)>
Returns the items discovered by scanning a web resource by the given XPath
recipe. Required members of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be a
valid XML document.
=item * C<foreach>
The XPath selector with which to select the individual events from the
resource.
=item * C<get>
A hashref containing the XPath selectors with which to collect individual data
for each item, keyed on the names of the fields to contain the data.
=back
C<%param> may also contain additional arguments for the C<ua()> method.
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
=head2 C<$class-E<gt>fetch_scraper(%param)>
Returns the items discovered by scanning by the given recipe. Required members
of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be an
HTML or XML document suitable for analysis by the C<Web::Scraper> module.
=item * C<scraper>
The C<Web::Scraper> scraper with which to extract item data from the specified
web resource. See L<Web::Scraper> for information on how to construct a
scraper.
=back
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
See also the below I<NOTE ON WEB::SCRAPER>.
=head2 C<$class-E<gt>build_results(%param)>
Converts a set of collected items into saved action records of type C<$class>.
The required members of C<%param> are:
=over 4
=item * C<author>
The C<MT::Author> instance whose action the items represent.
=item * C<items>
An arrayref of items to save as actions. Each item is a hashref containing the
action data, keyed on the names of the fields containing the data.
=back
Optional parameters are:
=over 4
=item * C<profile>
An arrayref describing the data for the author's profile for the associated
stream, such as is returned by the C<MT::Author::other_profile()> method
supplied by the Action Streams plugin.
The profile member is not used directly by C<build_results()>; they are only
passed to callbacks.
=item * C<stream>
A hashref containing the settings from the registry about the stream, such as
is returned from the C<registry_entry()> method.
=back
=head2 C<$class-E<gt>ua(%param)>
Returns the common HTTP user-agent, an instance of C<LWP::UserAgent>, with
which you can fetch web resources.
The resulting user agent may provide automatic conditional HTTP support when
you call its C<get> method. A UA with conditional HTTP support enabled will
store the values of the conditional HTTP headers (C<ETag> and
C<Last-Modified>) received in responses as C<ActionStreams::UserAgent::Cache>
objects and, on subsequent requests of the same URL, automatically supply the
header values. When the remote HTTP server reports that such a resource has
not changed, the C<HTTP::Response> will be a C<304 Not Modified> response; the
user agent does not itself store and supply the resource content. Using other
C<LWP::UserAgent> methods such as C<post> or C<request> will I<not> trigger
automatic conditional HTTP support.
No arguments are required; possible optional parameters are:
=over 4
=item * C<default_useragent>
If set, the returned HTTP user-agent will use C<LWP::UserAgent>'s default
identifier in the HTTP C<User-Agent> header. If omitted, the UA will use the
Action Streams identifier of C<mt-actionstreams-lwp/I<version>>.
=item * C<unconditional>
If set, the return HTTP user-agent will I<not> automatically use conditional
HTTP to avoid requesting old content from compliant servers. That is, if
omitted, the UA I<will> automatically use conditional HTTP when you call its
C<get> method.
=item * C<die_on_not_modified>
If set, when the response of the HTTP user-agent's C<get> method is a
conditional HTTP C<304 Not Modified> response, throw an exception instead of
returning the response. (Use this option to return control to yourself when
passing UAs with conditional HTTP support to other Perl modules that don't
expect 304 responses.)
The thrown exception is an C<ActionStreams::UserAgent::NotModified> exception.
=back
=head2 C<$self-E<gt>author()>
Returns the C<MT::Author> instance associated with this event, if its
C<author_id> field has been set.
=head2 C<$class-E<gt>install_properties(\%properties)>
I<TODO>
=head2 C<$class-E<gt>install_meta(\%properties)>
I<TODO>
=head2 C<$class-E<gt>registry_entry()>
Returns the registry data for the stream represented by C<$class>.
=head2 C<$class-E<gt>classes_for_type($service_id)>
Given a profile service ID (that is, a key from the C<profile_services> section
of the registry), returns a list of stream classes for scanning that service's
streams.
=head2 C<$class-E<gt>backup_terms_args($blog_ids)>
Used in backup. Backup function calls the method to generate $terms and
$args for the class to load objects. ActionStream::Event does not have
blog_id and does use class_column, the nature the class has to tell
backup function to properly load all the target objects of the class
to be backed up.
See I<MT::BackupRestore> for more detail.
=head1 NOTE ON WEB::SCRAPER
The C<Web::Scraper> module is powerful, but it has complex dependencies. While
its pure Perl requirements are bundled with the Action Streams plugin, it also
requires a compiled XML module. Also, because of how its syntax works, you must
directly C<use> the module in your own code, contrary to the Movable Type idiom
of using C<require> so that modules are loaded only when they are sure to be
used.
If you attempt load C<Web::Scraper> in the normal way, but C<Web::Scraper> is
unable to load due to its missing requirement, whenever the plugin attempts to
load your scraper, the entire plugin will fail to load.
Therefore the C<ActionStreams::Scraper> wrapper module is provided for you. If
you need to load C<Web::Scraper> so as to make a scraper to pass
C<ActionStreams::Event::fetch_scraper()> method, instead write in your module:
use ActionStreams::Scraper;
This module provides the C<Web::Scraper> interface, but if C<Web::Scraper> is
unable to load, the error will be thrown when your module tries to I<use> it,
rather than when you I<load> it. That is, if C<Web::Scraper> can't load, no
errors will be thrown to end users until they try to use your stream.
=head1 AUTHOR
Mark Paschal E<lt>[email protected]<gt>
=cut
|
markpasc/mt-plugin-action-streams
|
278df4223eeb4b4af488a3b2aca753d4df52dc35
|
Protect against some more cron-time warnings
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm
index 44aabec..7db3326 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm
@@ -1,839 +1,850 @@
package ActionStreams::Event;
use strict;
use base qw( MT::Object MT::Taggable MT::Scorable );
our @EXPORT_OK = qw( classes_for_type );
use HTTP::Date qw( str2time );
use MT::Util qw( encode_html encode_url );
use MT::I18N;
use ActionStreams::Scraper;
our $hide_timeless = 0;
__PACKAGE__->install_properties({
column_defs => {
id => 'integer not null auto_increment',
identifier => 'string(200)',
author_id => 'integer not null',
visible => 'integer not null',
},
defaults => {
visible => 1,
},
indexes => {
identifier => 1,
author_id => 1,
created_on => 1,
created_by => 1,
},
class_type => 'event',
audit => 1,
meta => 1,
datasource => 'profileevent',
primary_key => 'id',
});
__PACKAGE__->install_meta({
columns => [ qw(
title
url
thumbnail
via
via_id
) ],
});
# Oracle does not like an identifier of more than 30 characters.
sub datasource {
my $class = shift;
my $r = MT->request;
my $ds = $r->cache('as_event_ds');
return $ds if $ds;
my $dss_oracle = qr/(db[id]::)?oracle/;
if ( my $type = MT->config('ObjectDriver') ) {
if ((lc $type) =~ m/^$dss_oracle$/) {
$ds = 'as';
}
}
$ds = $class->properties->{datasource}
unless $ds;
$r->cache('as_event_ds', $ds);
return $ds;
}
sub encode_field_for_html {
my $event = shift;
my ($field) = @_;
return encode_html( $event->$field() );
}
sub as_html {
my $event = shift;
my %params = @_;
my $stream = $event->registry_entry or return '';
# How many spaces are there in the form?
my $form = $params{form} || $stream->{html_form} || q{};
my @nums = $form =~ m{ \[ _ (\d+) \] }xmsg;
my $max = shift @nums;
for my $num (@nums) {
$max = $num if $max < $num;
}
# Do we need to supply the author name?
my @content = map { $event->encode_field_for_html($_) }
@{ $stream->{html_params} };
if ($max > scalar @content) {
my $name = defined $params{name} ? $params{name}
: $event->author->nickname
;
unshift @content, encode_html($name);
}
return MT->translate($form, @content);
}
sub update_events_loggily {
my $class = shift;
my %profile = @_;
# Keep this option out of band so we don't have to count on
# implementations of update_events() passing it through.
local $hide_timeless = delete $profile{hide_timeless} ? 1 : 0;
my $warn = $SIG{__WARN__} || sub { print STDERR $_[0] };
local $SIG{__WARN__} = sub {
my ($msg) = @_;
$msg =~ s{ \n \z }{}xms;
$msg = MT->component('ActionStreams')->translate(
'[_1] updating [_2] events for [_3]',
$msg, $profile{type}, $profile{author}->name,
);
$warn->("$msg\n");
};
eval {
$class->update_events(%profile);
};
if (my $err = $@) {
my $plugin = MT->component('ActionStreams');
my $err_msg = $plugin->translate("Error updating events for [_1]'s [_2] stream (type [_3] ident [_4]): [_5]",
$profile{author}->name, $class->properties->{class_type},
$profile{type}, $profile{ident}, $err);
MT->log($err_msg);
die $err; # re-throw so we can handle from job invocation
}
}
sub update_events {
my $class = shift;
my %profile = @_;
my $author = delete $profile{author};
my $stream = $class->registry_entry or return;
my $fetch = $stream->{fetch} || {};
local $profile{url} = $stream->{url};
die "Oops, no url?" if !$profile{url};
die "Oops, no ident?" if !$profile{ident};
require MT::I18N;
my $ident = encode_url(MT::I18N::encode_text($profile{ident}, undef, 'utf-8'));
$profile{url} =~ s/ {{ident}} / $ident /xmsge;
my $items;
if (my $xpath_params = $stream->{xpath}) {
$items = $class->fetch_xpath(
%$xpath_params,
%$fetch,
%profile,
);
}
elsif (my $atom_params = $stream->{atom}) {
my $get = {
created_on => 'published',
modified_on => 'updated',
title => 'title',
url => q{link[@rel='alternate']/@href},
via => q{link[@rel='alternate']/@href},
via_id => 'id',
identifier => 'id',
};
$atom_params = {} if !ref $atom_params;
@$get{keys %$atom_params} = values %$atom_params;
$items = $class->fetch_xpath(
foreach => '//entry',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $rss_params = $stream->{rss}) {
my $get = {
title => 'title',
url => 'link',
via => 'link',
created_on => 'pubDate',
thumbnail => 'media:thumbnail/@url',
via_id => 'guid',
identifier => 'guid',
};
$rss_params = {} if !ref $rss_params;
@$get{keys %$rss_params} = values %$rss_params;
$items = $class->fetch_xpath(
foreach => '//item',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $scraper_params = $stream->{scraper}) {
my ($foreach, $get) = @$scraper_params{qw( foreach get )};
my $scraper = scraper {
process $foreach, 'res[]' => scraper {
while (my ($field, $sel) = each %$get) {
process $sel->[0], $field => $sel->[1];
}
};
result 'res';
};
$items = $class->fetch_scraper(
scraper => $scraper,
%$fetch,
%profile,
);
}
return if !$items;
$class->build_results(
items => $items,
stream => $stream,
author => $author,
profile => \%profile,
);
}
sub registry_entry {
my $event = shift;
my ($type, $stream) = split /_/, $event->properties->{class_type}, 2;
my $reg = MT->instance->registry('action_streams') or return;
my $service = $reg->{$type} or return;
$service->{$stream};
}
sub author {
my $event = shift;
my $author_id = $event->author_id
or return;
return MT->instance->model('author')->lookup($author_id);
}
sub blog_id { 0 }
sub classes_for_type {
my $class = shift;
my ($type) = @_;
my $prevts = MT->instance->registry('action_streams');
my $prevt = $prevts->{$type};
return if !$prevt;
my @classes;
PACKAGE: while (my ($stream_id, $stream) = each %$prevt) {
next if 'HASH' ne ref $stream;
next if !$stream->{class} && !$stream->{url};
# This check intentionally fails a lot, so ignore any DIE handler we
# might have.
my $has_props = sub {
my $pkg = shift;
return eval { local $SIG{__DIE__}; $pkg->properties };
};
my $pkg;
if ($pkg = $stream->{class}) {
$pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms;
if (!$has_props->($pkg)) {
if (!eval "require $pkg; 1") {
my $error = $@ || q{};
my $pl = MT->component('ActionStreams');
MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]',
$pkg, $type, $stream_id, $error));
next PACKAGE;
}
}
}
else {
$pkg = join q{::}, $class, 'Auto', ucfirst $type,
ucfirst $stream_id;
if (!$has_props->($pkg)) {
eval "package $pkg; use base qw( $class ); 1" or next PACKAGE;
my $class_type = join q{_}, $type, $stream_id;
$pkg->install_properties({ class_type => $class_type });
$pkg->install_meta({ columns => $stream->{fields} })
if $stream->{fields};
}
}
push @classes, $pkg;
}
return @classes;
}
my $ua;
sub ua {
my $class = shift;
my %params = @_;
$ua ||= MT->new_ua({
paranoid => 1,
timeout => 10,
});
$ua->max_size(250_000) if $ua->can('max_size');
$ua->agent($params{default_useragent} ? $ua->_agent
: "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version);
return $ua if $class->class_type eq 'event';
return $ua if $params{unconditional};
require ActionStreams::UserAgent::Adapter;
my $adapter = ActionStreams::UserAgent::Adapter->new(
ua => $ua,
action_type => $class->class_type,
die_on_not_modified => $params{die_on_not_modified} || 0,
);
return $adapter;
}
sub set_values {
my $event = shift;
my ($values) = @_;
for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) {
my $meta_val = delete $values->{$meta_col};
$event->$meta_col($meta_val) if defined $meta_val;
}
$event->SUPER::set_values($values);
}
sub fetch_xpath {
my $class = shift;
my %params = @_;
my $url = $params{url} || '';
if (!$url) {
MT->log(
MT->component('ActionStreams')->translate(
"No URL to fetch for [_1] results", $class));
return;
}
my $ua = $class->ua(%params);
my $res = $ua->get($url);
if (!$res->is_success()) {
MT->log(
MT->component('ActionStreams')->translate(
"Could not fetch [_1]: [_2]", $url, $res->status_line()))
if $res->code != 304;
return;
}
# Do not continue if contents is incomplete.
if (my $abort = $res->{_headers}{'client-aborted'}) {
MT->log(
MT->component('ActionStreams')->translate(
'Aborted fetching [_1]: [_2]', $url, $abort));
return;
}
# Strip leading whitespace, since the parser doesn't like it.
# TODO: confirm we got xml?
my $content = $res->content;
$content =~ s{ \A \s+ }{}xms;
require XML::XPath;
my $x = XML::XPath->new( xml => $content );
my @items;
ITEM: for my $item ($x->findnodes($params{foreach})) {
my %item_data;
VALUE: while (my ($key, $val) = each %{ $params{get} }) {
next VALUE if !$val;
if ($key eq 'tags') {
my @outvals = $item->findnodes($val)
or next VALUE;
- $item_data{$key} = [ map { MT::I18N::utf8_off( $_->getNodeValue ) } @outvals ];
+ $item_data{$key} = [ grep map { MT::I18N::utf8_off( $_->getNodeValue ) } @outvals ];
}
else {
my $outval = $item->findvalue($val)
or next VALUE;
$outval = MT::I18N::utf8_off("$outval");
if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) {
# try both RFC 822/1123 and ISO 8601 formats
- $outval = MT::Util::epoch2ts(undef, str2time($outval))
- || MT::Util::iso2ts(undef, $outval);
+ my $out_timestamp;
+ if (my $epoch = str2time($outval)) {
+ $out_timestamp = MT::Util::epoch2ts(undef, $epoch);
+ }
+ # The epoch2ts may have failed too.
+ if (!defined $out_timestamp) {
+ $out_timestamp = MT::Util::iso2ts(undef, $outval);
+ }
+ # Whether it's defined or not, that's our new outval.
+ $outval = $out_timestamp;
}
$item_data{$key} = $outval if $outval;
}
}
push @items, \%item_data;
}
return \@items;
}
sub build_results {
my $class = shift;
my %params = @_;
my ($author, $items, $profile, $stream) =
@params{qw( author items profile stream )};
my $mt = MT->app;
ITEM: for my $item (@$items) {
my $event;
my $identifier = delete $item->{identifier};
if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) {
$identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} };
}
if (defined $identifier) {
$identifier = "$identifier";
($event) = $class->search({
author_id => $author->id,
identifier => $identifier,
});
}
$event ||= $class->new;
$mt->run_callbacks('filter_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile)
or return;
$mt->run_callbacks('pre_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
my $tags = delete $item->{tags};
$event->set_values({
author_id => $author->id,
identifier => $identifier,
%$item,
});
- $event->tags(@$tags) if $tags;
+ $event->tags(@$tags) if $tags && @$tags;
if ($hide_timeless && !$event->created_on) {
$event->visible(0);
}
$mt->run_callbacks('post_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
$event->save() or MT->log($event->errstr);
}
1;
}
sub save {
my $event = shift;
# Built-in audit field setting will set a local time, so do it ourselves.
if (!$event->created_on) {
my $ts = MT::Util::epoch2ts(undef, time);
$event->created_on($ts);
$event->modified_on($ts);
}
return $event->SUPER::save(@_);
}
sub fetch_scraper {
my $class = shift;
my %params = @_;
my ($url, $scraper) = @params{qw( url scraper )};
$scraper->user_agent( $class->ua( %params, die_on_not_modified => 1 ) );
my $uri_obj = URI->new($url);
my $items = eval { $scraper->scrape($uri_obj) };
# Ignore Web::Scraper errors due to 304 Not Modified responses.
if (!$items && $@ && !UNIVERSAL::isa($@, 'ActionStreams::UserAgent::NotModified')) {
die; # rethrow
}
# we're only being used for our scraper.
return if !$items;
return $items if !ref $items;
return $items if 'ARRAY' ne ref $items;
ITEM: for my $item (@$items) {
next ITEM if !ref $item || ref $item ne 'HASH';
for my $field (keys %$item) {
if ($field eq 'tags') {
$item->{$field} = [ map { MT::I18N::utf8_off( "$_" ) } @{ $item->{$field} } ];
}
- else {
+ elsif (defined $item->{$field}) {
$item->{$field} = MT::I18N::utf8_off( q{} . $item->{$field} );
}
+ else {
+ delete $item->{$field};
+ }
}
}
return $items;
}
sub backup_terms_args {
my $class = shift;
my ($blog_ids) = @_;
return { terms => { 'class' => '*' }, args => undef };
}
1;
__END__
=head1 NAME
ActionStreams::Event - an Action Streams stream definition
=head1 SYNOPSIS
# in plugin's config.yaml
profile_services:
example:
streamid:
name: Dice Example
description: A simple die rolling Perl stream example.
html_form: [_1] rolled a [_2]!
html_params:
- title
class: My::Stream
# in plugin's lib/My/Stream.pm
package My::Stream;
use base qw( ActionStreams::Event );
__PACKAGE__->install_properties({
class_type => 'example_streamid',
});
sub update_events {
my $class = shift;
my %profile = @_;
# trivial example: save a random number
my $die_roll = int rand 20;
my %item = (
title => $die_roll,
identifier => $die_roll,
);
return $class->build_results(
author => $profile{author},
items => [ \%item ],
);
}
1;
=head1 DESCRIPTION
I<ActionStreams::Event> provides the basic implementation of an action stream.
Stream definitions are engines for turning web resources into I<actions> (also
called I<events>). This base class produces actions based on generic stream
recipes defined in the MT registry, as well as providing the internal machinery
for you to implement your own streams in Perl code.
=head1 METHODS TO IMPLEMENT
These are the methods one commonly implements (overrides) when implementing a
stream subclass.
=head2 C<$class-E<gt>update_events(%profile)>
Fetches the web resource specified by the profile parameters, collects data
from it into actions, and saves the action records for use later. Required
members of C<%profile> are:
=over 4
=item * C<author>
The C<MT::Author> instance for whom events should be collected.
=item * C<ident>
The author's identifier on the given service.
=back
Other information about the stream, such as the URL pattern into which the
C<ident> parameter can be replaced, is available through the
C<$class-E<gt>registry_entry()> method.
=head2 C<$self-E<gt>as_html(%params)>
Returns the HTML version of the action, suitable for display to readers.
The default implementation uses the stream's registry definition to construct
the action: the author's name and the action's values as named in
C<html_params> are replaced into the stream's C<html_form> setting. You need
override it only if you have more complex requirements.
Optional members of C<%params> are:
=over 4
=item * C<form>
The formatting string to use. If not given, the C<html_form> specified for
this stream in the registry is used.
=item * C<name>
The text to use as the author's name if C<as_html> needs to provide it
automatically in the result. Author names are provided if there are more
tokens in C<html_form> than there are fields specified in C<html_params>.
If not given, the event's author's nickname is provided. Note that a defined
but empty name (such as C<q{}>) I<will> be used; in this case, the name will
appear to be omitted from the result of the C<as_html> call.
=back
=head1 AVAILABLE METHODS
These are the methods provided by I<ActionStreams::Event> to perform common
tasks. Call them from your overridden methods.
=head2 C<$self-E<gt>set_values(\%values)>
Stores the data given in C<%values> as members of this event.
=head2 C<$class-E<gt>fetch_xpath(%param)>
Returns the items discovered by scanning a web resource by the given XPath
recipe. Required members of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be a
valid XML document.
=item * C<foreach>
The XPath selector with which to select the individual events from the
resource.
=item * C<get>
A hashref containing the XPath selectors with which to collect individual data
for each item, keyed on the names of the fields to contain the data.
=back
C<%param> may also contain additional arguments for the C<ua()> method.
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
=head2 C<$class-E<gt>fetch_scraper(%param)>
Returns the items discovered by scanning by the given recipe. Required members
of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be an
HTML or XML document suitable for analysis by the C<Web::Scraper> module.
=item * C<scraper>
The C<Web::Scraper> scraper with which to extract item data from the specified
web resource. See L<Web::Scraper> for information on how to construct a
scraper.
=back
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
See also the below I<NOTE ON WEB::SCRAPER>.
=head2 C<$class-E<gt>build_results(%param)>
Converts a set of collected items into saved action records of type C<$class>.
The required members of C<%param> are:
=over 4
=item * C<author>
The C<MT::Author> instance whose action the items represent.
=item * C<items>
An arrayref of items to save as actions. Each item is a hashref containing the
action data, keyed on the names of the fields containing the data.
=back
Optional parameters are:
=over 4
=item * C<profile>
An arrayref describing the data for the author's profile for the associated
stream, such as is returned by the C<MT::Author::other_profile()> method
supplied by the Action Streams plugin.
The profile member is not used directly by C<build_results()>; they are only
passed to callbacks.
=item * C<stream>
A hashref containing the settings from the registry about the stream, such as
is returned from the C<registry_entry()> method.
=back
=head2 C<$class-E<gt>ua(%param)>
Returns the common HTTP user-agent, an instance of C<LWP::UserAgent>, with
which you can fetch web resources.
The resulting user agent may provide automatic conditional HTTP support when
you call its C<get> method. A UA with conditional HTTP support enabled will
store the values of the conditional HTTP headers (C<ETag> and
C<Last-Modified>) received in responses as C<ActionStreams::UserAgent::Cache>
objects and, on subsequent requests of the same URL, automatically supply the
header values. When the remote HTTP server reports that such a resource has
not changed, the C<HTTP::Response> will be a C<304 Not Modified> response; the
user agent does not itself store and supply the resource content. Using other
C<LWP::UserAgent> methods such as C<post> or C<request> will I<not> trigger
automatic conditional HTTP support.
No arguments are required; possible optional parameters are:
=over 4
=item * C<default_useragent>
If set, the returned HTTP user-agent will use C<LWP::UserAgent>'s default
identifier in the HTTP C<User-Agent> header. If omitted, the UA will use the
Action Streams identifier of C<mt-actionstreams-lwp/I<version>>.
=item * C<unconditional>
If set, the return HTTP user-agent will I<not> automatically use conditional
HTTP to avoid requesting old content from compliant servers. That is, if
omitted, the UA I<will> automatically use conditional HTTP when you call its
C<get> method.
=item * C<die_on_not_modified>
If set, when the response of the HTTP user-agent's C<get> method is a
conditional HTTP C<304 Not Modified> response, throw an exception instead of
returning the response. (Use this option to return control to yourself when
passing UAs with conditional HTTP support to other Perl modules that don't
expect 304 responses.)
The thrown exception is an C<ActionStreams::UserAgent::NotModified> exception.
=back
=head2 C<$self-E<gt>author()>
Returns the C<MT::Author> instance associated with this event, if its
C<author_id> field has been set.
=head2 C<$class-E<gt>install_properties(\%properties)>
I<TODO>
=head2 C<$class-E<gt>install_meta(\%properties)>
I<TODO>
=head2 C<$class-E<gt>registry_entry()>
Returns the registry data for the stream represented by C<$class>.
=head2 C<$class-E<gt>classes_for_type($service_id)>
Given a profile service ID (that is, a key from the C<profile_services> section
of the registry), returns a list of stream classes for scanning that service's
streams.
=head2 C<$class-E<gt>backup_terms_args($blog_ids)>
Used in backup. Backup function calls the method to generate $terms and
$args for the class to load objects. ActionStream::Event does not have
blog_id and does use class_column, the nature the class has to tell
backup function to properly load all the target objects of the class
to be backed up.
See I<MT::BackupRestore> for more detail.
=head1 NOTE ON WEB::SCRAPER
The C<Web::Scraper> module is powerful, but it has complex dependencies. While
its pure Perl requirements are bundled with the Action Streams plugin, it also
requires a compiled XML module. Also, because of how its syntax works, you must
directly C<use> the module in your own code, contrary to the Movable Type idiom
of using C<require> so that modules are loaded only when they are sure to be
used.
If you attempt load C<Web::Scraper> in the normal way, but C<Web::Scraper> is
unable to load due to its missing requirement, whenever the plugin attempts to
load your scraper, the entire plugin will fail to load.
Therefore the C<ActionStreams::Scraper> wrapper module is provided for you. If
you need to load C<Web::Scraper> so as to make a scraper to pass
C<ActionStreams::Event::fetch_scraper()> method, instead write in your module:
use ActionStreams::Scraper;
This module provides the C<Web::Scraper> interface, but if C<Web::Scraper> is
unable to load, the error will be thrown when your module tries to I<use> it,
rather than when you I<load> it. That is, if C<Web::Scraper> can't load, no
errors will be thrown to end users until they try to use your stream.
=head1 AUTHOR
Mark Paschal E<lt>[email protected]<gt>
=cut
|
markpasc/mt-plugin-action-streams
|
e0208adaf76a10d47911258702020d598dc7adc1
|
Provide updated favicons for p0p.com and Upcoming
|
diff --git a/mt-static/plugins/ActionStreams/images/services/p0pulist.png b/mt-static/plugins/ActionStreams/images/services/p0pulist.png
index d2f49cf..5f1f428 100644
Binary files a/mt-static/plugins/ActionStreams/images/services/p0pulist.png and b/mt-static/plugins/ActionStreams/images/services/p0pulist.png differ
diff --git a/mt-static/plugins/ActionStreams/images/services/upcoming.png b/mt-static/plugins/ActionStreams/images/services/upcoming.png
index ee73fe6..a2a59df 100755
Binary files a/mt-static/plugins/ActionStreams/images/services/upcoming.png and b/mt-static/plugins/ActionStreams/images/services/upcoming.png differ
|
markpasc/mt-plugin-action-streams
|
130513f26ca53a7498e48dbb4305461f0b07a217
|
Add new service icons to CSS declarations too
|
diff --git a/mt-static/plugins/ActionStreams/css/action-streams.css b/mt-static/plugins/ActionStreams/css/action-streams.css
index 9e1e4e5..abb5ef2 100644
--- a/mt-static/plugins/ActionStreams/css/action-streams.css
+++ b/mt-static/plugins/ActionStreams/css/action-streams.css
@@ -1,113 +1,117 @@
#header,
#content,
#alpha,
#beta,
#gamma,
#footer {
position: static;
}
.action-stream-header {
margin: 1em 0 .25em;
}
.action-stream-list {
margin-left: 0px;
padding-left: 5px;
list-style-type: none;
}
.action-stream-list li {
margin: 0 0 0.5em;
padding-bottom: 1px;
}
.service-icon {
display: block;
overflow: hidden;
background: transparent url(../images/services/other.png) no-repeat;
padding-left: 20px;
min-height: 18px;
min-width: 16px;
}
.service-website { background-image: url(../images/services/website.png); }
.service-oneup { background-image: url(../images/services/oneup.png); }
.service-backtype { background-image: url(../images/services/backtype.png); }
+.service-blurst { background-image: url(../images/services/blurst.png); }
.service-fortythreethings { background-image: url(../images/services/fortythreethings.png); }
.service-aim { background-image: url(../images/services/aim.png); }
.service-bebo { background-image: url(../images/services/bebo.png); }
.service-catster { background-image: url(../images/services/catster.png); }
.service-colourlovers { background-image: url(../images/services/colourlovers.png); }
.service-corkd { background-image: url(../images/services/corkd.png); }
/*.service-deadjournal { background-image: url(../images/services/deadjournal.png); }*/
.service-delicious { background-image: url(../images/services/delicious.png); }
.service-digg { background-image: url(../images/services/digg.png); }
.service-dodgeball { background-image: url(../images/services/dodgeball.png); }
.service-dogster { background-image: url(../images/services/dogster.png); }
.service-dopplr { background-image: url(../images/services/dopplr.png); }
.service-facebook { background-image: url(../images/services/facebook.png); }
.service-ffffound { background-image: url(../images/services/ffffound.png); }
.service-flickr { background-image: url(../images/services/flickr.png); }
.service-friendfeed { background-image: url(../images/services/friendfeed.png); }
.service-gametap { background-image: url(../images/services/gametap.png); }
.service-goodreads { background-image: url(../images/services/goodreads.png); }
.service-googlereader { background-image: url(../images/services/googlereader.png); }
.service-gtalk { background-image: url(../images/services/gtalk.png); }
.service-hi5 { background-image: url(../images/services/hi5.png); }
.service-iconbuffet { background-image: url(../images/services/iconbuffet.png); }
.service-icq { background-image: url(../images/services/icq.png); }
.service-identica { background-image: url(../images/services/identica.png); }
.service-iminta { background-image: url(../images/services/iminta.png); }
+.service-instructables { background-image: url(../images/services/instructables.png); }
.service-istockphoto { background-image: url(../images/services/istockphoto.png); }
.service-iusethis { background-image: url(../images/services/iusethis.png); }
.service-iwatchthis { background-image: url(../images/services/iwatchthis.png); }
.service-jabber { background-image: url(../images/services/jabber.png); }
.service-jaiku { background-image: url(../images/services/jaiku.png); }
.service-kongregate { background-image: url(../images/services/kongregate.png); }
.service-lastfm { background-image: url(../images/services/lastfm.png); }
.service-linkedin { background-image: url(../images/services/linkedin.png); }
/*.service-livedoor { background-image: url(../images/services/livedoor.png); }*/
.service-livejournal { background-image: url(../images/services/livejournal.png); }
.service-magnolia { background-image: url(../images/services/magnolia.png); }
+.service-metafilter { background-image: url(../images/services/metafilter.png); }
.service-mog { background-image: url(../images/services/mog.png); }
.service-msn { background-image: url(../images/services/msn.png); }
.service-multiply { background-image: url(../images/services/multiply.png); }
.service-myspace { background-image: url(../images/services/myspace.png); }
.service-netflix { background-image: url(../images/services/netflix.png); }
.service-netvibes { background-image: url(../images/services/netvibes.png); }
.service-newsvine { background-image: url(../images/services/newsvine.png); }
.service-ning { background-image: url(../images/services/ning.png); }
+.service-nytimes { background-image: url(../images/services/nytimes.png); }
.service-ohloh { background-image: url(../images/services/ohloh.png); }
.service-orkut { background-image: url(../images/services/orkut.png); }
.service-pandora { background-image: url(../images/services/pandora.png); }
.service-picasaweb { background-image: url(../images/services/picasaweb.png); }
.service-p0pulist { background-image: url(../images/services/p0pulist.png); }
.service-pownce { background-image: url(../images/services/pownce.png); }
.service-reddit { background-image: url(../images/services/reddit.png); }
.service-skype { background-image: url(../images/services/skype.png); }
.service-slideshare { background-image: url(../images/services/slideshare.png); }
.service-smugmug { background-image: url(../images/services/smugmug.png); }
.service-sonicliving { background-image: url(../images/services/sonicliving.png); }
.service-steam { background-image: url(../images/services/steam.png); }
.service-stumbleupon { background-image: url(../images/services/stumbleupon.png); }
.service-tabblo { background-image: url(../images/services/tabblo.png); }
.service-technorati { background-image: url(../images/services/technorati.png); }
.service-tribe { background-image: url(../images/services/tribe.png); }
.service-twitter { background-image: url(../images/services/twitter.png); }
.service-tumblr { background-image: url(../images/services/tumblr.gif); }
.service-typepad { background-image: url(../images/services/typepad.png); }
.service-uncrate { background-image: url(../images/services/uncrate.png); }
.service-upcoming { background-image: url(../images/services/upcoming.png); }
.service-viddler { background-image: url(../images/services/viddler.png); }
.service-vimeo { background-image: url(../images/services/vimeo.png); }
.service-virb { background-image: url(../images/services/virb.png); }
.service-vox { background-image: url(../images/services/vox.png); }
.service-wists { background-image: url(../images/services/wists.png); }
.service-xboxlive { background-image: url(../images/services/xboxlive.png); }
.service-yahoo { background-image: url(../images/services/yahoo.png); }
.service-yelp { background-image: url(../images/services/yelp.png); }
.service-youtube { background-image: url(../images/services/youtube.png); }
.service-zooomr { background-image: url(../images/services/zooomr.png); }
|
markpasc/mt-plugin-action-streams
|
cf4384a4deb7cc65490b8a1b92fb8235f7b9a918
|
Add Blurst achievements stream
|
diff --git a/mt-static/plugins/ActionStreams/images/services/blurst.png b/mt-static/plugins/ActionStreams/images/services/blurst.png
new file mode 100644
index 0000000..047191d
Binary files /dev/null and b/mt-static/plugins/ActionStreams/images/services/blurst.png differ
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event/BlurstAchievements.pm b/plugins/ActionStreams/lib/ActionStreams/Event/BlurstAchievements.pm
new file mode 100644
index 0000000..617000f
--- /dev/null
+++ b/plugins/ActionStreams/lib/ActionStreams/Event/BlurstAchievements.pm
@@ -0,0 +1,91 @@
+package ActionStreams::Event::BlurstAchievements;
+use strict;
+use warnings;
+use base qw( ActionStreams::Event );
+
+use ActionStreams::Scraper;
+
+__PACKAGE__->install_properties({
+ class_type => 'blurst_achievements',
+});
+
+__PACKAGE__->install_meta({
+ columns => [ qw(
+ game_url
+ game_title
+ description
+ ) ],
+});
+
+sub _item_id_to_event_data {
+ my $class = shift;
+ my ($item_id, $ua) = @_;
+
+ my $resp = $ua->post("http://blurst.com/ajax/achievement-tooltip.php",
+ { id => $item_id });
+ return if !$resp->is_success();
+
+ my $scraper = scraper {
+ process 'img', thumbnail => '@src';
+ process '.tt-achievement-name', title => 'TEXT';
+ process '.tt-achievement-desc', description => 'TEXT';
+ process '.tt-achievement-time a',
+ game_url => '@href',
+ game_title => 'TEXT';
+ };
+ # Web::Scraper will scrape an HTTP::Response, so use it as the "URL."
+ my $event = $scraper->scrape($resp);
+ return if !$event;
+
+ $event->{identifier} = $item_id;
+ $event->{url} = URI->new_abs($event->{url}, 'http://blurst.com/')->as_string();
+ $event->{game_url} = URI->new_abs($event->{game_url}, 'http://blurst.com/')->as_string();
+ $event->{game_title} =~ s{ \A \s* Play \s* }{}xms;
+ $event->{title} =~ s{ \( .* \z }{}xms;
+
+ return $event;
+}
+
+sub update_events {
+ my $class = shift;
+ my %profile = @_;
+
+ my $author_id = $profile{author}->id;
+ my $ident = $profile{ident};
+
+ # Find the IDs of the profile achievements.
+ my $items = $class->fetch_scraper(
+ url => "http://blurst.com/community/p/$ident",
+ scraper => scraper {
+ process 'img.achievementicon',
+ 'id[]' => '@alt';
+ },
+ );
+ return if !$items;
+ $items = $items->{id};
+ return if !$items || !@$items;
+
+ # Toss all the IDs for which there are already events.
+ my %item_ids = map { $_ => 1 } @$items;
+ my @events = $class->load({
+ author_id => $author_id,
+ identifier => [ keys %item_ids ],
+ });
+ for my $event (@events) {
+ delete $item_ids{ $event->identifier };
+ }
+
+ # Make events for the remaining achievement IDs.
+ my $ua = $class->ua();
+ my @event_data = grep { $_ }
+ map { $class->_item_id_to_event_data($_, $ua) }
+ keys %item_ids;
+
+ return $class->build_results(
+ author => $profile{author},
+ items => \@event_data,
+ profile => \%profile,
+ );
+}
+
+1;
diff --git a/plugins/ActionStreams/services.yaml b/plugins/ActionStreams/services.yaml
index 1f08c44..2efb8f7 100644
--- a/plugins/ActionStreams/services.yaml
+++ b/plugins/ActionStreams/services.yaml
@@ -1,351 +1,356 @@
oneup:
name: 1up.com
url: http://{{ident}}.1up.com/
fortythreethings:
name: 43Things
url: http://www.43things.com/person/{{ident}}/
aim:
name: AIM
url: aim:goim?screenname={{ident}}
ident_label: Screen name
service_type: contact
backtype:
name: backtype
url: http://www.backtype.com/{{ident}}
service_type: comments
bebo:
name: Bebo
url: http://www.bebo.com/Profile.jsp?MemberId={{ident}}
service_type: network
+blurst:
+ name: Blurst
+ url: http://blurst.com/community/p/{{ident}}
+ ident_label: Username
+ ident_example: melody
catster:
name: Catster
url: http://www.catster.com/cats/{{ident}}
colourlovers:
name: COLOURlovers
url: http://www.colourlovers.com/lover/{{ident}}
corkd:
name: 'Cork''d'
url: http://www.corkd.com/people/{{ident}}
delicious:
name: Delicious
url: http://delicious.com/{{ident}}/
service_type: links
destructoid:
name: Destructoid
url: http://www.destructoid.com/elephant/profile.phtml?un={{ident}}
digg:
name: Digg
url: http://digg.com/users/{{ident}}/
service_type: links
dodgeball:
name: Dodgeball
url: http://www.dodgeball.com/user?uid={{ident}}
deprecated: 1
dogster:
name: Dogster
url: http://www.dogster.com/dogs/{{ident}}
dopplr:
name: Dopplr
url: http://www.dopplr.com/traveller/{{ident}}/
facebook:
name: Facebook
url: http://www.facebook.com/profile.php?id={{ident}}
ident_label: User ID
ident_example: 12345
service_type: network
ident_hint: You can find your Facebook user ID in your profile URL. For example: http://www.facebook.com/profile.php?id=12345
ffffound:
name: FFFFOUND!
url: http://ffffound.com/home/{{ident}}/found/
service_type: photos
flickr:
name: Flickr
url: http://flickr.com/photos/{{ident}}/
ident_example: 36381329@N00
service_type: photos
ident_hint: Enter your Flickr user ID that has a "@" in it. Your Flickr user ID is NOT the username in the URL of your photo stream.
friendfeed:
name: FriendFeed
url: http://friendfeed.com/{{ident}}
ident_example: JoeUsername
gametap:
name: Gametap
url: http://www.gametap.com/profile/show/profile.do?sn={{ident}}
goodreads:
name: Goodreads
url: http://www.goodreads.com/user/show/{{ident}}
ident_label: User ID
ident_example: 12345
ident_hint: You can find your Goodreads user ID in your profile URL. For example: http://www.goodreads.com/user/show/12345
googlereader:
name: Google Reader
url: http://www.google.com/reader/shared/{{ident}}
ident_label: Sharing ID
ident_example: http://www.google.com/reader/shared/16793324975410272738
service_type: links
hi5:
name: Hi5
url: http://hi5.com/friend/profile/displayProfile.do?userid={{ident}}
service_type: network
iconbuffet:
name: IconBuffet
url: http://www.iconbuffet.com/people/{{ident}}
icq:
name: ICQ
url: http://www.icq.com/people/about_me.php?uin={{ident}}
ident_label: UIN
ident_example: 12345
service_type: contact
identica:
name: Identi.ca
url: http://identi.ca/{{ident}}
service_type: status
iminta:
name: Iminta
url: http://iminta.com/people/{{ident}}
instructables:
name: Instructables
url: http://www.instructables.com/member/{{ident}}/
ident_label: Username
ident_example: melody
istockphoto:
name: iStockphoto
url: http://www.istockphoto.com/user_view.php?id={{ident}}
ident_label: User ID
ident_example: 123456
ident_hint: You can find your iStockphoto user ID in your profile URL. For example: http://www.istockphoto.com/user_view.php?id=123456
iusethis:
name: IUseThis
url: http://osx.iusethis.com/user/{{ident}}
iwatchthis:
name: iwatchthis
url: http://iwatchthis.com/{{ident}}
jabber:
name: Jabber
url: jabber://{{ident}}
ident_label: Jabber ID
ident_example: [email protected]
service_type: contact
jaiku:
name: Jaiku
url: http://{{ident}}.jaiku.com/
ident_suffix: .jaiku.com
service_type: status
kongregate:
name: Kongregate
url: http://www.kongregate.com/accounts/{{ident}}
lastfm:
name: Last.fm
url: http://www.last.fm/user/{{ident}}/
ident_example: JoeUsername
linkedin:
name: LinkedIn
url: http://www.linkedin.com/in/{{ident}}
ident_example: MelodyNelson
ident_prefix: http://www.linkedin.com/in/
ident_label: Profile URL
service_type: network
livejournal:
name: LiveJournal
url: http://{{ident}}.livejournal.com/
ident_suffix: .livejournal.com
service_type: blog
magnolia:
name: Ma.gnolia
url: http://ma.gnolia.com/people/{{ident}}
service_type: links
deprecated: 1
metafilter:
name: MetaFilter
url: http://www.metafilter.com/user/{{ident}}
ident_label: User Number
ident_example: 11039
mog:
name: MOG
url: http://mog.com/{{ident}}
msn:
name: 'MSN Messenger'
url: msnim:chat?contact={{ident}}
service_type: contact
multiply:
name: Multiply
url: http://{{ident}}.multiply.com/
myspace:
name: MySpace
url: http://www.myspace.com/{{ident}}
ident_label: User ID
ident_prefix: http://www.myspace.com/
service_type: network
netflix:
name: Netflix
url: http://rss.netflix.com/QueueRSS?id={{ident}}
ident_label: Netflix RSS ID
ident_example: P0000006746939516625352861892808956
ident_hint: To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.
netvibes:
name: Netvibes
url: http://www.netvibes.com/{{ident}}
service_type: links
newsvine:
name: Newsvine
url: http://{{ident}}.newsvine.com/
ning:
name: Ning
url: http://{{ident}}.ning.com/
service_type: network
ident_suffix: .ning.com/
ident_prefix: http://
ident_label: Social Network URL
nytimes:
name: New York Times (TimesPeople)
url: http://timespeople.nytimes.com/view/user/{{ident}}/activities.html
service_type: links
ident_label: Activity URL
ident_example: http://timespeople.nytimes.com/view/user/57963079/activities.html
ohloh:
name: Ohloh
url: http://ohloh.net/accounts/{{ident}}
orkut:
name: Orkut
url: http://www.orkut.com/Profile.aspx?uid={{ident}}
ident_label: User ID
ident_example: 1234567890123456789
service_type: network
ident_hint: You can find your Orkut user ID in your profile URL. For example: http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789
pandora:
name: Pandora
url: http://pandora.com/people/{{ident}}
ident_example: JoeUsername
picasaweb:
name: Picasa Web Albums
url: http://picasaweb.google.com/{{ident}}
service_type: photos
p0pulist:
name: p0p
url: http://p0p.com/list/hot_list/{{ident}}
ident_label: User ID
ident_example: 12345
ident_hint: You can find your p0p user ID in your Hot List URL. For example: http://p0pulist.com/list/hot_list/12345
pownce:
name: Pownce
url: http://pownce.com/{{ident}}/
service_type: status
deprecated: 1
reddit:
name: Reddit
url: http://reddit.com/user/{{ident}}/
service_type: links
skype:
name: Skype
url: callto://{{ident}}
slideshare:
name: SlideShare
url: http://www.slideshare.net/{{ident}}
smugmug:
name: Smugmug
url: http://{{ident}}.smugmug.com/
service_type: photos
sonicliving:
name: SonicLiving
url: http://www.sonicliving.com/user/{{ident}}/
ident_label: User ID
ident_example: 12345
ident_hint: You can find your SonicLiving user ID in your Share & Subscribe URL. For example: http://sonicliving.com/user/12345/feeds
steam:
name: Steam
url: http://steamcommunity.com/id/{{ident}}
stumbleupon:
name: StumbleUpon
url: http://{{ident}}.stumbleupon.com/
tabblo:
name: Tabblo
url: http://www.tabblo.com/studio/person/{{ident}}/
technorati:
name: Technorati
url: http://technorati.com/people/technorati/{{ident}}
tribe:
name: Tribe
url: http://people.tribe.net/{{ident}}
service_type: network
ident_label: User ID
ident_example: dcdc61ed-696a-40b5-80c1-e9a9809a726a
ident_hint: You can find your Tribe user ID in your profile URL. For example: http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a
tumblr:
name: Tumblr
url: http://{{ident}}.tumblr.com
icon: images/services/tumblr.gif
ident_label: URL
ident_suffix: .tumblr.com
service_type: blog
twitter:
name: Twitter
url: http://twitter.com/{{ident}}
service_type: status
typepad:
name: TypePad
ident_prefix: http://profile.typepad.com/
ident_label: Profile URL
url: http://profile.typepad.com/{{ident}}
uncrate:
name: Uncrate
url: http://www.uncrate.com/stuff/{{ident}}
upcoming:
name: Upcoming
url: http://upcoming.yahoo.com/user/{{ident}}
ident_label: User ID
ident_example: 12345
viddler:
name: Viddler
url: http://www.viddler.com/explore/{{ident}}
service_type: video
vimeo:
name: Vimeo
url: http://www.vimeo.com/{{ident}}
service_type: video
virb:
name: Virb
url: http://www.virb.com/{{ident}}
service_type: network
ident_label: User ID
ident_example: 2756504321310091
ident_hint: You can find your Virb user ID in your home URL. For example: http://www.virb.com/backend/2756504321310091/your_home
vox:
name: Vox
url: http://{{ident}}.vox.com/
ident_label: Vox name
ident_suffix: .vox.com
service_type: blog
website:
name: Website
url: '{{ident}}'
ident_label: URL
ident_example: http://www.example.com/
ident_exact: 1
can_many: 1
service_type: blog
wists:
name: Wists
url: http://www.wists.com/{{ident}}
xboxlive:
name: 'Xbox Live'
url: http://live.xbox.com/member/{{ident}}
ident_label: Gamertag
yahoo:
name: 'Yahoo! Messenger'
url: http://edit.yahoo.com/config/send_webmesg?.target={{ident}}
service_type: contact
yelp:
name: Yelp
url: http://www.yelp.com/user_details?userid={{ident}}
ident_label: User ID
ident_example: 4BXqlLKW8oP0RBCW1FvaIg
youtube:
name: YouTube
url: http://www.youtube.com/user/{{ident}}
service_type: video
zooomr:
name: Zooomr
url: http://www.zooomr.com/photos/{{ident}}
ident_example: 1234567@Z01
service_type: photos
diff --git a/plugins/ActionStreams/streams.yaml b/plugins/ActionStreams/streams.yaml
index f29648f..c22e911 100644
--- a/plugins/ActionStreams/streams.yaml
+++ b/plugins/ActionStreams/streams.yaml
@@ -1,530 +1,544 @@
oneup:
playing:
name: Currently Playing
description: The games in your collection you're currently playing
class: OneupPlaying
backtype:
comments:
name: Comments
description: Comments you have made on the web
fields:
- queue
html_form: '[_1] commented on <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.backtype.com/{{ident}}'
rss: 1
identifier: url
+blurst:
+ achievements:
+ name: Achievements
+ description: Achievements earned in Blurst games
+ fields:
+ - game_title
+ - game_url
+ html_form: '[_1] won achievement <a href="[_2]">[_3]</a> in <a href="[_4]">[_5]</a>'
+ html_params:
+ - url
+ - title
+ - game_url
+ - game_title
+ class: BlurstAchievements
colourlovers:
colors:
name: Colors
description: Colors you saved
fields:
- queue
html_form: '[_1] saved the color <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/colors/new?lover={{ident}}'
xpath:
foreach: //color
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
palettes:
name: Palettes
description: Palettes you saved
fields:
- queue
html_form: '[_1] saved the palette <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/palettes/new?lover={{ident}}'
xpath:
foreach: //palette
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
patterns:
name: Patterns
description: Patterns you saved
fields:
- queue
html_form: '[_1] saved the pattern <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/patterns/new?lover={{ident}}'
xpath:
foreach: //pattern
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
favpalettes:
name: Favorite Palettes
description: Palettes you saved as favorites
fields:
- queue
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite palette'
html_params:
- url
- title
url: 'http://www.colourlovers.com/rss/lover/{{ident}}/palettes/favorites'
rss: 1
corkd:
reviews:
name: Reviews
description: Your wine reviews
fields:
- review
html_form: '[_1] reviewed <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/journal/{{ident}}'
rss: 1
cellar:
name: Cellar
description: Wines you own
fields:
- wine
html_form: '[_1] owns <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/cellar/{{ident}}'
rss: 1
list:
name: Shopping List
description: Wines you want to buy
fields:
- wine
html_form: '[_1] wants <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/shoppinglist/{{ident}}'
rss: 1
delicious:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.delicious.com/v2/rss/{{ident}}?plain'
identifier: url
rss:
note: description
tags: category/child::text()
digg:
links:
name: Dugg
description: Links you dugg
html_form: '[_1] dugg the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://digg.com/users/{{ident}}/history/diggs.rss'
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
submitted:
name: Submissions
description: Links you submitted
html_form: '[_1] submitted the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://digg.com/users/{{ident}}/history/submissions.rss
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
ffffound:
favorites:
name: Found
description: Photos you found
html_form: '[_1] ffffound <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://ffffound.com/home/{{ident}}/found/feed
rss: 1
flickr:
favorites:
name: Favorites
description: Photos you marked as favorites
fields:
- by
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite photo'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_faves.gne?nsid={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
by: author/name
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_public.gne?id={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
friendfeed:
likes:
name: Likes
description: Things from your friends that you "like"
html_form: '[_1] likes <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://friendfeed.com/{{ident}}/likes?format=atom'
atom:
url: link/@href
gametap:
scores:
name: Leaderboard scores
description: Your high scores in games with leaderboards
fields:
- score
html_form: '[_1] scored <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- score
- url
- title
url: http://www.gametap.com/profile/leaderboards.do?sn={{ident}}
identifier: title,score
scraper:
foreach: 'div.buddy-leaderboards div.tr'
get:
url:
- 'div.name a'
- '@href'
title:
- 'div.name strong'
- TEXT
score:
- 'div.name div'
- TEXT
goodreads:
toread:
name: To read
description: Books on your "to-read" shelf
fields:
- by
html_form: '[_1] saved <a href="[_2]"><i>[_3]</i> by [_4]</a> to read'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=to-read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
reading:
name: Reading
description: Books on your "currently-reading" shelf
fields:
- by
html_form: '[_1] started reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=currently-reading'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
read:
name: Read
description: Books on your "read" shelf
fields:
- by
html_form: '[_1] finished reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
googlereader:
links:
name: Shared
description: Your shared items
html_form: '[_1] shared <a href="[_2]">[_3]</a> from <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- source_url
- source_title
class: GoogleReader
iconbuffet:
icons:
name: Deliveries
description: Icon sets you were delivered
html_form: '[_1] received the icon set <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.iconbuffet.com/people/{{ident}};received_packages'
identifier: url
scraper:
foreach: 'div#icons div.preview-sm'
get:
title:
- a span
- TEXT
url:
- a
- '@href'
identica:
statuses:
name: Notices
description: Notices you posted
html_form: '[_1] <a href="[_2]">said</a>, “[_3]”'
html_params:
- url
- title
url: 'http://identi.ca/{{ident}}/rss'
rss:
created_on: dc:date
class: Identica
iminta:
links:
name: Intas
description: Links you saved
html_form: '[_1] is inta <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://iminta.com/people/{{ident}}/rss.xml?inta_source_id=11'
rss: 1
instructables:
favorites:
name: Favorites
description: Instructables you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite'
html_params:
- url
- title
url: http://www.instructables.com/member/{{ident}}/rss.xml?show=good
rss:
created_on: ''
modified_on: ''
thumbnail: imageThumb
istockphoto:
photos:
name: Photos
description: Photos you posted that were approved
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.istockphoto.com/webservices/feeds/?feedFormat=IStockAtom_1_0&feedName=istockfeed.image.newestUploads&feedParams=UserID={{ident}}'
identifier: url
atom:
thumbnail: content/div/a/img/@src
iusethis:
events:
name: Recent events
description: Events from your recent events feed
html_form: '[_1] <a href="[_2]">[_3]</a>'
html_params:
- url
- title
rss: 1
url: 'http://osx.iusethis.com/user/feed.rss/{{ident}}?following=0'
osxapps:
name: Apps you use
description: The applications you saved as ones you use
fields:
- favorite
html_form: '[_1] started using <a href="[_2]">[_3]</a>[quant,_4, (and loves it),,]'
html_params:
- url
- title
- favorite
url: 'http://osx.iusethis.com/user/{{ident}}'
iwatchthis:
favorites:
name: Favorites
description: Videos you saved as watched
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video'
html_params:
- url
- title
url: 'http://iwatchthis.com/rss/{{ident}}'
rss: 1
jaiku:
jaikus:
name: Jaikus
description: Jaikus you posted
html_form: '[_1] <a href="[_2]">jaiku''d</a>, "[_3]"'
html_params:
- url
- title
url: 'http://{{ident}}.jaiku.com/feed/atom'
atom: 1
kongregate:
favorites:
name: Favorites
description: Games you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite game'
html_params:
- url
- title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url
scraper:
foreach: #favorites dl
get:
url:
- dd a
- '@href'
title:
- dd a
- TEXT
thumbnail:
- dt img
- '@src'
achievements:
name: Achievements
description: Achievements you won
fields:
- game_title
html_form: '[_1] won the <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- title
- url
- game_title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url,title
scraper:
foreach: #achievements .badge_details
get:
url:
- dt.badge_img a
- '@href'
thumbnail:
- dt.badge_img img
- '@style'
title:
- dd.badge_name
- TEXT
game_title:
- a.badge_game
- TEXT
lastfm:
tracks:
name: Tracks
description: Songs you recently listened to (High spam potential!)
html_form: '[_1] heard <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/recenttracks.rss'
rss: 1
lovedtracks:
name: Loved Tracks
description: Songs you marked as "loved"
fields:
- artist
html_form: '[_1] loved <a href="[_2]">[_3]</a> by [_4]'
html_params:
- url
- title
- artist
url: 'http://pipes.yahoo.com/pipes/pipe.run?_id=4smlkvMW3RGPpBPfTqoASA&_render=rss&lastFM_UserName={{ident}}'
identifier: url
rss:
artist: description
journalentries:
name: Journal Entries
description: Your recent journal entries
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/journals.rss'
rss: 1
events:
name: Events
description: The events you said you'll be attending
html_form: '[_1] is attending <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/events.rss'
rss: 1
livejournal:
posts:
name: Posts
description: Your public posts to your journal
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://users.livejournal.com/{{ident}}/data/atom'
atom: 1
magnolia:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ma.gnolia.com/atom/full/people/{{ident}}'
identifier: url
|
markpasc/mt-plugin-action-streams
|
0f33644085b58807ce8f473442899904fd0f5a3f
|
Add Instructables favorites stream
|
diff --git a/mt-static/plugins/ActionStreams/images/services/instructables.png b/mt-static/plugins/ActionStreams/images/services/instructables.png
new file mode 100644
index 0000000..2e409f9
Binary files /dev/null and b/mt-static/plugins/ActionStreams/images/services/instructables.png differ
diff --git a/plugins/ActionStreams/config.yaml b/plugins/ActionStreams/config.yaml
index 53dc8b2..eed97e1 100644
--- a/plugins/ActionStreams/config.yaml
+++ b/plugins/ActionStreams/config.yaml
@@ -1,196 +1,197 @@
name: Action Streams
id: ActionStreams
key: ActionStreams
author_link: http://www.sixapart.com/
author_name: Six Apart Ltd.
description: <MT_TRANS phrase="Manages authors' accounts and actions on sites elsewhere around the web">
schema_version: 16
version: 2.2
plugin_link: http://www.sixapart.com/
settings:
rebuild_for_action_stream_events:
Default: 0
Scope: blog
l10n_class: ActionStreams::L10N
blog_config_template: blog_config_template.tmpl
init_app: $ActionStreams::ActionStreams::Init::init_app
applications:
cms:
methods:
list_profileevent: $ActionStreams::ActionStreams::Plugin::list_profileevent
other_profiles: $ActionStreams::ActionStreams::Plugin::other_profiles
dialog_add_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile
dialog_edit_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile
add_other_profile: $ActionStreams::ActionStreams::Plugin::add_other_profile
edit_other_profile: $ActionStreams::ActionStreams::Plugin::edit_other_profile
remove_other_profile: $ActionStreams::ActionStreams::Plugin::remove_other_profile
itemset_update_profiles: $ActionStreams::ActionStreams::Plugin::itemset_update_profiles
itemset_hide_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_events
itemset_show_events: $ActionStreams::ActionStreams::Plugin::itemset_show_events
itemset_hide_all_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events
itemset_show_all_events: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events
community:
methods:
profile_add_external_profile: $ActionStreams::ActionStreams::Plugin::profile_add_external_profile
profile_delete_external_profile: $ActionStreams::ActionStreams::Plugin::profile_delete_external_profile
callbacks:
post_add_profile: $ActionStreams::ActionStreams::Plugin::profile_first_update_events
callbacks:
MT::App::CMS::template_param.edit_author: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::template_param.list_member: $ActionStreams::ActionStreams::Plugin::param_list_member
MT::App::CMS::template_param.other_profiles: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::template_param.list_profileevent: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::post_add_profile: $ActionStreams::ActionStreams::Plugin::first_profile_update
post_action_streams_task: $ActionStreams::ActionStreams::Plugin::rebuild_action_stream_blogs
pre_build_action_streams_event.flickr_favorites: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail
pre_build_action_streams_event.flickr_photos: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail
pre_build_action_streams_event.gametap_scores: $ActionStreams::ActionStreams::Fix::gametap_score_stuff
pre_build_action_streams_event.identica_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name
pre_build_action_streams_event.iminta_links: $ActionStreams::ActionStreams::Fix::iminta_link_title
+ pre_build_action_streams_event.instructables_favorites: $ActionStreams::ActionStreams::Fix::instructables_favorites_thumbnails
pre_build_action_streams_event.iusethis_events: $ActionStreams::ActionStreams::Fix::iusethis_event_title
pre_build_action_streams_event.kongregate_achievements: $ActionStreams::ActionStreams::Fix::kongregate_achievement_title_thumb
pre_build_action_streams_event.magnolia_links: $ActionStreams::ActionStreams::Fix::magnolia_link_notes
pre_build_action_streams_event.metafilter_favorites: $ActionStreams::ActionStreams::Fix::metafilter_favorites_titles
pre_build_action_streams_event.netflix_queue: $ActionStreams::ActionStreams::Fix::netflix_queue_prefix_thumb
pre_build_action_streams_event.netflix_recent: $ActionStreams::ActionStreams::Fix::netflix_recent_prefix_thumb
pre_build_action_streams_event.p0pulist_stuff: $ActionStreams::ActionStreams::Fix::p0pulist_stuff_urls
pre_build_action_streams_event.twitter_favorites: $ActionStreams::ActionStreams::Fix::twitter_favorite_author
pre_build_action_streams_event.twitter_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name
pre_build_action_streams_event.typepad_comments: $ActionStreams::ActionStreams::Fix::typepad_comment_titles
pre_build_action_streams_event.wists_wists: $ActionStreams::ActionStreams::Fix::wists_thumb
filter_action_streams_event.nytimes_links: $ActionStreams::ActionStreams::Fix::nytimes_links_titles
object_types:
profileevent: ActionStreams::Event
as: ActionStreams::Event
as_ua_cache: ActionStreams::UserAgent::Cache
list_actions:
profileevent:
hide_all:
label: Hide All
order: 100
js: finishPluginActionAll
code: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events
continue_prompt_handler: >
sub { MT->translate('Are you sure you want to hide EVERY event in EVERY action stream?') }
show_all:
label: Show All
order: 200
js: finishPluginActionAll
code: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events
continue_prompt_handler: >
sub { MT->translate('Are you sure you want to show EVERY event in EVERY action stream?') }
delete:
label: Delete
order: 300
code: $core::MT::App::CMS::delete
continue_prompt_handler: >
sub { MT->translate('Deleted events that are still available from the remote service will be added back in the next scan. Only events that are no longer available from your profile will remain deleted. Are you sure you want to delete the selected event(s)?') }
tags:
function:
StreamAction: $ActionStreams::ActionStreams::Tags::stream_action
StreamActionID: $ActionStreams::ActionStreams::Tags::stream_action_id
StreamActionVar: $ActionStreams::ActionStreams::Tags::stream_action_var
StreamActionDate: $ActionStreams::ActionStreams::Tags::stream_action_date
StreamActionModifiedDate: $ActionStreams::ActionStreams::Tags::stream_action_modified_date
StreamActionTitle: $ActionStreams::ActionStreams::Tags::stream_action_title
StreamActionURL: $ActionStreams::ActionStreams::Tags::stream_action_url
StreamActionThumbnailURL: $ActionStreams::ActionStreams::Tags::stream_action_thumbnail_url
StreamActionVia: $ActionStreams::ActionStreams::Tags::stream_action_via
OtherProfileVar: $ActionStreams::ActionStreams::Tags::other_profile_var
block:
ActionStreams: $ActionStreams::ActionStreams::Tags::action_streams
StreamActionTags: $ActionStreams::ActionStreams::Tags::stream_action_tags
OtherProfiles: $ActionStreams::ActionStreams::Tags::other_profiles
ProfileServices: $ActionStreams::ActionStreams::Tags::profile_services
StreamActionRollup: $ActionStreams::ActionStreams::Tags::stream_action_rollup
tasks:
UpdateEvents:
frequency: 1800
label: Poll for new events
code: $ActionStreams::ActionStreams::Plugin::update_events
task_workers:
UpdateEvents:
label: Update Events
class: ActionStreams::Worker
widgets:
asotd:
label: Recent Actions
template: widget_recent.mtml
permission: post
singular: 1
set: sidebar
handler: $ActionStreams::ActionStreams::Plugin::widget_recent
condition: $ActionStreams::ActionStreams::Plugin::widget_blog_dashboard_only
template_sets:
streams:
label: Action Stream
base_path: 'blog_tmpl'
base_css: themes-base/blog.css
order: 100
templates:
index:
main_index:
label: Main Index (Recent Actions)
outfile: index.html
rebuild_me: 1
archive:
label: Action Archive
outfile: archive.html
rebuild_me: 1
styles:
label: Stylesheet
outfile: styles.css
rebuild_me: 1
feed_recent:
label: Feed - Recent Activity
outfile: atom.xml
rebuild_me: 1
module:
html_head:
label: HTML Head
banner_header:
label: Banner Header
banner_footer:
label: Banner Footer
sidebar:
label: Sidebar
widget:
elsewhere:
label: Find Authors Elsewhere
actions:
label: Recent Actions
widgetset:
2column_layout_sidebar:
label: 2-column layout - Sidebar
widgets:
- Find Authors Elsewhere
upgrade_functions:
enable_existing_streams:
version_limit: 9
updater:
type: author
label: Enabling default action streams for selected profiles...
code: $ActionStreams::ActionStreams::Upgrade::enable_existing_streams
reclass_actions:
version_limit: 15
handler: $ActionStreams::ActionStreams::Upgrade::reclass_actions
priority: 8
rename_action_metadata:
version_limit: 15
handler: $ActionStreams::ActionStreams::Upgrade::rename_action_metadata
priority: 9
upgrade_data:
reclass_actions:
twitter_tweets: twitter_statuses
pownce_notes: pownce_statuses
googlereader_shared: googlereader_links
rename_action_metadata:
- action_type: delicious_links
old: annotation
new: note
- action_type: googlereader_links
old: annotation
new: note
profile_services: services.yaml
action_streams: streams.yaml
diff --git a/plugins/ActionStreams/lib/ActionStreams/Fix.pm b/plugins/ActionStreams/lib/ActionStreams/Fix.pm
index 8067d37..ba4905c 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Fix.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Fix.pm
@@ -1,151 +1,157 @@
package ActionStreams::Fix;
use strict;
use warnings;
use ActionStreams::Scraper;
sub _twitter_add_tags_to_item {
my ($item) = @_;
if (my @tags = $item->{title} =~ m{
(?: \A | \s ) # BOT or whitespace
\# # hash
(\w\S*\w) # tag
(?<! 's ) # but don't end with 's
}xmsg) {
$item->{tags} = \@tags;
}
}
sub twitter_tweet_name {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the Twitter username from the front of the tweet.
my $ident = $profile->{ident};
$item->{title} =~ s{ \A \s* \Q$ident\E : \s* }{}xmsi;
_twitter_add_tags_to_item($item);
}
sub twitter_favorite_author {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the Twitter username from the front of the tweet.
if ($item->{title} =~ s{ \A \s* ([^\s:]+) : \s* }{}xms) {
$item->{tweet_author} = $1;
}
_twitter_add_tags_to_item($item);
}
sub flickr_photo_thumbnail {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Extract just the URL, and use the _t size thumbnail, not the _m size image.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ (http://farm[^\.]+\.static\.flickr\.com .*? _m.jpg) }xms) {
$thumb = $1;
$thumb =~ s{ _m.jpg \z }{_t.jpg}xms;
$item->{thumbnail} = $thumb;
}
}
sub iminta_link_title {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the username for when we add it back in later.
$item->{title} =~ s{ (?: \s* :: [^:]+ ){2} \z }{}xms;
}
+sub instructables_favorites_thumbnails {
+ my ($cb, $app, $item, $event, $author, $profile) = @_;
+ $item->{thumbnail} = URI->new_abs($item->{thumbnail}, 'http://www.instructables.com/')
+ if $item->{thumbnail};
+}
+
sub iusethis_event_title {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the username for when we add it back in later.
$item->{title} =~ s{ \A \w+ \s* }{}xms;
}
sub metafilter_favorites_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{title} =~ s{ \A [^:]+ : \s* }{}xms;
}
sub netflix_recent_prefix_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the 'Shipped:' or 'Received:' prefix.
$item->{title} =~ s{ \A [^:]*: \s* }{}xms;
# Extract thumbnail from description.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m/ <img src="([^"]+)"} /xms) {
$item->{thumbnail} = $1;
}
}
sub netflix_queue_prefix_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the item number.
$item->{title} =~ s{ \A \d+ [\W\S] \s* }{}xms;
# Extract thumbnail from description.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m/ <img src="([^"]+)"} /xms) {
$item->{thumbnail} = $1;
}
}
sub nytimes_links_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
return $item->{title} =~ s{ \A [^:]* recommended [^:]* : \s* }{}xms ? 1 : 0;
}
sub p0pulist_stuff_urls {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{url} =~ s{ \A / }{http://p0pulist.com/}xms;
}
sub kongregate_achievement_title_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the parenthetical from the end of the title.
$item->{title} =~ s{ \( [^)]* \) \z }{}xms;
# Pick the actual achievement badge out of the inline CSS.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ background-image: \s* url\( ([^)]+) }xms) {
$item->{thumbnail} = $1;
}
}
sub wists_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Grab the wists thumbnail out.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ (http://cache.wists.com/thumbnails/ [^"]+ ) }xms) {
$item->{thumbnail} = $1;
}
}
sub gametap_score_stuff {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{score} =~ s{ \D }{}xmsg;
$item->{url} = q{} . $item->{url};
$item->{url} =~ s{ \A / }{http://www.gametap.com/}xms;
}
sub typepad_comment_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{title} =~ s{ \A .*? ' }{}xms;
$item->{title} =~ s{ ' \z }{}xms;
}
sub magnolia_link_notes {
my ($cb, $app, $item, $event, $author, $profile) = @_;
my $scraper = scraper {
process '//p[position()=2]', note => 'TEXT';
};
my $result = $scraper->scrape(\$item->{note});
if ($result->{note}) {
$item->{note} = $result->{note};
}
else {
delete $item->{note};
}
}
1;
diff --git a/plugins/ActionStreams/services.yaml b/plugins/ActionStreams/services.yaml
index cbf4499..1f08c44 100644
--- a/plugins/ActionStreams/services.yaml
+++ b/plugins/ActionStreams/services.yaml
@@ -1,346 +1,351 @@
oneup:
name: 1up.com
url: http://{{ident}}.1up.com/
fortythreethings:
name: 43Things
url: http://www.43things.com/person/{{ident}}/
aim:
name: AIM
url: aim:goim?screenname={{ident}}
ident_label: Screen name
service_type: contact
backtype:
name: backtype
url: http://www.backtype.com/{{ident}}
service_type: comments
bebo:
name: Bebo
url: http://www.bebo.com/Profile.jsp?MemberId={{ident}}
service_type: network
catster:
name: Catster
url: http://www.catster.com/cats/{{ident}}
colourlovers:
name: COLOURlovers
url: http://www.colourlovers.com/lover/{{ident}}
corkd:
name: 'Cork''d'
url: http://www.corkd.com/people/{{ident}}
delicious:
name: Delicious
url: http://delicious.com/{{ident}}/
service_type: links
destructoid:
name: Destructoid
url: http://www.destructoid.com/elephant/profile.phtml?un={{ident}}
digg:
name: Digg
url: http://digg.com/users/{{ident}}/
service_type: links
dodgeball:
name: Dodgeball
url: http://www.dodgeball.com/user?uid={{ident}}
deprecated: 1
dogster:
name: Dogster
url: http://www.dogster.com/dogs/{{ident}}
dopplr:
name: Dopplr
url: http://www.dopplr.com/traveller/{{ident}}/
facebook:
name: Facebook
url: http://www.facebook.com/profile.php?id={{ident}}
ident_label: User ID
ident_example: 12345
service_type: network
ident_hint: You can find your Facebook user ID in your profile URL. For example: http://www.facebook.com/profile.php?id=12345
ffffound:
name: FFFFOUND!
url: http://ffffound.com/home/{{ident}}/found/
service_type: photos
flickr:
name: Flickr
url: http://flickr.com/photos/{{ident}}/
ident_example: 36381329@N00
service_type: photos
ident_hint: Enter your Flickr user ID that has a "@" in it. Your Flickr user ID is NOT the username in the URL of your photo stream.
friendfeed:
name: FriendFeed
url: http://friendfeed.com/{{ident}}
ident_example: JoeUsername
gametap:
name: Gametap
url: http://www.gametap.com/profile/show/profile.do?sn={{ident}}
goodreads:
name: Goodreads
url: http://www.goodreads.com/user/show/{{ident}}
ident_label: User ID
ident_example: 12345
ident_hint: You can find your Goodreads user ID in your profile URL. For example: http://www.goodreads.com/user/show/12345
googlereader:
name: Google Reader
url: http://www.google.com/reader/shared/{{ident}}
ident_label: Sharing ID
ident_example: http://www.google.com/reader/shared/16793324975410272738
service_type: links
hi5:
name: Hi5
url: http://hi5.com/friend/profile/displayProfile.do?userid={{ident}}
service_type: network
iconbuffet:
name: IconBuffet
url: http://www.iconbuffet.com/people/{{ident}}
icq:
name: ICQ
url: http://www.icq.com/people/about_me.php?uin={{ident}}
ident_label: UIN
ident_example: 12345
service_type: contact
identica:
name: Identi.ca
url: http://identi.ca/{{ident}}
service_type: status
iminta:
name: Iminta
url: http://iminta.com/people/{{ident}}
+instructables:
+ name: Instructables
+ url: http://www.instructables.com/member/{{ident}}/
+ ident_label: Username
+ ident_example: melody
istockphoto:
name: iStockphoto
url: http://www.istockphoto.com/user_view.php?id={{ident}}
ident_label: User ID
ident_example: 123456
ident_hint: You can find your iStockphoto user ID in your profile URL. For example: http://www.istockphoto.com/user_view.php?id=123456
iusethis:
name: IUseThis
url: http://osx.iusethis.com/user/{{ident}}
iwatchthis:
name: iwatchthis
url: http://iwatchthis.com/{{ident}}
jabber:
name: Jabber
url: jabber://{{ident}}
ident_label: Jabber ID
ident_example: [email protected]
service_type: contact
jaiku:
name: Jaiku
url: http://{{ident}}.jaiku.com/
ident_suffix: .jaiku.com
service_type: status
kongregate:
name: Kongregate
url: http://www.kongregate.com/accounts/{{ident}}
lastfm:
name: Last.fm
url: http://www.last.fm/user/{{ident}}/
ident_example: JoeUsername
linkedin:
name: LinkedIn
url: http://www.linkedin.com/in/{{ident}}
ident_example: MelodyNelson
ident_prefix: http://www.linkedin.com/in/
ident_label: Profile URL
service_type: network
livejournal:
name: LiveJournal
url: http://{{ident}}.livejournal.com/
ident_suffix: .livejournal.com
service_type: blog
magnolia:
name: Ma.gnolia
url: http://ma.gnolia.com/people/{{ident}}
service_type: links
deprecated: 1
metafilter:
name: MetaFilter
url: http://www.metafilter.com/user/{{ident}}
ident_label: User Number
ident_example: 11039
mog:
name: MOG
url: http://mog.com/{{ident}}
msn:
name: 'MSN Messenger'
url: msnim:chat?contact={{ident}}
service_type: contact
multiply:
name: Multiply
url: http://{{ident}}.multiply.com/
myspace:
name: MySpace
url: http://www.myspace.com/{{ident}}
ident_label: User ID
ident_prefix: http://www.myspace.com/
service_type: network
netflix:
name: Netflix
url: http://rss.netflix.com/QueueRSS?id={{ident}}
ident_label: Netflix RSS ID
ident_example: P0000006746939516625352861892808956
ident_hint: To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.
netvibes:
name: Netvibes
url: http://www.netvibes.com/{{ident}}
service_type: links
newsvine:
name: Newsvine
url: http://{{ident}}.newsvine.com/
ning:
name: Ning
url: http://{{ident}}.ning.com/
service_type: network
ident_suffix: .ning.com/
ident_prefix: http://
ident_label: Social Network URL
nytimes:
name: New York Times (TimesPeople)
url: http://timespeople.nytimes.com/view/user/{{ident}}/activities.html
service_type: links
ident_label: Activity URL
ident_example: http://timespeople.nytimes.com/view/user/57963079/activities.html
ohloh:
name: Ohloh
url: http://ohloh.net/accounts/{{ident}}
orkut:
name: Orkut
url: http://www.orkut.com/Profile.aspx?uid={{ident}}
ident_label: User ID
ident_example: 1234567890123456789
service_type: network
ident_hint: You can find your Orkut user ID in your profile URL. For example: http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789
pandora:
name: Pandora
url: http://pandora.com/people/{{ident}}
ident_example: JoeUsername
picasaweb:
name: Picasa Web Albums
url: http://picasaweb.google.com/{{ident}}
service_type: photos
p0pulist:
name: p0p
url: http://p0p.com/list/hot_list/{{ident}}
ident_label: User ID
ident_example: 12345
ident_hint: You can find your p0p user ID in your Hot List URL. For example: http://p0pulist.com/list/hot_list/12345
pownce:
name: Pownce
url: http://pownce.com/{{ident}}/
service_type: status
deprecated: 1
reddit:
name: Reddit
url: http://reddit.com/user/{{ident}}/
service_type: links
skype:
name: Skype
url: callto://{{ident}}
slideshare:
name: SlideShare
url: http://www.slideshare.net/{{ident}}
smugmug:
name: Smugmug
url: http://{{ident}}.smugmug.com/
service_type: photos
sonicliving:
name: SonicLiving
url: http://www.sonicliving.com/user/{{ident}}/
ident_label: User ID
ident_example: 12345
ident_hint: You can find your SonicLiving user ID in your Share & Subscribe URL. For example: http://sonicliving.com/user/12345/feeds
steam:
name: Steam
url: http://steamcommunity.com/id/{{ident}}
stumbleupon:
name: StumbleUpon
url: http://{{ident}}.stumbleupon.com/
tabblo:
name: Tabblo
url: http://www.tabblo.com/studio/person/{{ident}}/
technorati:
name: Technorati
url: http://technorati.com/people/technorati/{{ident}}
tribe:
name: Tribe
url: http://people.tribe.net/{{ident}}
service_type: network
ident_label: User ID
ident_example: dcdc61ed-696a-40b5-80c1-e9a9809a726a
ident_hint: You can find your Tribe user ID in your profile URL. For example: http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a
tumblr:
name: Tumblr
url: http://{{ident}}.tumblr.com
icon: images/services/tumblr.gif
ident_label: URL
ident_suffix: .tumblr.com
service_type: blog
twitter:
name: Twitter
url: http://twitter.com/{{ident}}
service_type: status
typepad:
name: TypePad
ident_prefix: http://profile.typepad.com/
ident_label: Profile URL
url: http://profile.typepad.com/{{ident}}
uncrate:
name: Uncrate
url: http://www.uncrate.com/stuff/{{ident}}
upcoming:
name: Upcoming
url: http://upcoming.yahoo.com/user/{{ident}}
ident_label: User ID
ident_example: 12345
viddler:
name: Viddler
url: http://www.viddler.com/explore/{{ident}}
service_type: video
vimeo:
name: Vimeo
url: http://www.vimeo.com/{{ident}}
service_type: video
virb:
name: Virb
url: http://www.virb.com/{{ident}}
service_type: network
ident_label: User ID
ident_example: 2756504321310091
ident_hint: You can find your Virb user ID in your home URL. For example: http://www.virb.com/backend/2756504321310091/your_home
vox:
name: Vox
url: http://{{ident}}.vox.com/
ident_label: Vox name
ident_suffix: .vox.com
service_type: blog
website:
name: Website
url: '{{ident}}'
ident_label: URL
ident_example: http://www.example.com/
ident_exact: 1
can_many: 1
service_type: blog
wists:
name: Wists
url: http://www.wists.com/{{ident}}
xboxlive:
name: 'Xbox Live'
url: http://live.xbox.com/member/{{ident}}
ident_label: Gamertag
yahoo:
name: 'Yahoo! Messenger'
url: http://edit.yahoo.com/config/send_webmesg?.target={{ident}}
service_type: contact
yelp:
name: Yelp
url: http://www.yelp.com/user_details?userid={{ident}}
ident_label: User ID
ident_example: 4BXqlLKW8oP0RBCW1FvaIg
youtube:
name: YouTube
url: http://www.youtube.com/user/{{ident}}
service_type: video
zooomr:
name: Zooomr
url: http://www.zooomr.com/photos/{{ident}}
ident_example: 1234567@Z01
service_type: photos
diff --git a/plugins/ActionStreams/streams.yaml b/plugins/ActionStreams/streams.yaml
index ffee6f9..f29648f 100644
--- a/plugins/ActionStreams/streams.yaml
+++ b/plugins/ActionStreams/streams.yaml
@@ -1,863 +1,876 @@
oneup:
playing:
name: Currently Playing
description: The games in your collection you're currently playing
class: OneupPlaying
backtype:
comments:
name: Comments
description: Comments you have made on the web
fields:
- queue
html_form: '[_1] commented on <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.backtype.com/{{ident}}'
rss: 1
identifier: url
colourlovers:
colors:
name: Colors
description: Colors you saved
fields:
- queue
html_form: '[_1] saved the color <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/colors/new?lover={{ident}}'
xpath:
foreach: //color
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
palettes:
name: Palettes
description: Palettes you saved
fields:
- queue
html_form: '[_1] saved the palette <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/palettes/new?lover={{ident}}'
xpath:
foreach: //palette
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
patterns:
name: Patterns
description: Patterns you saved
fields:
- queue
html_form: '[_1] saved the pattern <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/patterns/new?lover={{ident}}'
xpath:
foreach: //pattern
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
favpalettes:
name: Favorite Palettes
description: Palettes you saved as favorites
fields:
- queue
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite palette'
html_params:
- url
- title
url: 'http://www.colourlovers.com/rss/lover/{{ident}}/palettes/favorites'
rss: 1
corkd:
reviews:
name: Reviews
description: Your wine reviews
fields:
- review
html_form: '[_1] reviewed <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/journal/{{ident}}'
rss: 1
cellar:
name: Cellar
description: Wines you own
fields:
- wine
html_form: '[_1] owns <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/cellar/{{ident}}'
rss: 1
list:
name: Shopping List
description: Wines you want to buy
fields:
- wine
html_form: '[_1] wants <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/shoppinglist/{{ident}}'
rss: 1
delicious:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.delicious.com/v2/rss/{{ident}}?plain'
identifier: url
rss:
note: description
tags: category/child::text()
digg:
links:
name: Dugg
description: Links you dugg
html_form: '[_1] dugg the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://digg.com/users/{{ident}}/history/diggs.rss'
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
submitted:
name: Submissions
description: Links you submitted
html_form: '[_1] submitted the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://digg.com/users/{{ident}}/history/submissions.rss
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
ffffound:
favorites:
name: Found
description: Photos you found
html_form: '[_1] ffffound <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://ffffound.com/home/{{ident}}/found/feed
rss: 1
flickr:
favorites:
name: Favorites
description: Photos you marked as favorites
fields:
- by
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite photo'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_faves.gne?nsid={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
by: author/name
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_public.gne?id={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
friendfeed:
likes:
name: Likes
description: Things from your friends that you "like"
html_form: '[_1] likes <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://friendfeed.com/{{ident}}/likes?format=atom'
atom:
url: link/@href
gametap:
scores:
name: Leaderboard scores
description: Your high scores in games with leaderboards
fields:
- score
html_form: '[_1] scored <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- score
- url
- title
url: http://www.gametap.com/profile/leaderboards.do?sn={{ident}}
identifier: title,score
scraper:
foreach: 'div.buddy-leaderboards div.tr'
get:
url:
- 'div.name a'
- '@href'
title:
- 'div.name strong'
- TEXT
score:
- 'div.name div'
- TEXT
goodreads:
toread:
name: To read
description: Books on your "to-read" shelf
fields:
- by
html_form: '[_1] saved <a href="[_2]"><i>[_3]</i> by [_4]</a> to read'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=to-read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
reading:
name: Reading
description: Books on your "currently-reading" shelf
fields:
- by
html_form: '[_1] started reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=currently-reading'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
read:
name: Read
description: Books on your "read" shelf
fields:
- by
html_form: '[_1] finished reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
googlereader:
links:
name: Shared
description: Your shared items
html_form: '[_1] shared <a href="[_2]">[_3]</a> from <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- source_url
- source_title
class: GoogleReader
iconbuffet:
icons:
name: Deliveries
description: Icon sets you were delivered
html_form: '[_1] received the icon set <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.iconbuffet.com/people/{{ident}};received_packages'
identifier: url
scraper:
foreach: 'div#icons div.preview-sm'
get:
title:
- a span
- TEXT
url:
- a
- '@href'
identica:
statuses:
name: Notices
description: Notices you posted
html_form: '[_1] <a href="[_2]">said</a>, “[_3]”'
html_params:
- url
- title
url: 'http://identi.ca/{{ident}}/rss'
rss:
created_on: dc:date
class: Identica
iminta:
links:
name: Intas
description: Links you saved
html_form: '[_1] is inta <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://iminta.com/people/{{ident}}/rss.xml?inta_source_id=11'
rss: 1
+instructables:
+ favorites:
+ name: Favorites
+ description: Instructables you saved as favorites
+ html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite'
+ html_params:
+ - url
+ - title
+ url: http://www.instructables.com/member/{{ident}}/rss.xml?show=good
+ rss:
+ created_on: ''
+ modified_on: ''
+ thumbnail: imageThumb
istockphoto:
photos:
name: Photos
description: Photos you posted that were approved
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.istockphoto.com/webservices/feeds/?feedFormat=IStockAtom_1_0&feedName=istockfeed.image.newestUploads&feedParams=UserID={{ident}}'
identifier: url
atom:
thumbnail: content/div/a/img/@src
iusethis:
events:
name: Recent events
description: Events from your recent events feed
html_form: '[_1] <a href="[_2]">[_3]</a>'
html_params:
- url
- title
rss: 1
url: 'http://osx.iusethis.com/user/feed.rss/{{ident}}?following=0'
osxapps:
name: Apps you use
description: The applications you saved as ones you use
fields:
- favorite
html_form: '[_1] started using <a href="[_2]">[_3]</a>[quant,_4, (and loves it),,]'
html_params:
- url
- title
- favorite
url: 'http://osx.iusethis.com/user/{{ident}}'
iwatchthis:
favorites:
name: Favorites
description: Videos you saved as watched
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video'
html_params:
- url
- title
url: 'http://iwatchthis.com/rss/{{ident}}'
rss: 1
jaiku:
jaikus:
name: Jaikus
description: Jaikus you posted
html_form: '[_1] <a href="[_2]">jaiku''d</a>, "[_3]"'
html_params:
- url
- title
url: 'http://{{ident}}.jaiku.com/feed/atom'
atom: 1
kongregate:
favorites:
name: Favorites
description: Games you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite game'
html_params:
- url
- title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url
scraper:
foreach: #favorites dl
get:
url:
- dd a
- '@href'
title:
- dd a
- TEXT
thumbnail:
- dt img
- '@src'
achievements:
name: Achievements
description: Achievements you won
fields:
- game_title
html_form: '[_1] won the <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- title
- url
- game_title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url,title
scraper:
foreach: #achievements .badge_details
get:
url:
- dt.badge_img a
- '@href'
thumbnail:
- dt.badge_img img
- '@style'
title:
- dd.badge_name
- TEXT
game_title:
- a.badge_game
- TEXT
lastfm:
tracks:
name: Tracks
description: Songs you recently listened to (High spam potential!)
html_form: '[_1] heard <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/recenttracks.rss'
rss: 1
lovedtracks:
name: Loved Tracks
description: Songs you marked as "loved"
fields:
- artist
html_form: '[_1] loved <a href="[_2]">[_3]</a> by [_4]'
html_params:
- url
- title
- artist
url: 'http://pipes.yahoo.com/pipes/pipe.run?_id=4smlkvMW3RGPpBPfTqoASA&_render=rss&lastFM_UserName={{ident}}'
identifier: url
rss:
artist: description
journalentries:
name: Journal Entries
description: Your recent journal entries
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/journals.rss'
rss: 1
events:
name: Events
description: The events you said you'll be attending
html_form: '[_1] is attending <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/events.rss'
rss: 1
livejournal:
posts:
name: Posts
description: Your public posts to your journal
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://users.livejournal.com/{{ident}}/data/atom'
atom: 1
magnolia:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ma.gnolia.com/atom/full/people/{{ident}}'
identifier: url
atom:
tags: "category[@scheme='http://ma.gnolia.com/tags']/@term"
note: content
metafilter:
favorites:
name: Favorites
description: Posts you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite'
html_params:
- url
- title
url: 'http://www.metafilter.com/favorites/{{ident}}/posts/rss'
rss:
created_on: ''
netflix:
queue:
name: Queue
description: Movies you added to your rental queue
fields:
- queue
html_form: '[_1] queued <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/QueueRSS?id={{ident}}'
rss:
thumbnail: description
recent:
name: Recent Movies
description: Recent Rental Activity
fields:
- recent
html_form: '[_1] is watching <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/TrackingRSS?id={{ident}}'
rss:
thumbnail: description
netvibes:
links:
name: Links
description: Links you saved
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www2.netvibes.com/rest/account/{{ident}}/timeline?format=atom'
atom: 1
nytimes:
links:
name: Recommendations
description: Recommendations in your TimesPeople activities
html_form: '[_1] recommended <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://timespeople.nytimes.com/view/user/{{ident}}/rss.xml'
rss: 1
ohloh:
kudos:
name: Kudos
description: Kudos you have received
html_form: '[_1] received kudos from <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.ohloh.net/accounts/{{ident}}/kudos'
identifier: url
scraper:
foreach: 'div.received_kudo'
get:
url:
- a
- '@href'
title:
- a
- TEXT
pandora:
favorites:
name: Favorite Songs
description: Songs you marked as favorites
fields:
- album_art
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite song'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favorites.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
album_art: pandora:albumArtUrl
favoriteartists:
name: Favorite Artists
description: Artists you marked as favorites
fields:
- artist-photo-url
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite artist'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favoriteartists.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
artist-photo-url: pandora:stationImageUrl
stations:
name: Stations
description: Radio stations you added
fields:
- guid
- station-image-url
html_form: '[_1] added a new radio station named <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/stations.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: pandora:stationLink
station-image-url: pandora:stationImageUrl
picasaweb:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://picasaweb.google.com/data/feed/api/user/{{ident}}?kind=photo&max-results=15'
atom:
thumbnail: media:group/media:thumbnail[position()=2]/@url
p0pulist:
stuff:
name: List
description: Things you put in your list
html_form: '[_1] is enjoying <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://p0p.com/list/hot_list/{{ident}}.rss'
rss:
thumbnail: image/url
pownce:
statuses:
name: Notes
description: Your public notes
fields:
- note
html_form: '[_1] <a href="[_2]">posted</a>, "[_3]"'
html_params:
- url
- note
url: 'http://pownce.com/feeds/public/{{ident}}/'
atom:
note: summary
reddit:
comments:
name: Comments
description: Comments you posted
html_form: '[_1] commented on <a href="[_2]">[_3]</a> at Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/comments/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
submitted:
name: Submissions
description: Articles you submitted
html_form: '[_1] submitted <a href="[_2]">[_3]</a> to Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/submitted/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
favorites:
name: Likes
description: Articles you liked (your votes must be public)
html_form: '[_1] liked <a href="[_2]">[_3]</a> from Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/liked/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
dislikes:
name: Dislikes
description: Articles you disliked (your votes must be public)
html_form: '[_1] disliked <a href="[_2]">[_3]</a> on Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/disliked/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
slideshare:
favorites:
name: Favorites
description: Slideshows you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite slideshow'
html_params:
- url
- title
url: 'http://www.slideshare.net/rss/user/{{ident}}/favorites'
rss:
thumbnail: media:content/media:thumbnail/@url
created_on: ''
slideshows:
name: Slideshows
description: Slideshows you posted
html_form: '[_1] posted the slideshow <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.slideshare.net/rss/user/{{ident}}'
rss:
thumbnail: media:content/media:thumbnail/@url
smugmug:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">a photo</a>'
html_params:
- url
url: 'http://www.smugmug.com/hack/feed.mg?Type=nicknameRecentPhotos&Data={{ident}}&format=atom10&ImageCount=15'
atom:
thumbnail: id
steam:
achievements:
name: Achievements
description: Your achievements for achievement-enabled games
html_form: '[_1] won the <strong>[_2]</strong> achievement in <a href="http://steamcommunity.com/id/[_3]/stats/[_4]?tab=achievements">[_5]</a>'
html_params:
- title
- ident
- gamecode
- game
class: Steam
tumblr:
events:
name: Stuff
description: Things you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://{{ident}}.tumblr.com/rss'
rss: 1
twitter:
statuses:
name: Tweets
description: Your public tweets
class: TwitterTweet
html_form: '[_1] <a href="[_2]">tweeted</a>, "[_3]"'
html_params:
- url
- title
url: 'http://twitter.com/statuses/user_timeline/{{ident}}.atom'
atom: 1
favorites:
name: Favorites
description: Public tweets you saved as favorites
class: TwitterFavorite
fields:
- tweet_author
html_form: '[_1] saved <a href="[_2]">[_3]''s tweet</a>, "[_4]" as a favorite'
html_params:
- url
- tweet_author
- title
url: 'http://twitter.com/favorites/{{ident}}.atom'
atom:
created_on: ''
modified_on: ''
typepad:
comments:
name: Comments
description: Comments you posted
html_form: '[_1] left a comment on <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://profile.typepad.com/{{ident}}/comments/atom.xml'
atom: 1
uncrate:
saved:
name: Saved
description: Things you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> on Uncrate'
html_params:
- url
- title
url: 'http://www.uncrate.com/stuff/{{ident}}'
identifier: url
|
markpasc/mt-plugin-action-streams
|
9f7de5af002e823c790fc8dc82e52282af83f55a
|
Add MetaFilter favorites stream
|
diff --git a/mt-static/plugins/ActionStreams/images/services/metafilter.png b/mt-static/plugins/ActionStreams/images/services/metafilter.png
new file mode 100644
index 0000000..616acbc
Binary files /dev/null and b/mt-static/plugins/ActionStreams/images/services/metafilter.png differ
diff --git a/plugins/ActionStreams/config.yaml b/plugins/ActionStreams/config.yaml
index 5202d01..53dc8b2 100644
--- a/plugins/ActionStreams/config.yaml
+++ b/plugins/ActionStreams/config.yaml
@@ -1,195 +1,196 @@
name: Action Streams
id: ActionStreams
key: ActionStreams
author_link: http://www.sixapart.com/
author_name: Six Apart Ltd.
description: <MT_TRANS phrase="Manages authors' accounts and actions on sites elsewhere around the web">
schema_version: 16
version: 2.2
plugin_link: http://www.sixapart.com/
settings:
rebuild_for_action_stream_events:
Default: 0
Scope: blog
l10n_class: ActionStreams::L10N
blog_config_template: blog_config_template.tmpl
init_app: $ActionStreams::ActionStreams::Init::init_app
applications:
cms:
methods:
list_profileevent: $ActionStreams::ActionStreams::Plugin::list_profileevent
other_profiles: $ActionStreams::ActionStreams::Plugin::other_profiles
dialog_add_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile
dialog_edit_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile
add_other_profile: $ActionStreams::ActionStreams::Plugin::add_other_profile
edit_other_profile: $ActionStreams::ActionStreams::Plugin::edit_other_profile
remove_other_profile: $ActionStreams::ActionStreams::Plugin::remove_other_profile
itemset_update_profiles: $ActionStreams::ActionStreams::Plugin::itemset_update_profiles
itemset_hide_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_events
itemset_show_events: $ActionStreams::ActionStreams::Plugin::itemset_show_events
itemset_hide_all_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events
itemset_show_all_events: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events
community:
methods:
profile_add_external_profile: $ActionStreams::ActionStreams::Plugin::profile_add_external_profile
profile_delete_external_profile: $ActionStreams::ActionStreams::Plugin::profile_delete_external_profile
callbacks:
post_add_profile: $ActionStreams::ActionStreams::Plugin::profile_first_update_events
callbacks:
MT::App::CMS::template_param.edit_author: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::template_param.list_member: $ActionStreams::ActionStreams::Plugin::param_list_member
MT::App::CMS::template_param.other_profiles: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::template_param.list_profileevent: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::post_add_profile: $ActionStreams::ActionStreams::Plugin::first_profile_update
post_action_streams_task: $ActionStreams::ActionStreams::Plugin::rebuild_action_stream_blogs
pre_build_action_streams_event.flickr_favorites: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail
pre_build_action_streams_event.flickr_photos: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail
pre_build_action_streams_event.gametap_scores: $ActionStreams::ActionStreams::Fix::gametap_score_stuff
pre_build_action_streams_event.identica_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name
pre_build_action_streams_event.iminta_links: $ActionStreams::ActionStreams::Fix::iminta_link_title
pre_build_action_streams_event.iusethis_events: $ActionStreams::ActionStreams::Fix::iusethis_event_title
pre_build_action_streams_event.kongregate_achievements: $ActionStreams::ActionStreams::Fix::kongregate_achievement_title_thumb
pre_build_action_streams_event.magnolia_links: $ActionStreams::ActionStreams::Fix::magnolia_link_notes
+ pre_build_action_streams_event.metafilter_favorites: $ActionStreams::ActionStreams::Fix::metafilter_favorites_titles
pre_build_action_streams_event.netflix_queue: $ActionStreams::ActionStreams::Fix::netflix_queue_prefix_thumb
pre_build_action_streams_event.netflix_recent: $ActionStreams::ActionStreams::Fix::netflix_recent_prefix_thumb
pre_build_action_streams_event.p0pulist_stuff: $ActionStreams::ActionStreams::Fix::p0pulist_stuff_urls
pre_build_action_streams_event.twitter_favorites: $ActionStreams::ActionStreams::Fix::twitter_favorite_author
pre_build_action_streams_event.twitter_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name
pre_build_action_streams_event.typepad_comments: $ActionStreams::ActionStreams::Fix::typepad_comment_titles
pre_build_action_streams_event.wists_wists: $ActionStreams::ActionStreams::Fix::wists_thumb
filter_action_streams_event.nytimes_links: $ActionStreams::ActionStreams::Fix::nytimes_links_titles
object_types:
profileevent: ActionStreams::Event
as: ActionStreams::Event
as_ua_cache: ActionStreams::UserAgent::Cache
list_actions:
profileevent:
hide_all:
label: Hide All
order: 100
js: finishPluginActionAll
code: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events
continue_prompt_handler: >
sub { MT->translate('Are you sure you want to hide EVERY event in EVERY action stream?') }
show_all:
label: Show All
order: 200
js: finishPluginActionAll
code: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events
continue_prompt_handler: >
sub { MT->translate('Are you sure you want to show EVERY event in EVERY action stream?') }
delete:
label: Delete
order: 300
code: $core::MT::App::CMS::delete
continue_prompt_handler: >
sub { MT->translate('Deleted events that are still available from the remote service will be added back in the next scan. Only events that are no longer available from your profile will remain deleted. Are you sure you want to delete the selected event(s)?') }
tags:
function:
StreamAction: $ActionStreams::ActionStreams::Tags::stream_action
StreamActionID: $ActionStreams::ActionStreams::Tags::stream_action_id
StreamActionVar: $ActionStreams::ActionStreams::Tags::stream_action_var
StreamActionDate: $ActionStreams::ActionStreams::Tags::stream_action_date
StreamActionModifiedDate: $ActionStreams::ActionStreams::Tags::stream_action_modified_date
StreamActionTitle: $ActionStreams::ActionStreams::Tags::stream_action_title
StreamActionURL: $ActionStreams::ActionStreams::Tags::stream_action_url
StreamActionThumbnailURL: $ActionStreams::ActionStreams::Tags::stream_action_thumbnail_url
StreamActionVia: $ActionStreams::ActionStreams::Tags::stream_action_via
OtherProfileVar: $ActionStreams::ActionStreams::Tags::other_profile_var
block:
ActionStreams: $ActionStreams::ActionStreams::Tags::action_streams
StreamActionTags: $ActionStreams::ActionStreams::Tags::stream_action_tags
OtherProfiles: $ActionStreams::ActionStreams::Tags::other_profiles
ProfileServices: $ActionStreams::ActionStreams::Tags::profile_services
StreamActionRollup: $ActionStreams::ActionStreams::Tags::stream_action_rollup
tasks:
UpdateEvents:
frequency: 1800
label: Poll for new events
code: $ActionStreams::ActionStreams::Plugin::update_events
task_workers:
UpdateEvents:
label: Update Events
class: ActionStreams::Worker
widgets:
asotd:
label: Recent Actions
template: widget_recent.mtml
permission: post
singular: 1
set: sidebar
handler: $ActionStreams::ActionStreams::Plugin::widget_recent
condition: $ActionStreams::ActionStreams::Plugin::widget_blog_dashboard_only
template_sets:
streams:
label: Action Stream
base_path: 'blog_tmpl'
base_css: themes-base/blog.css
order: 100
templates:
index:
main_index:
label: Main Index (Recent Actions)
outfile: index.html
rebuild_me: 1
archive:
label: Action Archive
outfile: archive.html
rebuild_me: 1
styles:
label: Stylesheet
outfile: styles.css
rebuild_me: 1
feed_recent:
label: Feed - Recent Activity
outfile: atom.xml
rebuild_me: 1
module:
html_head:
label: HTML Head
banner_header:
label: Banner Header
banner_footer:
label: Banner Footer
sidebar:
label: Sidebar
widget:
elsewhere:
label: Find Authors Elsewhere
actions:
label: Recent Actions
widgetset:
2column_layout_sidebar:
label: 2-column layout - Sidebar
widgets:
- Find Authors Elsewhere
upgrade_functions:
enable_existing_streams:
version_limit: 9
updater:
type: author
label: Enabling default action streams for selected profiles...
code: $ActionStreams::ActionStreams::Upgrade::enable_existing_streams
reclass_actions:
version_limit: 15
handler: $ActionStreams::ActionStreams::Upgrade::reclass_actions
priority: 8
rename_action_metadata:
version_limit: 15
handler: $ActionStreams::ActionStreams::Upgrade::rename_action_metadata
priority: 9
upgrade_data:
reclass_actions:
twitter_tweets: twitter_statuses
pownce_notes: pownce_statuses
googlereader_shared: googlereader_links
rename_action_metadata:
- action_type: delicious_links
old: annotation
new: note
- action_type: googlereader_links
old: annotation
new: note
profile_services: services.yaml
action_streams: streams.yaml
diff --git a/plugins/ActionStreams/lib/ActionStreams/Fix.pm b/plugins/ActionStreams/lib/ActionStreams/Fix.pm
index 4a88ed8..8067d37 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Fix.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Fix.pm
@@ -1,146 +1,151 @@
package ActionStreams::Fix;
use strict;
use warnings;
use ActionStreams::Scraper;
sub _twitter_add_tags_to_item {
my ($item) = @_;
if (my @tags = $item->{title} =~ m{
(?: \A | \s ) # BOT or whitespace
\# # hash
(\w\S*\w) # tag
(?<! 's ) # but don't end with 's
}xmsg) {
$item->{tags} = \@tags;
}
}
sub twitter_tweet_name {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the Twitter username from the front of the tweet.
my $ident = $profile->{ident};
$item->{title} =~ s{ \A \s* \Q$ident\E : \s* }{}xmsi;
_twitter_add_tags_to_item($item);
}
sub twitter_favorite_author {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the Twitter username from the front of the tweet.
if ($item->{title} =~ s{ \A \s* ([^\s:]+) : \s* }{}xms) {
$item->{tweet_author} = $1;
}
_twitter_add_tags_to_item($item);
}
sub flickr_photo_thumbnail {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Extract just the URL, and use the _t size thumbnail, not the _m size image.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ (http://farm[^\.]+\.static\.flickr\.com .*? _m.jpg) }xms) {
$thumb = $1;
$thumb =~ s{ _m.jpg \z }{_t.jpg}xms;
$item->{thumbnail} = $thumb;
}
}
sub iminta_link_title {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the username for when we add it back in later.
$item->{title} =~ s{ (?: \s* :: [^:]+ ){2} \z }{}xms;
}
sub iusethis_event_title {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the username for when we add it back in later.
$item->{title} =~ s{ \A \w+ \s* }{}xms;
}
+sub metafilter_favorites_titles {
+ my ($cb, $app, $item, $event, $author, $profile) = @_;
+ $item->{title} =~ s{ \A [^:]+ : \s* }{}xms;
+}
+
sub netflix_recent_prefix_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the 'Shipped:' or 'Received:' prefix.
$item->{title} =~ s{ \A [^:]*: \s* }{}xms;
# Extract thumbnail from description.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m/ <img src="([^"]+)"} /xms) {
$item->{thumbnail} = $1;
}
}
sub netflix_queue_prefix_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the item number.
$item->{title} =~ s{ \A \d+ [\W\S] \s* }{}xms;
# Extract thumbnail from description.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m/ <img src="([^"]+)"} /xms) {
$item->{thumbnail} = $1;
}
}
sub nytimes_links_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
return $item->{title} =~ s{ \A [^:]* recommended [^:]* : \s* }{}xms ? 1 : 0;
}
sub p0pulist_stuff_urls {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{url} =~ s{ \A / }{http://p0pulist.com/}xms;
}
sub kongregate_achievement_title_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the parenthetical from the end of the title.
$item->{title} =~ s{ \( [^)]* \) \z }{}xms;
# Pick the actual achievement badge out of the inline CSS.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ background-image: \s* url\( ([^)]+) }xms) {
$item->{thumbnail} = $1;
}
}
sub wists_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Grab the wists thumbnail out.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ (http://cache.wists.com/thumbnails/ [^"]+ ) }xms) {
$item->{thumbnail} = $1;
}
}
sub gametap_score_stuff {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{score} =~ s{ \D }{}xmsg;
$item->{url} = q{} . $item->{url};
$item->{url} =~ s{ \A / }{http://www.gametap.com/}xms;
}
sub typepad_comment_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{title} =~ s{ \A .*? ' }{}xms;
$item->{title} =~ s{ ' \z }{}xms;
}
sub magnolia_link_notes {
my ($cb, $app, $item, $event, $author, $profile) = @_;
my $scraper = scraper {
process '//p[position()=2]', note => 'TEXT';
};
my $result = $scraper->scrape(\$item->{note});
if ($result->{note}) {
$item->{note} = $result->{note};
}
else {
delete $item->{note};
}
}
1;
diff --git a/plugins/ActionStreams/services.yaml b/plugins/ActionStreams/services.yaml
index 82792ab..cbf4499 100644
--- a/plugins/ActionStreams/services.yaml
+++ b/plugins/ActionStreams/services.yaml
@@ -1,341 +1,346 @@
oneup:
name: 1up.com
url: http://{{ident}}.1up.com/
fortythreethings:
name: 43Things
url: http://www.43things.com/person/{{ident}}/
aim:
name: AIM
url: aim:goim?screenname={{ident}}
ident_label: Screen name
service_type: contact
backtype:
name: backtype
url: http://www.backtype.com/{{ident}}
service_type: comments
bebo:
name: Bebo
url: http://www.bebo.com/Profile.jsp?MemberId={{ident}}
service_type: network
catster:
name: Catster
url: http://www.catster.com/cats/{{ident}}
colourlovers:
name: COLOURlovers
url: http://www.colourlovers.com/lover/{{ident}}
corkd:
name: 'Cork''d'
url: http://www.corkd.com/people/{{ident}}
delicious:
name: Delicious
url: http://delicious.com/{{ident}}/
service_type: links
destructoid:
name: Destructoid
url: http://www.destructoid.com/elephant/profile.phtml?un={{ident}}
digg:
name: Digg
url: http://digg.com/users/{{ident}}/
service_type: links
dodgeball:
name: Dodgeball
url: http://www.dodgeball.com/user?uid={{ident}}
deprecated: 1
dogster:
name: Dogster
url: http://www.dogster.com/dogs/{{ident}}
dopplr:
name: Dopplr
url: http://www.dopplr.com/traveller/{{ident}}/
facebook:
name: Facebook
url: http://www.facebook.com/profile.php?id={{ident}}
ident_label: User ID
ident_example: 12345
service_type: network
ident_hint: You can find your Facebook user ID in your profile URL. For example: http://www.facebook.com/profile.php?id=12345
ffffound:
name: FFFFOUND!
url: http://ffffound.com/home/{{ident}}/found/
service_type: photos
flickr:
name: Flickr
url: http://flickr.com/photos/{{ident}}/
ident_example: 36381329@N00
service_type: photos
ident_hint: Enter your Flickr user ID that has a "@" in it. Your Flickr user ID is NOT the username in the URL of your photo stream.
friendfeed:
name: FriendFeed
url: http://friendfeed.com/{{ident}}
ident_example: JoeUsername
gametap:
name: Gametap
url: http://www.gametap.com/profile/show/profile.do?sn={{ident}}
goodreads:
name: Goodreads
url: http://www.goodreads.com/user/show/{{ident}}
ident_label: User ID
ident_example: 12345
ident_hint: You can find your Goodreads user ID in your profile URL. For example: http://www.goodreads.com/user/show/12345
googlereader:
name: Google Reader
url: http://www.google.com/reader/shared/{{ident}}
ident_label: Sharing ID
ident_example: http://www.google.com/reader/shared/16793324975410272738
service_type: links
hi5:
name: Hi5
url: http://hi5.com/friend/profile/displayProfile.do?userid={{ident}}
service_type: network
iconbuffet:
name: IconBuffet
url: http://www.iconbuffet.com/people/{{ident}}
icq:
name: ICQ
url: http://www.icq.com/people/about_me.php?uin={{ident}}
ident_label: UIN
ident_example: 12345
service_type: contact
identica:
name: Identi.ca
url: http://identi.ca/{{ident}}
service_type: status
iminta:
name: Iminta
url: http://iminta.com/people/{{ident}}
istockphoto:
name: iStockphoto
url: http://www.istockphoto.com/user_view.php?id={{ident}}
ident_label: User ID
ident_example: 123456
ident_hint: You can find your iStockphoto user ID in your profile URL. For example: http://www.istockphoto.com/user_view.php?id=123456
iusethis:
name: IUseThis
url: http://osx.iusethis.com/user/{{ident}}
iwatchthis:
name: iwatchthis
url: http://iwatchthis.com/{{ident}}
jabber:
name: Jabber
url: jabber://{{ident}}
ident_label: Jabber ID
ident_example: [email protected]
service_type: contact
jaiku:
name: Jaiku
url: http://{{ident}}.jaiku.com/
ident_suffix: .jaiku.com
service_type: status
kongregate:
name: Kongregate
url: http://www.kongregate.com/accounts/{{ident}}
lastfm:
name: Last.fm
url: http://www.last.fm/user/{{ident}}/
ident_example: JoeUsername
linkedin:
name: LinkedIn
url: http://www.linkedin.com/in/{{ident}}
ident_example: MelodyNelson
ident_prefix: http://www.linkedin.com/in/
ident_label: Profile URL
service_type: network
livejournal:
name: LiveJournal
url: http://{{ident}}.livejournal.com/
ident_suffix: .livejournal.com
service_type: blog
magnolia:
name: Ma.gnolia
url: http://ma.gnolia.com/people/{{ident}}
service_type: links
deprecated: 1
+metafilter:
+ name: MetaFilter
+ url: http://www.metafilter.com/user/{{ident}}
+ ident_label: User Number
+ ident_example: 11039
mog:
name: MOG
url: http://mog.com/{{ident}}
msn:
name: 'MSN Messenger'
url: msnim:chat?contact={{ident}}
service_type: contact
multiply:
name: Multiply
url: http://{{ident}}.multiply.com/
myspace:
name: MySpace
url: http://www.myspace.com/{{ident}}
ident_label: User ID
ident_prefix: http://www.myspace.com/
service_type: network
netflix:
name: Netflix
url: http://rss.netflix.com/QueueRSS?id={{ident}}
ident_label: Netflix RSS ID
ident_example: P0000006746939516625352861892808956
ident_hint: To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.
netvibes:
name: Netvibes
url: http://www.netvibes.com/{{ident}}
service_type: links
newsvine:
name: Newsvine
url: http://{{ident}}.newsvine.com/
ning:
name: Ning
url: http://{{ident}}.ning.com/
service_type: network
ident_suffix: .ning.com/
ident_prefix: http://
ident_label: Social Network URL
nytimes:
name: New York Times (TimesPeople)
url: http://timespeople.nytimes.com/view/user/{{ident}}/activities.html
service_type: links
ident_label: Activity URL
ident_example: http://timespeople.nytimes.com/view/user/57963079/activities.html
ohloh:
name: Ohloh
url: http://ohloh.net/accounts/{{ident}}
orkut:
name: Orkut
url: http://www.orkut.com/Profile.aspx?uid={{ident}}
ident_label: User ID
ident_example: 1234567890123456789
service_type: network
ident_hint: You can find your Orkut user ID in your profile URL. For example: http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789
pandora:
name: Pandora
url: http://pandora.com/people/{{ident}}
ident_example: JoeUsername
picasaweb:
name: Picasa Web Albums
url: http://picasaweb.google.com/{{ident}}
service_type: photos
p0pulist:
name: p0p
url: http://p0p.com/list/hot_list/{{ident}}
ident_label: User ID
ident_example: 12345
ident_hint: You can find your p0p user ID in your Hot List URL. For example: http://p0pulist.com/list/hot_list/12345
pownce:
name: Pownce
url: http://pownce.com/{{ident}}/
service_type: status
deprecated: 1
reddit:
name: Reddit
url: http://reddit.com/user/{{ident}}/
service_type: links
skype:
name: Skype
url: callto://{{ident}}
slideshare:
name: SlideShare
url: http://www.slideshare.net/{{ident}}
smugmug:
name: Smugmug
url: http://{{ident}}.smugmug.com/
service_type: photos
sonicliving:
name: SonicLiving
url: http://www.sonicliving.com/user/{{ident}}/
ident_label: User ID
ident_example: 12345
ident_hint: You can find your SonicLiving user ID in your Share & Subscribe URL. For example: http://sonicliving.com/user/12345/feeds
steam:
name: Steam
url: http://steamcommunity.com/id/{{ident}}
stumbleupon:
name: StumbleUpon
url: http://{{ident}}.stumbleupon.com/
tabblo:
name: Tabblo
url: http://www.tabblo.com/studio/person/{{ident}}/
technorati:
name: Technorati
url: http://technorati.com/people/technorati/{{ident}}
tribe:
name: Tribe
url: http://people.tribe.net/{{ident}}
service_type: network
ident_label: User ID
ident_example: dcdc61ed-696a-40b5-80c1-e9a9809a726a
ident_hint: You can find your Tribe user ID in your profile URL. For example: http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a
tumblr:
name: Tumblr
url: http://{{ident}}.tumblr.com
icon: images/services/tumblr.gif
ident_label: URL
ident_suffix: .tumblr.com
service_type: blog
twitter:
name: Twitter
url: http://twitter.com/{{ident}}
service_type: status
typepad:
name: TypePad
ident_prefix: http://profile.typepad.com/
ident_label: Profile URL
url: http://profile.typepad.com/{{ident}}
uncrate:
name: Uncrate
url: http://www.uncrate.com/stuff/{{ident}}
upcoming:
name: Upcoming
url: http://upcoming.yahoo.com/user/{{ident}}
ident_label: User ID
ident_example: 12345
viddler:
name: Viddler
url: http://www.viddler.com/explore/{{ident}}
service_type: video
vimeo:
name: Vimeo
url: http://www.vimeo.com/{{ident}}
service_type: video
virb:
name: Virb
url: http://www.virb.com/{{ident}}
service_type: network
ident_label: User ID
ident_example: 2756504321310091
ident_hint: You can find your Virb user ID in your home URL. For example: http://www.virb.com/backend/2756504321310091/your_home
vox:
name: Vox
url: http://{{ident}}.vox.com/
ident_label: Vox name
ident_suffix: .vox.com
service_type: blog
website:
name: Website
url: '{{ident}}'
ident_label: URL
ident_example: http://www.example.com/
ident_exact: 1
can_many: 1
service_type: blog
wists:
name: Wists
url: http://www.wists.com/{{ident}}
xboxlive:
name: 'Xbox Live'
url: http://live.xbox.com/member/{{ident}}
ident_label: Gamertag
yahoo:
name: 'Yahoo! Messenger'
url: http://edit.yahoo.com/config/send_webmesg?.target={{ident}}
service_type: contact
yelp:
name: Yelp
url: http://www.yelp.com/user_details?userid={{ident}}
ident_label: User ID
ident_example: 4BXqlLKW8oP0RBCW1FvaIg
youtube:
name: YouTube
url: http://www.youtube.com/user/{{ident}}
service_type: video
zooomr:
name: Zooomr
url: http://www.zooomr.com/photos/{{ident}}
ident_example: 1234567@Z01
service_type: photos
diff --git a/plugins/ActionStreams/streams.yaml b/plugins/ActionStreams/streams.yaml
index 61cc3e6..ffee6f9 100644
--- a/plugins/ActionStreams/streams.yaml
+++ b/plugins/ActionStreams/streams.yaml
@@ -9,1024 +9,1035 @@ backtype:
description: Comments you have made on the web
fields:
- queue
html_form: '[_1] commented on <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.backtype.com/{{ident}}'
rss: 1
identifier: url
colourlovers:
colors:
name: Colors
description: Colors you saved
fields:
- queue
html_form: '[_1] saved the color <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/colors/new?lover={{ident}}'
xpath:
foreach: //color
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
palettes:
name: Palettes
description: Palettes you saved
fields:
- queue
html_form: '[_1] saved the palette <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/palettes/new?lover={{ident}}'
xpath:
foreach: //palette
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
patterns:
name: Patterns
description: Patterns you saved
fields:
- queue
html_form: '[_1] saved the pattern <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/patterns/new?lover={{ident}}'
xpath:
foreach: //pattern
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
favpalettes:
name: Favorite Palettes
description: Palettes you saved as favorites
fields:
- queue
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite palette'
html_params:
- url
- title
url: 'http://www.colourlovers.com/rss/lover/{{ident}}/palettes/favorites'
rss: 1
corkd:
reviews:
name: Reviews
description: Your wine reviews
fields:
- review
html_form: '[_1] reviewed <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/journal/{{ident}}'
rss: 1
cellar:
name: Cellar
description: Wines you own
fields:
- wine
html_form: '[_1] owns <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/cellar/{{ident}}'
rss: 1
list:
name: Shopping List
description: Wines you want to buy
fields:
- wine
html_form: '[_1] wants <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/shoppinglist/{{ident}}'
rss: 1
delicious:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.delicious.com/v2/rss/{{ident}}?plain'
identifier: url
rss:
note: description
tags: category/child::text()
digg:
links:
name: Dugg
description: Links you dugg
html_form: '[_1] dugg the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://digg.com/users/{{ident}}/history/diggs.rss'
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
submitted:
name: Submissions
description: Links you submitted
html_form: '[_1] submitted the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://digg.com/users/{{ident}}/history/submissions.rss
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
ffffound:
favorites:
name: Found
description: Photos you found
html_form: '[_1] ffffound <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://ffffound.com/home/{{ident}}/found/feed
rss: 1
flickr:
favorites:
name: Favorites
description: Photos you marked as favorites
fields:
- by
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite photo'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_faves.gne?nsid={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
by: author/name
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_public.gne?id={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
friendfeed:
likes:
name: Likes
description: Things from your friends that you "like"
html_form: '[_1] likes <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://friendfeed.com/{{ident}}/likes?format=atom'
atom:
url: link/@href
gametap:
scores:
name: Leaderboard scores
description: Your high scores in games with leaderboards
fields:
- score
html_form: '[_1] scored <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- score
- url
- title
url: http://www.gametap.com/profile/leaderboards.do?sn={{ident}}
identifier: title,score
scraper:
foreach: 'div.buddy-leaderboards div.tr'
get:
url:
- 'div.name a'
- '@href'
title:
- 'div.name strong'
- TEXT
score:
- 'div.name div'
- TEXT
goodreads:
toread:
name: To read
description: Books on your "to-read" shelf
fields:
- by
html_form: '[_1] saved <a href="[_2]"><i>[_3]</i> by [_4]</a> to read'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=to-read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
reading:
name: Reading
description: Books on your "currently-reading" shelf
fields:
- by
html_form: '[_1] started reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=currently-reading'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
read:
name: Read
description: Books on your "read" shelf
fields:
- by
html_form: '[_1] finished reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
googlereader:
links:
name: Shared
description: Your shared items
html_form: '[_1] shared <a href="[_2]">[_3]</a> from <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- source_url
- source_title
class: GoogleReader
iconbuffet:
icons:
name: Deliveries
description: Icon sets you were delivered
html_form: '[_1] received the icon set <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.iconbuffet.com/people/{{ident}};received_packages'
identifier: url
scraper:
foreach: 'div#icons div.preview-sm'
get:
title:
- a span
- TEXT
url:
- a
- '@href'
identica:
statuses:
name: Notices
description: Notices you posted
html_form: '[_1] <a href="[_2]">said</a>, “[_3]”'
html_params:
- url
- title
url: 'http://identi.ca/{{ident}}/rss'
rss:
created_on: dc:date
class: Identica
iminta:
links:
name: Intas
description: Links you saved
html_form: '[_1] is inta <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://iminta.com/people/{{ident}}/rss.xml?inta_source_id=11'
rss: 1
istockphoto:
photos:
name: Photos
description: Photos you posted that were approved
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.istockphoto.com/webservices/feeds/?feedFormat=IStockAtom_1_0&feedName=istockfeed.image.newestUploads&feedParams=UserID={{ident}}'
identifier: url
atom:
thumbnail: content/div/a/img/@src
iusethis:
events:
name: Recent events
description: Events from your recent events feed
html_form: '[_1] <a href="[_2]">[_3]</a>'
html_params:
- url
- title
rss: 1
url: 'http://osx.iusethis.com/user/feed.rss/{{ident}}?following=0'
osxapps:
name: Apps you use
description: The applications you saved as ones you use
fields:
- favorite
html_form: '[_1] started using <a href="[_2]">[_3]</a>[quant,_4, (and loves it),,]'
html_params:
- url
- title
- favorite
url: 'http://osx.iusethis.com/user/{{ident}}'
iwatchthis:
favorites:
name: Favorites
description: Videos you saved as watched
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video'
html_params:
- url
- title
url: 'http://iwatchthis.com/rss/{{ident}}'
rss: 1
jaiku:
jaikus:
name: Jaikus
description: Jaikus you posted
html_form: '[_1] <a href="[_2]">jaiku''d</a>, "[_3]"'
html_params:
- url
- title
url: 'http://{{ident}}.jaiku.com/feed/atom'
atom: 1
kongregate:
favorites:
name: Favorites
description: Games you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite game'
html_params:
- url
- title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url
scraper:
foreach: #favorites dl
get:
url:
- dd a
- '@href'
title:
- dd a
- TEXT
thumbnail:
- dt img
- '@src'
achievements:
name: Achievements
description: Achievements you won
fields:
- game_title
html_form: '[_1] won the <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- title
- url
- game_title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url,title
scraper:
foreach: #achievements .badge_details
get:
url:
- dt.badge_img a
- '@href'
thumbnail:
- dt.badge_img img
- '@style'
title:
- dd.badge_name
- TEXT
game_title:
- a.badge_game
- TEXT
lastfm:
tracks:
name: Tracks
description: Songs you recently listened to (High spam potential!)
html_form: '[_1] heard <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/recenttracks.rss'
rss: 1
lovedtracks:
name: Loved Tracks
description: Songs you marked as "loved"
fields:
- artist
html_form: '[_1] loved <a href="[_2]">[_3]</a> by [_4]'
html_params:
- url
- title
- artist
url: 'http://pipes.yahoo.com/pipes/pipe.run?_id=4smlkvMW3RGPpBPfTqoASA&_render=rss&lastFM_UserName={{ident}}'
identifier: url
rss:
artist: description
journalentries:
name: Journal Entries
description: Your recent journal entries
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/journals.rss'
rss: 1
events:
name: Events
description: The events you said you'll be attending
html_form: '[_1] is attending <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/events.rss'
rss: 1
livejournal:
posts:
name: Posts
description: Your public posts to your journal
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://users.livejournal.com/{{ident}}/data/atom'
atom: 1
magnolia:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ma.gnolia.com/atom/full/people/{{ident}}'
identifier: url
atom:
tags: "category[@scheme='http://ma.gnolia.com/tags']/@term"
note: content
+metafilter:
+ favorites:
+ name: Favorites
+ description: Posts you saved as favorites
+ html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite'
+ html_params:
+ - url
+ - title
+ url: 'http://www.metafilter.com/favorites/{{ident}}/posts/rss'
+ rss:
+ created_on: ''
netflix:
queue:
name: Queue
description: Movies you added to your rental queue
fields:
- queue
html_form: '[_1] queued <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/QueueRSS?id={{ident}}'
rss:
thumbnail: description
recent:
name: Recent Movies
description: Recent Rental Activity
fields:
- recent
html_form: '[_1] is watching <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/TrackingRSS?id={{ident}}'
rss:
thumbnail: description
netvibes:
links:
name: Links
description: Links you saved
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www2.netvibes.com/rest/account/{{ident}}/timeline?format=atom'
atom: 1
nytimes:
links:
name: Recommendations
description: Recommendations in your TimesPeople activities
html_form: '[_1] recommended <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://timespeople.nytimes.com/view/user/{{ident}}/rss.xml'
rss: 1
ohloh:
kudos:
name: Kudos
description: Kudos you have received
html_form: '[_1] received kudos from <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.ohloh.net/accounts/{{ident}}/kudos'
identifier: url
scraper:
foreach: 'div.received_kudo'
get:
url:
- a
- '@href'
title:
- a
- TEXT
pandora:
favorites:
name: Favorite Songs
description: Songs you marked as favorites
fields:
- album_art
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite song'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favorites.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
album_art: pandora:albumArtUrl
favoriteartists:
name: Favorite Artists
description: Artists you marked as favorites
fields:
- artist-photo-url
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite artist'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favoriteartists.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
artist-photo-url: pandora:stationImageUrl
stations:
name: Stations
description: Radio stations you added
fields:
- guid
- station-image-url
html_form: '[_1] added a new radio station named <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/stations.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: pandora:stationLink
station-image-url: pandora:stationImageUrl
picasaweb:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://picasaweb.google.com/data/feed/api/user/{{ident}}?kind=photo&max-results=15'
atom:
thumbnail: media:group/media:thumbnail[position()=2]/@url
p0pulist:
stuff:
name: List
description: Things you put in your list
html_form: '[_1] is enjoying <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://p0p.com/list/hot_list/{{ident}}.rss'
rss:
thumbnail: image/url
pownce:
statuses:
name: Notes
description: Your public notes
fields:
- note
html_form: '[_1] <a href="[_2]">posted</a>, "[_3]"'
html_params:
- url
- note
url: 'http://pownce.com/feeds/public/{{ident}}/'
atom:
note: summary
reddit:
comments:
name: Comments
description: Comments you posted
html_form: '[_1] commented on <a href="[_2]">[_3]</a> at Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/comments/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
submitted:
name: Submissions
description: Articles you submitted
html_form: '[_1] submitted <a href="[_2]">[_3]</a> to Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/submitted/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
favorites:
name: Likes
description: Articles you liked (your votes must be public)
html_form: '[_1] liked <a href="[_2]">[_3]</a> from Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/liked/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
dislikes:
name: Dislikes
description: Articles you disliked (your votes must be public)
html_form: '[_1] disliked <a href="[_2]">[_3]</a> on Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/disliked/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
slideshare:
favorites:
name: Favorites
description: Slideshows you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite slideshow'
html_params:
- url
- title
url: 'http://www.slideshare.net/rss/user/{{ident}}/favorites'
rss:
thumbnail: media:content/media:thumbnail/@url
created_on: ''
slideshows:
name: Slideshows
description: Slideshows you posted
html_form: '[_1] posted the slideshow <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.slideshare.net/rss/user/{{ident}}'
rss:
thumbnail: media:content/media:thumbnail/@url
smugmug:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">a photo</a>'
html_params:
- url
url: 'http://www.smugmug.com/hack/feed.mg?Type=nicknameRecentPhotos&Data={{ident}}&format=atom10&ImageCount=15'
atom:
thumbnail: id
steam:
achievements:
name: Achievements
description: Your achievements for achievement-enabled games
html_form: '[_1] won the <strong>[_2]</strong> achievement in <a href="http://steamcommunity.com/id/[_3]/stats/[_4]?tab=achievements">[_5]</a>'
html_params:
- title
- ident
- gamecode
- game
class: Steam
tumblr:
events:
name: Stuff
description: Things you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://{{ident}}.tumblr.com/rss'
rss: 1
twitter:
statuses:
name: Tweets
description: Your public tweets
class: TwitterTweet
html_form: '[_1] <a href="[_2]">tweeted</a>, "[_3]"'
html_params:
- url
- title
url: 'http://twitter.com/statuses/user_timeline/{{ident}}.atom'
atom: 1
favorites:
name: Favorites
description: Public tweets you saved as favorites
class: TwitterFavorite
fields:
- tweet_author
html_form: '[_1] saved <a href="[_2]">[_3]''s tweet</a>, "[_4]" as a favorite'
html_params:
- url
- tweet_author
- title
url: 'http://twitter.com/favorites/{{ident}}.atom'
atom:
created_on: ''
modified_on: ''
typepad:
comments:
name: Comments
description: Comments you posted
html_form: '[_1] left a comment on <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://profile.typepad.com/{{ident}}/comments/atom.xml'
atom: 1
uncrate:
saved:
name: Saved
description: Things you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> on Uncrate'
html_params:
- url
- title
url: 'http://www.uncrate.com/stuff/{{ident}}'
identifier: url
scraper:
foreach: '#profile-recent-actions h2'
get:
title:
- a
- TEXT
url:
- a
- '@href'
upcoming:
events:
name: Events
description: Events you are watching or attending
fields:
- venue
html_form: '[_1] is attending <a href="[_2]">[_3]</a> at [_4]'
html_params:
- url
- title
- venue
url: 'http://upcoming.yahoo.com/syndicate/v2/my_events/{{ident}}'
xpath:
foreach: //item
get:
title: xCal:summary
url: link
created_on: dc:date
modified_on: dc:date
venue: 'xCal:x-calconnect-venue/xCal:adr/xCal:x-calconnect-venue-name'
identifier: guid
viddler:
videos:
name: Videos
description: Videos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.viddler.com/explore/{{ident}}/videos/feed/'
rss:
thumbnail: media:content/media:thumbnail/@url
vimeo:
videos:
name: Videos
description: Videos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://vimeo.com/{{ident}}/videos/rss
rss:
thumbnail: media:thumbnail/@url
like:
name: Likes
description: Videos you liked
html_form: '[_1] liked <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://vimeo.com/{{ident}}/likes/rss
rss:
thumbnail: media:thumbnail/@url
created_on: ''
modified_on: ''
vox:
favorites:
name: Favorites
description: Public assets you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite'
html_params:
- url
- title
class: Vox
photos:
name: Photos
description: Your public photos in your Vox library
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://{{ident}}.vox.com/library/photos/rss.xml'
rss:
thumbnail: media:thumbnail/@url
tags: category
posts:
name: Posts
description: Your public posts to your Vox
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://{{ident}}.vox.com/library/posts/atom.xml'
atom:
tags: category/@label
website:
posted:
name: Posts
description: The posts available from the website's feed
html_form: '[_1] posted <a href="[_2]">[_3]</a> on <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- source_url
- source_title
class: Website
wists:
wists:
name: Wists
description: Stuff you saved
html_form: '[_1] wants <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.wists.com/{{ident}}?out=rdf'
identifier: url
rss:
created_on: dc:date
tags: dc:tag
thumbnail: content:encoded
xboxlive:
gamerscore:
name: Gamerscore
description: Notes when your gamerscore passes an even number
html_form: '[_1] passed <strong>[_2]</strong> gamerscore <a href="[_3]">on Xbox Live</a>'
html_params:
- score
- url
class: XboxGamerscore
yelp:
reviews:
name: Reviews
description: Places you reviewed
html_form: '[_1] reviewed <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.yelp.com/syndicate/user/{{ident}}/atom.xml'
atom:
url: link/@href
youtube:
favorites:
name: Favorites
description: Videos you saved as favorites
fields:
- by
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video'
html_params:
- url
- title
url: 'http://gdata.youtube.com/feeds/users/{{ident}}/favorites'
atom:
by: author/name
url: "link[@rel='alternate' and @type='text/html']/@href"
thumbnail: "media:group/media:thumbnail[position()=1]/@url"
created_on: ''
modified_on: ''
videos:
name: Videos
description: Videos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a> to YouTube'
html_params:
- url
- title
url: 'http://gdata.youtube.com/feeds/users/{{ident}}/uploads'
atom:
url: "link[@rel='alternate' and @type='text/html']/@href"
thumbnail: "media:group/media:thumbnail[position()=1]/@url"
zooomr:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">a photo</a>'
html_params:
- url
url: 'http://www.zooomr.com/services/feeds/public_photos/?id={{ident}}&format=rss_200'
xpath:
foreach: //item
get:
identifier: link
thumbnail: media:content/@url
|
markpasc/mt-plugin-action-streams
|
9ad9bb780320c4275068dd7fdf18f185b26c9e9f
|
Add icon for NYT service
|
diff --git a/mt-static/plugins/ActionStreams/images/services/nytimes.png b/mt-static/plugins/ActionStreams/images/services/nytimes.png
new file mode 100644
index 0000000..672607b
Binary files /dev/null and b/mt-static/plugins/ActionStreams/images/services/nytimes.png differ
|
markpasc/mt-plugin-action-streams
|
009234965d75e26193f503aaa85b8efcc5d9114b
|
Add New York Times TimesPeople recommendations stream Add filter_action_streams_event callback (like pre_build_action_streams_event but able to prevent creation of the event)
|
diff --git a/plugins/ActionStreams/config.yaml b/plugins/ActionStreams/config.yaml
index c67b3e2..5202d01 100644
--- a/plugins/ActionStreams/config.yaml
+++ b/plugins/ActionStreams/config.yaml
@@ -1,194 +1,195 @@
name: Action Streams
id: ActionStreams
key: ActionStreams
author_link: http://www.sixapart.com/
author_name: Six Apart Ltd.
description: <MT_TRANS phrase="Manages authors' accounts and actions on sites elsewhere around the web">
schema_version: 16
version: 2.2
plugin_link: http://www.sixapart.com/
settings:
rebuild_for_action_stream_events:
Default: 0
Scope: blog
l10n_class: ActionStreams::L10N
blog_config_template: blog_config_template.tmpl
init_app: $ActionStreams::ActionStreams::Init::init_app
applications:
cms:
methods:
list_profileevent: $ActionStreams::ActionStreams::Plugin::list_profileevent
other_profiles: $ActionStreams::ActionStreams::Plugin::other_profiles
dialog_add_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile
dialog_edit_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile
add_other_profile: $ActionStreams::ActionStreams::Plugin::add_other_profile
edit_other_profile: $ActionStreams::ActionStreams::Plugin::edit_other_profile
remove_other_profile: $ActionStreams::ActionStreams::Plugin::remove_other_profile
itemset_update_profiles: $ActionStreams::ActionStreams::Plugin::itemset_update_profiles
itemset_hide_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_events
itemset_show_events: $ActionStreams::ActionStreams::Plugin::itemset_show_events
itemset_hide_all_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events
itemset_show_all_events: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events
community:
methods:
profile_add_external_profile: $ActionStreams::ActionStreams::Plugin::profile_add_external_profile
profile_delete_external_profile: $ActionStreams::ActionStreams::Plugin::profile_delete_external_profile
callbacks:
post_add_profile: $ActionStreams::ActionStreams::Plugin::profile_first_update_events
callbacks:
MT::App::CMS::template_param.edit_author: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::template_param.list_member: $ActionStreams::ActionStreams::Plugin::param_list_member
MT::App::CMS::template_param.other_profiles: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::template_param.list_profileevent: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::post_add_profile: $ActionStreams::ActionStreams::Plugin::first_profile_update
post_action_streams_task: $ActionStreams::ActionStreams::Plugin::rebuild_action_stream_blogs
pre_build_action_streams_event.flickr_favorites: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail
pre_build_action_streams_event.flickr_photos: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail
pre_build_action_streams_event.gametap_scores: $ActionStreams::ActionStreams::Fix::gametap_score_stuff
pre_build_action_streams_event.identica_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name
pre_build_action_streams_event.iminta_links: $ActionStreams::ActionStreams::Fix::iminta_link_title
pre_build_action_streams_event.iusethis_events: $ActionStreams::ActionStreams::Fix::iusethis_event_title
pre_build_action_streams_event.kongregate_achievements: $ActionStreams::ActionStreams::Fix::kongregate_achievement_title_thumb
pre_build_action_streams_event.magnolia_links: $ActionStreams::ActionStreams::Fix::magnolia_link_notes
pre_build_action_streams_event.netflix_queue: $ActionStreams::ActionStreams::Fix::netflix_queue_prefix_thumb
pre_build_action_streams_event.netflix_recent: $ActionStreams::ActionStreams::Fix::netflix_recent_prefix_thumb
pre_build_action_streams_event.p0pulist_stuff: $ActionStreams::ActionStreams::Fix::p0pulist_stuff_urls
pre_build_action_streams_event.twitter_favorites: $ActionStreams::ActionStreams::Fix::twitter_favorite_author
pre_build_action_streams_event.twitter_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name
pre_build_action_streams_event.typepad_comments: $ActionStreams::ActionStreams::Fix::typepad_comment_titles
pre_build_action_streams_event.wists_wists: $ActionStreams::ActionStreams::Fix::wists_thumb
+ filter_action_streams_event.nytimes_links: $ActionStreams::ActionStreams::Fix::nytimes_links_titles
object_types:
profileevent: ActionStreams::Event
as: ActionStreams::Event
as_ua_cache: ActionStreams::UserAgent::Cache
list_actions:
profileevent:
hide_all:
label: Hide All
order: 100
js: finishPluginActionAll
code: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events
continue_prompt_handler: >
sub { MT->translate('Are you sure you want to hide EVERY event in EVERY action stream?') }
show_all:
label: Show All
order: 200
js: finishPluginActionAll
code: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events
continue_prompt_handler: >
sub { MT->translate('Are you sure you want to show EVERY event in EVERY action stream?') }
delete:
label: Delete
order: 300
code: $core::MT::App::CMS::delete
continue_prompt_handler: >
sub { MT->translate('Deleted events that are still available from the remote service will be added back in the next scan. Only events that are no longer available from your profile will remain deleted. Are you sure you want to delete the selected event(s)?') }
tags:
function:
StreamAction: $ActionStreams::ActionStreams::Tags::stream_action
StreamActionID: $ActionStreams::ActionStreams::Tags::stream_action_id
StreamActionVar: $ActionStreams::ActionStreams::Tags::stream_action_var
StreamActionDate: $ActionStreams::ActionStreams::Tags::stream_action_date
StreamActionModifiedDate: $ActionStreams::ActionStreams::Tags::stream_action_modified_date
StreamActionTitle: $ActionStreams::ActionStreams::Tags::stream_action_title
StreamActionURL: $ActionStreams::ActionStreams::Tags::stream_action_url
StreamActionThumbnailURL: $ActionStreams::ActionStreams::Tags::stream_action_thumbnail_url
StreamActionVia: $ActionStreams::ActionStreams::Tags::stream_action_via
OtherProfileVar: $ActionStreams::ActionStreams::Tags::other_profile_var
block:
ActionStreams: $ActionStreams::ActionStreams::Tags::action_streams
StreamActionTags: $ActionStreams::ActionStreams::Tags::stream_action_tags
OtherProfiles: $ActionStreams::ActionStreams::Tags::other_profiles
ProfileServices: $ActionStreams::ActionStreams::Tags::profile_services
StreamActionRollup: $ActionStreams::ActionStreams::Tags::stream_action_rollup
tasks:
UpdateEvents:
frequency: 1800
label: Poll for new events
code: $ActionStreams::ActionStreams::Plugin::update_events
task_workers:
UpdateEvents:
label: Update Events
class: ActionStreams::Worker
widgets:
asotd:
label: Recent Actions
template: widget_recent.mtml
permission: post
singular: 1
set: sidebar
handler: $ActionStreams::ActionStreams::Plugin::widget_recent
condition: $ActionStreams::ActionStreams::Plugin::widget_blog_dashboard_only
template_sets:
streams:
label: Action Stream
base_path: 'blog_tmpl'
base_css: themes-base/blog.css
order: 100
templates:
index:
main_index:
label: Main Index (Recent Actions)
outfile: index.html
rebuild_me: 1
archive:
label: Action Archive
outfile: archive.html
rebuild_me: 1
styles:
label: Stylesheet
outfile: styles.css
rebuild_me: 1
feed_recent:
label: Feed - Recent Activity
outfile: atom.xml
rebuild_me: 1
module:
html_head:
label: HTML Head
banner_header:
label: Banner Header
banner_footer:
label: Banner Footer
sidebar:
label: Sidebar
widget:
elsewhere:
label: Find Authors Elsewhere
actions:
label: Recent Actions
widgetset:
2column_layout_sidebar:
label: 2-column layout - Sidebar
widgets:
- Find Authors Elsewhere
upgrade_functions:
enable_existing_streams:
version_limit: 9
updater:
type: author
label: Enabling default action streams for selected profiles...
code: $ActionStreams::ActionStreams::Upgrade::enable_existing_streams
reclass_actions:
version_limit: 15
handler: $ActionStreams::ActionStreams::Upgrade::reclass_actions
priority: 8
rename_action_metadata:
version_limit: 15
handler: $ActionStreams::ActionStreams::Upgrade::rename_action_metadata
priority: 9
upgrade_data:
reclass_actions:
twitter_tweets: twitter_statuses
pownce_notes: pownce_statuses
googlereader_shared: googlereader_links
rename_action_metadata:
- action_type: delicious_links
old: annotation
new: note
- action_type: googlereader_links
old: annotation
new: note
profile_services: services.yaml
action_streams: streams.yaml
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm
index 93a5abf..44aabec 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm
@@ -1,835 +1,839 @@
package ActionStreams::Event;
use strict;
use base qw( MT::Object MT::Taggable MT::Scorable );
our @EXPORT_OK = qw( classes_for_type );
use HTTP::Date qw( str2time );
use MT::Util qw( encode_html encode_url );
use MT::I18N;
use ActionStreams::Scraper;
our $hide_timeless = 0;
__PACKAGE__->install_properties({
column_defs => {
id => 'integer not null auto_increment',
identifier => 'string(200)',
author_id => 'integer not null',
visible => 'integer not null',
},
defaults => {
visible => 1,
},
indexes => {
identifier => 1,
author_id => 1,
created_on => 1,
created_by => 1,
},
class_type => 'event',
audit => 1,
meta => 1,
datasource => 'profileevent',
primary_key => 'id',
});
__PACKAGE__->install_meta({
columns => [ qw(
title
url
thumbnail
via
via_id
) ],
});
# Oracle does not like an identifier of more than 30 characters.
sub datasource {
my $class = shift;
my $r = MT->request;
my $ds = $r->cache('as_event_ds');
return $ds if $ds;
my $dss_oracle = qr/(db[id]::)?oracle/;
if ( my $type = MT->config('ObjectDriver') ) {
if ((lc $type) =~ m/^$dss_oracle$/) {
$ds = 'as';
}
}
$ds = $class->properties->{datasource}
unless $ds;
$r->cache('as_event_ds', $ds);
return $ds;
}
sub encode_field_for_html {
my $event = shift;
my ($field) = @_;
return encode_html( $event->$field() );
}
sub as_html {
my $event = shift;
my %params = @_;
my $stream = $event->registry_entry or return '';
# How many spaces are there in the form?
my $form = $params{form} || $stream->{html_form} || q{};
my @nums = $form =~ m{ \[ _ (\d+) \] }xmsg;
my $max = shift @nums;
for my $num (@nums) {
$max = $num if $max < $num;
}
# Do we need to supply the author name?
my @content = map { $event->encode_field_for_html($_) }
@{ $stream->{html_params} };
if ($max > scalar @content) {
my $name = defined $params{name} ? $params{name}
: $event->author->nickname
;
unshift @content, encode_html($name);
}
return MT->translate($form, @content);
}
sub update_events_loggily {
my $class = shift;
my %profile = @_;
# Keep this option out of band so we don't have to count on
# implementations of update_events() passing it through.
local $hide_timeless = delete $profile{hide_timeless} ? 1 : 0;
my $warn = $SIG{__WARN__} || sub { print STDERR $_[0] };
local $SIG{__WARN__} = sub {
my ($msg) = @_;
$msg =~ s{ \n \z }{}xms;
$msg = MT->component('ActionStreams')->translate(
'[_1] updating [_2] events for [_3]',
$msg, $profile{type}, $profile{author}->name,
);
$warn->("$msg\n");
};
eval {
$class->update_events(%profile);
};
if (my $err = $@) {
my $plugin = MT->component('ActionStreams');
my $err_msg = $plugin->translate("Error updating events for [_1]'s [_2] stream (type [_3] ident [_4]): [_5]",
$profile{author}->name, $class->properties->{class_type},
$profile{type}, $profile{ident}, $err);
MT->log($err_msg);
die $err; # re-throw so we can handle from job invocation
}
}
sub update_events {
my $class = shift;
my %profile = @_;
my $author = delete $profile{author};
my $stream = $class->registry_entry or return;
my $fetch = $stream->{fetch} || {};
local $profile{url} = $stream->{url};
die "Oops, no url?" if !$profile{url};
die "Oops, no ident?" if !$profile{ident};
require MT::I18N;
my $ident = encode_url(MT::I18N::encode_text($profile{ident}, undef, 'utf-8'));
$profile{url} =~ s/ {{ident}} / $ident /xmsge;
my $items;
if (my $xpath_params = $stream->{xpath}) {
$items = $class->fetch_xpath(
%$xpath_params,
%$fetch,
%profile,
);
}
elsif (my $atom_params = $stream->{atom}) {
my $get = {
created_on => 'published',
modified_on => 'updated',
title => 'title',
url => q{link[@rel='alternate']/@href},
via => q{link[@rel='alternate']/@href},
via_id => 'id',
identifier => 'id',
};
$atom_params = {} if !ref $atom_params;
@$get{keys %$atom_params} = values %$atom_params;
$items = $class->fetch_xpath(
foreach => '//entry',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $rss_params = $stream->{rss}) {
my $get = {
title => 'title',
url => 'link',
via => 'link',
created_on => 'pubDate',
thumbnail => 'media:thumbnail/@url',
via_id => 'guid',
identifier => 'guid',
};
$rss_params = {} if !ref $rss_params;
@$get{keys %$rss_params} = values %$rss_params;
$items = $class->fetch_xpath(
foreach => '//item',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $scraper_params = $stream->{scraper}) {
my ($foreach, $get) = @$scraper_params{qw( foreach get )};
my $scraper = scraper {
process $foreach, 'res[]' => scraper {
while (my ($field, $sel) = each %$get) {
process $sel->[0], $field => $sel->[1];
}
};
result 'res';
};
$items = $class->fetch_scraper(
scraper => $scraper,
%$fetch,
%profile,
);
}
return if !$items;
$class->build_results(
items => $items,
stream => $stream,
author => $author,
profile => \%profile,
);
}
sub registry_entry {
my $event = shift;
my ($type, $stream) = split /_/, $event->properties->{class_type}, 2;
my $reg = MT->instance->registry('action_streams') or return;
my $service = $reg->{$type} or return;
$service->{$stream};
}
sub author {
my $event = shift;
my $author_id = $event->author_id
or return;
return MT->instance->model('author')->lookup($author_id);
}
sub blog_id { 0 }
sub classes_for_type {
my $class = shift;
my ($type) = @_;
my $prevts = MT->instance->registry('action_streams');
my $prevt = $prevts->{$type};
return if !$prevt;
my @classes;
PACKAGE: while (my ($stream_id, $stream) = each %$prevt) {
next if 'HASH' ne ref $stream;
next if !$stream->{class} && !$stream->{url};
# This check intentionally fails a lot, so ignore any DIE handler we
# might have.
my $has_props = sub {
my $pkg = shift;
return eval { local $SIG{__DIE__}; $pkg->properties };
};
my $pkg;
if ($pkg = $stream->{class}) {
$pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms;
if (!$has_props->($pkg)) {
if (!eval "require $pkg; 1") {
my $error = $@ || q{};
my $pl = MT->component('ActionStreams');
MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]',
$pkg, $type, $stream_id, $error));
next PACKAGE;
}
}
}
else {
$pkg = join q{::}, $class, 'Auto', ucfirst $type,
ucfirst $stream_id;
if (!$has_props->($pkg)) {
eval "package $pkg; use base qw( $class ); 1" or next PACKAGE;
my $class_type = join q{_}, $type, $stream_id;
$pkg->install_properties({ class_type => $class_type });
$pkg->install_meta({ columns => $stream->{fields} })
if $stream->{fields};
}
}
push @classes, $pkg;
}
return @classes;
}
my $ua;
sub ua {
my $class = shift;
my %params = @_;
$ua ||= MT->new_ua({
paranoid => 1,
timeout => 10,
});
$ua->max_size(250_000) if $ua->can('max_size');
$ua->agent($params{default_useragent} ? $ua->_agent
: "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version);
return $ua if $class->class_type eq 'event';
return $ua if $params{unconditional};
require ActionStreams::UserAgent::Adapter;
my $adapter = ActionStreams::UserAgent::Adapter->new(
ua => $ua,
action_type => $class->class_type,
die_on_not_modified => $params{die_on_not_modified} || 0,
);
return $adapter;
}
sub set_values {
my $event = shift;
my ($values) = @_;
for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) {
my $meta_val = delete $values->{$meta_col};
$event->$meta_col($meta_val) if defined $meta_val;
}
$event->SUPER::set_values($values);
}
sub fetch_xpath {
my $class = shift;
my %params = @_;
my $url = $params{url} || '';
if (!$url) {
MT->log(
MT->component('ActionStreams')->translate(
"No URL to fetch for [_1] results", $class));
return;
}
my $ua = $class->ua(%params);
my $res = $ua->get($url);
if (!$res->is_success()) {
MT->log(
MT->component('ActionStreams')->translate(
"Could not fetch [_1]: [_2]", $url, $res->status_line()))
if $res->code != 304;
return;
}
# Do not continue if contents is incomplete.
if (my $abort = $res->{_headers}{'client-aborted'}) {
MT->log(
MT->component('ActionStreams')->translate(
'Aborted fetching [_1]: [_2]', $url, $abort));
return;
}
# Strip leading whitespace, since the parser doesn't like it.
# TODO: confirm we got xml?
my $content = $res->content;
$content =~ s{ \A \s+ }{}xms;
require XML::XPath;
my $x = XML::XPath->new( xml => $content );
my @items;
ITEM: for my $item ($x->findnodes($params{foreach})) {
my %item_data;
VALUE: while (my ($key, $val) = each %{ $params{get} }) {
next VALUE if !$val;
if ($key eq 'tags') {
my @outvals = $item->findnodes($val)
or next VALUE;
$item_data{$key} = [ map { MT::I18N::utf8_off( $_->getNodeValue ) } @outvals ];
}
else {
my $outval = $item->findvalue($val)
or next VALUE;
$outval = MT::I18N::utf8_off("$outval");
if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) {
# try both RFC 822/1123 and ISO 8601 formats
$outval = MT::Util::epoch2ts(undef, str2time($outval))
|| MT::Util::iso2ts(undef, $outval);
}
$item_data{$key} = $outval if $outval;
}
}
push @items, \%item_data;
}
return \@items;
}
sub build_results {
my $class = shift;
my %params = @_;
my ($author, $items, $profile, $stream) =
@params{qw( author items profile stream )};
my $mt = MT->app;
ITEM: for my $item (@$items) {
my $event;
my $identifier = delete $item->{identifier};
if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) {
$identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} };
}
if (defined $identifier) {
$identifier = "$identifier";
($event) = $class->search({
author_id => $author->id,
identifier => $identifier,
});
}
$event ||= $class->new;
+ $mt->run_callbacks('filter_action_streams_event.'
+ . $class->class_type, $mt, $item, $event, $author, $profile)
+ or return;
+
$mt->run_callbacks('pre_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
my $tags = delete $item->{tags};
$event->set_values({
author_id => $author->id,
identifier => $identifier,
%$item,
});
$event->tags(@$tags) if $tags;
if ($hide_timeless && !$event->created_on) {
$event->visible(0);
}
$mt->run_callbacks('post_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
$event->save() or MT->log($event->errstr);
}
1;
}
sub save {
my $event = shift;
# Built-in audit field setting will set a local time, so do it ourselves.
if (!$event->created_on) {
my $ts = MT::Util::epoch2ts(undef, time);
$event->created_on($ts);
$event->modified_on($ts);
}
return $event->SUPER::save(@_);
}
sub fetch_scraper {
my $class = shift;
my %params = @_;
my ($url, $scraper) = @params{qw( url scraper )};
$scraper->user_agent( $class->ua( %params, die_on_not_modified => 1 ) );
my $uri_obj = URI->new($url);
my $items = eval { $scraper->scrape($uri_obj) };
# Ignore Web::Scraper errors due to 304 Not Modified responses.
if (!$items && $@ && !UNIVERSAL::isa($@, 'ActionStreams::UserAgent::NotModified')) {
die; # rethrow
}
# we're only being used for our scraper.
return if !$items;
return $items if !ref $items;
return $items if 'ARRAY' ne ref $items;
ITEM: for my $item (@$items) {
next ITEM if !ref $item || ref $item ne 'HASH';
for my $field (keys %$item) {
if ($field eq 'tags') {
$item->{$field} = [ map { MT::I18N::utf8_off( "$_" ) } @{ $item->{$field} } ];
}
else {
$item->{$field} = MT::I18N::utf8_off( q{} . $item->{$field} );
}
}
}
return $items;
}
sub backup_terms_args {
my $class = shift;
my ($blog_ids) = @_;
return { terms => { 'class' => '*' }, args => undef };
}
1;
__END__
=head1 NAME
ActionStreams::Event - an Action Streams stream definition
=head1 SYNOPSIS
# in plugin's config.yaml
profile_services:
example:
streamid:
name: Dice Example
description: A simple die rolling Perl stream example.
html_form: [_1] rolled a [_2]!
html_params:
- title
class: My::Stream
# in plugin's lib/My/Stream.pm
package My::Stream;
use base qw( ActionStreams::Event );
__PACKAGE__->install_properties({
class_type => 'example_streamid',
});
sub update_events {
my $class = shift;
my %profile = @_;
# trivial example: save a random number
my $die_roll = int rand 20;
my %item = (
title => $die_roll,
identifier => $die_roll,
);
return $class->build_results(
author => $profile{author},
items => [ \%item ],
);
}
1;
=head1 DESCRIPTION
I<ActionStreams::Event> provides the basic implementation of an action stream.
Stream definitions are engines for turning web resources into I<actions> (also
called I<events>). This base class produces actions based on generic stream
recipes defined in the MT registry, as well as providing the internal machinery
for you to implement your own streams in Perl code.
=head1 METHODS TO IMPLEMENT
These are the methods one commonly implements (overrides) when implementing a
stream subclass.
=head2 C<$class-E<gt>update_events(%profile)>
Fetches the web resource specified by the profile parameters, collects data
from it into actions, and saves the action records for use later. Required
members of C<%profile> are:
=over 4
=item * C<author>
The C<MT::Author> instance for whom events should be collected.
=item * C<ident>
The author's identifier on the given service.
=back
Other information about the stream, such as the URL pattern into which the
C<ident> parameter can be replaced, is available through the
C<$class-E<gt>registry_entry()> method.
=head2 C<$self-E<gt>as_html(%params)>
Returns the HTML version of the action, suitable for display to readers.
The default implementation uses the stream's registry definition to construct
the action: the author's name and the action's values as named in
C<html_params> are replaced into the stream's C<html_form> setting. You need
override it only if you have more complex requirements.
Optional members of C<%params> are:
=over 4
=item * C<form>
The formatting string to use. If not given, the C<html_form> specified for
this stream in the registry is used.
=item * C<name>
The text to use as the author's name if C<as_html> needs to provide it
automatically in the result. Author names are provided if there are more
tokens in C<html_form> than there are fields specified in C<html_params>.
If not given, the event's author's nickname is provided. Note that a defined
but empty name (such as C<q{}>) I<will> be used; in this case, the name will
appear to be omitted from the result of the C<as_html> call.
=back
=head1 AVAILABLE METHODS
These are the methods provided by I<ActionStreams::Event> to perform common
tasks. Call them from your overridden methods.
=head2 C<$self-E<gt>set_values(\%values)>
Stores the data given in C<%values> as members of this event.
=head2 C<$class-E<gt>fetch_xpath(%param)>
Returns the items discovered by scanning a web resource by the given XPath
recipe. Required members of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be a
valid XML document.
=item * C<foreach>
The XPath selector with which to select the individual events from the
resource.
=item * C<get>
A hashref containing the XPath selectors with which to collect individual data
for each item, keyed on the names of the fields to contain the data.
=back
C<%param> may also contain additional arguments for the C<ua()> method.
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
=head2 C<$class-E<gt>fetch_scraper(%param)>
Returns the items discovered by scanning by the given recipe. Required members
of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be an
HTML or XML document suitable for analysis by the C<Web::Scraper> module.
=item * C<scraper>
The C<Web::Scraper> scraper with which to extract item data from the specified
web resource. See L<Web::Scraper> for information on how to construct a
scraper.
=back
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
See also the below I<NOTE ON WEB::SCRAPER>.
=head2 C<$class-E<gt>build_results(%param)>
Converts a set of collected items into saved action records of type C<$class>.
The required members of C<%param> are:
=over 4
=item * C<author>
The C<MT::Author> instance whose action the items represent.
=item * C<items>
An arrayref of items to save as actions. Each item is a hashref containing the
action data, keyed on the names of the fields containing the data.
=back
Optional parameters are:
=over 4
=item * C<profile>
An arrayref describing the data for the author's profile for the associated
stream, such as is returned by the C<MT::Author::other_profile()> method
supplied by the Action Streams plugin.
The profile member is not used directly by C<build_results()>; they are only
passed to callbacks.
=item * C<stream>
A hashref containing the settings from the registry about the stream, such as
is returned from the C<registry_entry()> method.
=back
=head2 C<$class-E<gt>ua(%param)>
Returns the common HTTP user-agent, an instance of C<LWP::UserAgent>, with
which you can fetch web resources.
The resulting user agent may provide automatic conditional HTTP support when
you call its C<get> method. A UA with conditional HTTP support enabled will
store the values of the conditional HTTP headers (C<ETag> and
C<Last-Modified>) received in responses as C<ActionStreams::UserAgent::Cache>
objects and, on subsequent requests of the same URL, automatically supply the
header values. When the remote HTTP server reports that such a resource has
not changed, the C<HTTP::Response> will be a C<304 Not Modified> response; the
user agent does not itself store and supply the resource content. Using other
C<LWP::UserAgent> methods such as C<post> or C<request> will I<not> trigger
automatic conditional HTTP support.
No arguments are required; possible optional parameters are:
=over 4
=item * C<default_useragent>
If set, the returned HTTP user-agent will use C<LWP::UserAgent>'s default
identifier in the HTTP C<User-Agent> header. If omitted, the UA will use the
Action Streams identifier of C<mt-actionstreams-lwp/I<version>>.
=item * C<unconditional>
If set, the return HTTP user-agent will I<not> automatically use conditional
HTTP to avoid requesting old content from compliant servers. That is, if
omitted, the UA I<will> automatically use conditional HTTP when you call its
C<get> method.
=item * C<die_on_not_modified>
If set, when the response of the HTTP user-agent's C<get> method is a
conditional HTTP C<304 Not Modified> response, throw an exception instead of
returning the response. (Use this option to return control to yourself when
passing UAs with conditional HTTP support to other Perl modules that don't
expect 304 responses.)
The thrown exception is an C<ActionStreams::UserAgent::NotModified> exception.
=back
=head2 C<$self-E<gt>author()>
Returns the C<MT::Author> instance associated with this event, if its
C<author_id> field has been set.
=head2 C<$class-E<gt>install_properties(\%properties)>
I<TODO>
=head2 C<$class-E<gt>install_meta(\%properties)>
I<TODO>
=head2 C<$class-E<gt>registry_entry()>
Returns the registry data for the stream represented by C<$class>.
=head2 C<$class-E<gt>classes_for_type($service_id)>
Given a profile service ID (that is, a key from the C<profile_services> section
of the registry), returns a list of stream classes for scanning that service's
streams.
=head2 C<$class-E<gt>backup_terms_args($blog_ids)>
Used in backup. Backup function calls the method to generate $terms and
$args for the class to load objects. ActionStream::Event does not have
blog_id and does use class_column, the nature the class has to tell
backup function to properly load all the target objects of the class
to be backed up.
See I<MT::BackupRestore> for more detail.
=head1 NOTE ON WEB::SCRAPER
The C<Web::Scraper> module is powerful, but it has complex dependencies. While
its pure Perl requirements are bundled with the Action Streams plugin, it also
requires a compiled XML module. Also, because of how its syntax works, you must
directly C<use> the module in your own code, contrary to the Movable Type idiom
of using C<require> so that modules are loaded only when they are sure to be
used.
If you attempt load C<Web::Scraper> in the normal way, but C<Web::Scraper> is
unable to load due to its missing requirement, whenever the plugin attempts to
load your scraper, the entire plugin will fail to load.
Therefore the C<ActionStreams::Scraper> wrapper module is provided for you. If
you need to load C<Web::Scraper> so as to make a scraper to pass
C<ActionStreams::Event::fetch_scraper()> method, instead write in your module:
use ActionStreams::Scraper;
This module provides the C<Web::Scraper> interface, but if C<Web::Scraper> is
unable to load, the error will be thrown when your module tries to I<use> it,
rather than when you I<load> it. That is, if C<Web::Scraper> can't load, no
errors will be thrown to end users until they try to use your stream.
=head1 AUTHOR
Mark Paschal E<lt>[email protected]<gt>
=cut
diff --git a/plugins/ActionStreams/lib/ActionStreams/Fix.pm b/plugins/ActionStreams/lib/ActionStreams/Fix.pm
index 8618367..4a88ed8 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Fix.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Fix.pm
@@ -1,141 +1,146 @@
package ActionStreams::Fix;
use strict;
use warnings;
use ActionStreams::Scraper;
sub _twitter_add_tags_to_item {
my ($item) = @_;
if (my @tags = $item->{title} =~ m{
(?: \A | \s ) # BOT or whitespace
\# # hash
(\w\S*\w) # tag
(?<! 's ) # but don't end with 's
}xmsg) {
$item->{tags} = \@tags;
}
}
sub twitter_tweet_name {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the Twitter username from the front of the tweet.
my $ident = $profile->{ident};
$item->{title} =~ s{ \A \s* \Q$ident\E : \s* }{}xmsi;
_twitter_add_tags_to_item($item);
}
sub twitter_favorite_author {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the Twitter username from the front of the tweet.
if ($item->{title} =~ s{ \A \s* ([^\s:]+) : \s* }{}xms) {
$item->{tweet_author} = $1;
}
_twitter_add_tags_to_item($item);
}
sub flickr_photo_thumbnail {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Extract just the URL, and use the _t size thumbnail, not the _m size image.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ (http://farm[^\.]+\.static\.flickr\.com .*? _m.jpg) }xms) {
$thumb = $1;
$thumb =~ s{ _m.jpg \z }{_t.jpg}xms;
$item->{thumbnail} = $thumb;
}
}
sub iminta_link_title {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the username for when we add it back in later.
$item->{title} =~ s{ (?: \s* :: [^:]+ ){2} \z }{}xms;
}
sub iusethis_event_title {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the username for when we add it back in later.
$item->{title} =~ s{ \A \w+ \s* }{}xms;
}
sub netflix_recent_prefix_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the 'Shipped:' or 'Received:' prefix.
$item->{title} =~ s{ \A [^:]*: \s* }{}xms;
# Extract thumbnail from description.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m/ <img src="([^"]+)"} /xms) {
$item->{thumbnail} = $1;
}
}
sub netflix_queue_prefix_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the item number.
$item->{title} =~ s{ \A \d+ [\W\S] \s* }{}xms;
# Extract thumbnail from description.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m/ <img src="([^"]+)"} /xms) {
$item->{thumbnail} = $1;
}
}
+sub nytimes_links_titles {
+ my ($cb, $app, $item, $event, $author, $profile) = @_;
+ return $item->{title} =~ s{ \A [^:]* recommended [^:]* : \s* }{}xms ? 1 : 0;
+}
+
sub p0pulist_stuff_urls {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{url} =~ s{ \A / }{http://p0pulist.com/}xms;
}
sub kongregate_achievement_title_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Remove the parenthetical from the end of the title.
$item->{title} =~ s{ \( [^)]* \) \z }{}xms;
# Pick the actual achievement badge out of the inline CSS.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ background-image: \s* url\( ([^)]+) }xms) {
$item->{thumbnail} = $1;
}
}
sub wists_thumb {
my ($cb, $app, $item, $event, $author, $profile) = @_;
# Grab the wists thumbnail out.
my $thumb = delete $item->{thumbnail};
if ($thumb =~ m{ (http://cache.wists.com/thumbnails/ [^"]+ ) }xms) {
$item->{thumbnail} = $1;
}
}
sub gametap_score_stuff {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{score} =~ s{ \D }{}xmsg;
$item->{url} = q{} . $item->{url};
$item->{url} =~ s{ \A / }{http://www.gametap.com/}xms;
}
sub typepad_comment_titles {
my ($cb, $app, $item, $event, $author, $profile) = @_;
$item->{title} =~ s{ \A .*? ' }{}xms;
$item->{title} =~ s{ ' \z }{}xms;
}
sub magnolia_link_notes {
my ($cb, $app, $item, $event, $author, $profile) = @_;
my $scraper = scraper {
process '//p[position()=2]', note => 'TEXT';
};
my $result = $scraper->scrape(\$item->{note});
if ($result->{note}) {
$item->{note} = $result->{note};
}
else {
delete $item->{note};
}
}
1;
diff --git a/plugins/ActionStreams/services.yaml b/plugins/ActionStreams/services.yaml
index da5eb8a..82792ab 100644
--- a/plugins/ActionStreams/services.yaml
+++ b/plugins/ActionStreams/services.yaml
@@ -1,335 +1,341 @@
oneup:
name: 1up.com
url: http://{{ident}}.1up.com/
fortythreethings:
name: 43Things
url: http://www.43things.com/person/{{ident}}/
aim:
name: AIM
url: aim:goim?screenname={{ident}}
ident_label: Screen name
service_type: contact
backtype:
name: backtype
url: http://www.backtype.com/{{ident}}
service_type: comments
bebo:
name: Bebo
url: http://www.bebo.com/Profile.jsp?MemberId={{ident}}
service_type: network
catster:
name: Catster
url: http://www.catster.com/cats/{{ident}}
colourlovers:
name: COLOURlovers
url: http://www.colourlovers.com/lover/{{ident}}
corkd:
name: 'Cork''d'
url: http://www.corkd.com/people/{{ident}}
delicious:
name: Delicious
url: http://delicious.com/{{ident}}/
service_type: links
destructoid:
name: Destructoid
url: http://www.destructoid.com/elephant/profile.phtml?un={{ident}}
digg:
name: Digg
url: http://digg.com/users/{{ident}}/
service_type: links
dodgeball:
name: Dodgeball
url: http://www.dodgeball.com/user?uid={{ident}}
deprecated: 1
dogster:
name: Dogster
url: http://www.dogster.com/dogs/{{ident}}
dopplr:
name: Dopplr
url: http://www.dopplr.com/traveller/{{ident}}/
facebook:
name: Facebook
url: http://www.facebook.com/profile.php?id={{ident}}
ident_label: User ID
ident_example: 12345
service_type: network
ident_hint: You can find your Facebook user ID in your profile URL. For example: http://www.facebook.com/profile.php?id=12345
ffffound:
name: FFFFOUND!
url: http://ffffound.com/home/{{ident}}/found/
service_type: photos
flickr:
name: Flickr
url: http://flickr.com/photos/{{ident}}/
ident_example: 36381329@N00
service_type: photos
ident_hint: Enter your Flickr user ID that has a "@" in it. Your Flickr user ID is NOT the username in the URL of your photo stream.
friendfeed:
name: FriendFeed
url: http://friendfeed.com/{{ident}}
ident_example: JoeUsername
gametap:
name: Gametap
url: http://www.gametap.com/profile/show/profile.do?sn={{ident}}
goodreads:
name: Goodreads
url: http://www.goodreads.com/user/show/{{ident}}
ident_label: User ID
ident_example: 12345
ident_hint: You can find your Goodreads user ID in your profile URL. For example: http://www.goodreads.com/user/show/12345
googlereader:
name: Google Reader
url: http://www.google.com/reader/shared/{{ident}}
ident_label: Sharing ID
ident_example: http://www.google.com/reader/shared/16793324975410272738
service_type: links
hi5:
name: Hi5
url: http://hi5.com/friend/profile/displayProfile.do?userid={{ident}}
service_type: network
iconbuffet:
name: IconBuffet
url: http://www.iconbuffet.com/people/{{ident}}
icq:
name: ICQ
url: http://www.icq.com/people/about_me.php?uin={{ident}}
ident_label: UIN
ident_example: 12345
service_type: contact
identica:
name: Identi.ca
url: http://identi.ca/{{ident}}
service_type: status
iminta:
name: Iminta
url: http://iminta.com/people/{{ident}}
istockphoto:
name: iStockphoto
url: http://www.istockphoto.com/user_view.php?id={{ident}}
ident_label: User ID
ident_example: 123456
ident_hint: You can find your iStockphoto user ID in your profile URL. For example: http://www.istockphoto.com/user_view.php?id=123456
iusethis:
name: IUseThis
url: http://osx.iusethis.com/user/{{ident}}
iwatchthis:
name: iwatchthis
url: http://iwatchthis.com/{{ident}}
jabber:
name: Jabber
url: jabber://{{ident}}
ident_label: Jabber ID
ident_example: [email protected]
service_type: contact
jaiku:
name: Jaiku
url: http://{{ident}}.jaiku.com/
ident_suffix: .jaiku.com
service_type: status
kongregate:
name: Kongregate
url: http://www.kongregate.com/accounts/{{ident}}
lastfm:
name: Last.fm
url: http://www.last.fm/user/{{ident}}/
ident_example: JoeUsername
linkedin:
name: LinkedIn
url: http://www.linkedin.com/in/{{ident}}
ident_example: MelodyNelson
ident_prefix: http://www.linkedin.com/in/
ident_label: Profile URL
service_type: network
livejournal:
name: LiveJournal
url: http://{{ident}}.livejournal.com/
ident_suffix: .livejournal.com
service_type: blog
magnolia:
name: Ma.gnolia
url: http://ma.gnolia.com/people/{{ident}}
service_type: links
deprecated: 1
mog:
name: MOG
url: http://mog.com/{{ident}}
msn:
name: 'MSN Messenger'
url: msnim:chat?contact={{ident}}
service_type: contact
multiply:
name: Multiply
url: http://{{ident}}.multiply.com/
myspace:
name: MySpace
url: http://www.myspace.com/{{ident}}
ident_label: User ID
ident_prefix: http://www.myspace.com/
service_type: network
netflix:
name: Netflix
url: http://rss.netflix.com/QueueRSS?id={{ident}}
ident_label: Netflix RSS ID
ident_example: P0000006746939516625352861892808956
ident_hint: To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.
netvibes:
name: Netvibes
url: http://www.netvibes.com/{{ident}}
service_type: links
newsvine:
name: Newsvine
url: http://{{ident}}.newsvine.com/
ning:
name: Ning
url: http://{{ident}}.ning.com/
service_type: network
ident_suffix: .ning.com/
ident_prefix: http://
ident_label: Social Network URL
+nytimes:
+ name: New York Times (TimesPeople)
+ url: http://timespeople.nytimes.com/view/user/{{ident}}/activities.html
+ service_type: links
+ ident_label: Activity URL
+ ident_example: http://timespeople.nytimes.com/view/user/57963079/activities.html
ohloh:
name: Ohloh
url: http://ohloh.net/accounts/{{ident}}
orkut:
name: Orkut
url: http://www.orkut.com/Profile.aspx?uid={{ident}}
ident_label: User ID
ident_example: 1234567890123456789
service_type: network
ident_hint: You can find your Orkut user ID in your profile URL. For example: http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789
pandora:
name: Pandora
url: http://pandora.com/people/{{ident}}
ident_example: JoeUsername
picasaweb:
name: Picasa Web Albums
url: http://picasaweb.google.com/{{ident}}
service_type: photos
p0pulist:
name: p0p
url: http://p0p.com/list/hot_list/{{ident}}
ident_label: User ID
ident_example: 12345
ident_hint: You can find your p0p user ID in your Hot List URL. For example: http://p0pulist.com/list/hot_list/12345
pownce:
name: Pownce
url: http://pownce.com/{{ident}}/
service_type: status
deprecated: 1
reddit:
name: Reddit
url: http://reddit.com/user/{{ident}}/
service_type: links
skype:
name: Skype
url: callto://{{ident}}
slideshare:
name: SlideShare
url: http://www.slideshare.net/{{ident}}
smugmug:
name: Smugmug
url: http://{{ident}}.smugmug.com/
service_type: photos
sonicliving:
name: SonicLiving
url: http://www.sonicliving.com/user/{{ident}}/
ident_label: User ID
ident_example: 12345
ident_hint: You can find your SonicLiving user ID in your Share & Subscribe URL. For example: http://sonicliving.com/user/12345/feeds
steam:
name: Steam
url: http://steamcommunity.com/id/{{ident}}
stumbleupon:
name: StumbleUpon
url: http://{{ident}}.stumbleupon.com/
tabblo:
name: Tabblo
url: http://www.tabblo.com/studio/person/{{ident}}/
technorati:
name: Technorati
url: http://technorati.com/people/technorati/{{ident}}
tribe:
name: Tribe
url: http://people.tribe.net/{{ident}}
service_type: network
ident_label: User ID
ident_example: dcdc61ed-696a-40b5-80c1-e9a9809a726a
ident_hint: You can find your Tribe user ID in your profile URL. For example: http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a
tumblr:
name: Tumblr
url: http://{{ident}}.tumblr.com
icon: images/services/tumblr.gif
ident_label: URL
ident_suffix: .tumblr.com
service_type: blog
twitter:
name: Twitter
url: http://twitter.com/{{ident}}
service_type: status
typepad:
name: TypePad
ident_prefix: http://profile.typepad.com/
ident_label: Profile URL
url: http://profile.typepad.com/{{ident}}
uncrate:
name: Uncrate
url: http://www.uncrate.com/stuff/{{ident}}
upcoming:
name: Upcoming
url: http://upcoming.yahoo.com/user/{{ident}}
ident_label: User ID
ident_example: 12345
viddler:
name: Viddler
url: http://www.viddler.com/explore/{{ident}}
service_type: video
vimeo:
name: Vimeo
url: http://www.vimeo.com/{{ident}}
service_type: video
virb:
name: Virb
url: http://www.virb.com/{{ident}}
service_type: network
ident_label: User ID
ident_example: 2756504321310091
ident_hint: You can find your Virb user ID in your home URL. For example: http://www.virb.com/backend/2756504321310091/your_home
vox:
name: Vox
url: http://{{ident}}.vox.com/
ident_label: Vox name
ident_suffix: .vox.com
service_type: blog
website:
name: Website
url: '{{ident}}'
ident_label: URL
ident_example: http://www.example.com/
ident_exact: 1
can_many: 1
service_type: blog
wists:
name: Wists
url: http://www.wists.com/{{ident}}
xboxlive:
name: 'Xbox Live'
url: http://live.xbox.com/member/{{ident}}
ident_label: Gamertag
yahoo:
name: 'Yahoo! Messenger'
url: http://edit.yahoo.com/config/send_webmesg?.target={{ident}}
service_type: contact
yelp:
name: Yelp
url: http://www.yelp.com/user_details?userid={{ident}}
ident_label: User ID
ident_example: 4BXqlLKW8oP0RBCW1FvaIg
youtube:
name: YouTube
url: http://www.youtube.com/user/{{ident}}
service_type: video
zooomr:
name: Zooomr
url: http://www.zooomr.com/photos/{{ident}}
ident_example: 1234567@Z01
service_type: photos
diff --git a/plugins/ActionStreams/streams.yaml b/plugins/ActionStreams/streams.yaml
index 00ceb41..61cc3e6 100644
--- a/plugins/ActionStreams/streams.yaml
+++ b/plugins/ActionStreams/streams.yaml
@@ -44,980 +44,990 @@ colourlovers:
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/palettes/new?lover={{ident}}'
xpath:
foreach: //palette
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
patterns:
name: Patterns
description: Patterns you saved
fields:
- queue
html_form: '[_1] saved the pattern <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/patterns/new?lover={{ident}}'
xpath:
foreach: //pattern
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
favpalettes:
name: Favorite Palettes
description: Palettes you saved as favorites
fields:
- queue
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite palette'
html_params:
- url
- title
url: 'http://www.colourlovers.com/rss/lover/{{ident}}/palettes/favorites'
rss: 1
corkd:
reviews:
name: Reviews
description: Your wine reviews
fields:
- review
html_form: '[_1] reviewed <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/journal/{{ident}}'
rss: 1
cellar:
name: Cellar
description: Wines you own
fields:
- wine
html_form: '[_1] owns <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/cellar/{{ident}}'
rss: 1
list:
name: Shopping List
description: Wines you want to buy
fields:
- wine
html_form: '[_1] wants <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/shoppinglist/{{ident}}'
rss: 1
delicious:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.delicious.com/v2/rss/{{ident}}?plain'
identifier: url
rss:
note: description
tags: category/child::text()
digg:
links:
name: Dugg
description: Links you dugg
html_form: '[_1] dugg the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://digg.com/users/{{ident}}/history/diggs.rss'
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
submitted:
name: Submissions
description: Links you submitted
html_form: '[_1] submitted the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://digg.com/users/{{ident}}/history/submissions.rss
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
ffffound:
favorites:
name: Found
description: Photos you found
html_form: '[_1] ffffound <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://ffffound.com/home/{{ident}}/found/feed
rss: 1
flickr:
favorites:
name: Favorites
description: Photos you marked as favorites
fields:
- by
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite photo'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_faves.gne?nsid={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
by: author/name
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_public.gne?id={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
friendfeed:
likes:
name: Likes
description: Things from your friends that you "like"
html_form: '[_1] likes <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://friendfeed.com/{{ident}}/likes?format=atom'
atom:
url: link/@href
gametap:
scores:
name: Leaderboard scores
description: Your high scores in games with leaderboards
fields:
- score
html_form: '[_1] scored <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- score
- url
- title
url: http://www.gametap.com/profile/leaderboards.do?sn={{ident}}
identifier: title,score
scraper:
foreach: 'div.buddy-leaderboards div.tr'
get:
url:
- 'div.name a'
- '@href'
title:
- 'div.name strong'
- TEXT
score:
- 'div.name div'
- TEXT
goodreads:
toread:
name: To read
description: Books on your "to-read" shelf
fields:
- by
html_form: '[_1] saved <a href="[_2]"><i>[_3]</i> by [_4]</a> to read'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=to-read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
reading:
name: Reading
description: Books on your "currently-reading" shelf
fields:
- by
html_form: '[_1] started reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=currently-reading'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
read:
name: Read
description: Books on your "read" shelf
fields:
- by
html_form: '[_1] finished reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
googlereader:
links:
name: Shared
description: Your shared items
html_form: '[_1] shared <a href="[_2]">[_3]</a> from <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- source_url
- source_title
class: GoogleReader
iconbuffet:
icons:
name: Deliveries
description: Icon sets you were delivered
html_form: '[_1] received the icon set <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.iconbuffet.com/people/{{ident}};received_packages'
identifier: url
scraper:
foreach: 'div#icons div.preview-sm'
get:
title:
- a span
- TEXT
url:
- a
- '@href'
identica:
statuses:
name: Notices
description: Notices you posted
html_form: '[_1] <a href="[_2]">said</a>, “[_3]”'
html_params:
- url
- title
url: 'http://identi.ca/{{ident}}/rss'
rss:
created_on: dc:date
class: Identica
iminta:
links:
name: Intas
description: Links you saved
html_form: '[_1] is inta <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://iminta.com/people/{{ident}}/rss.xml?inta_source_id=11'
rss: 1
istockphoto:
photos:
name: Photos
description: Photos you posted that were approved
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.istockphoto.com/webservices/feeds/?feedFormat=IStockAtom_1_0&feedName=istockfeed.image.newestUploads&feedParams=UserID={{ident}}'
identifier: url
atom:
thumbnail: content/div/a/img/@src
iusethis:
events:
name: Recent events
description: Events from your recent events feed
html_form: '[_1] <a href="[_2]">[_3]</a>'
html_params:
- url
- title
rss: 1
url: 'http://osx.iusethis.com/user/feed.rss/{{ident}}?following=0'
osxapps:
name: Apps you use
description: The applications you saved as ones you use
fields:
- favorite
html_form: '[_1] started using <a href="[_2]">[_3]</a>[quant,_4, (and loves it),,]'
html_params:
- url
- title
- favorite
url: 'http://osx.iusethis.com/user/{{ident}}'
iwatchthis:
favorites:
name: Favorites
description: Videos you saved as watched
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video'
html_params:
- url
- title
url: 'http://iwatchthis.com/rss/{{ident}}'
rss: 1
jaiku:
jaikus:
name: Jaikus
description: Jaikus you posted
html_form: '[_1] <a href="[_2]">jaiku''d</a>, "[_3]"'
html_params:
- url
- title
url: 'http://{{ident}}.jaiku.com/feed/atom'
atom: 1
kongregate:
favorites:
name: Favorites
description: Games you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite game'
html_params:
- url
- title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url
scraper:
foreach: #favorites dl
get:
url:
- dd a
- '@href'
title:
- dd a
- TEXT
thumbnail:
- dt img
- '@src'
achievements:
name: Achievements
description: Achievements you won
fields:
- game_title
html_form: '[_1] won the <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- title
- url
- game_title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url,title
scraper:
foreach: #achievements .badge_details
get:
url:
- dt.badge_img a
- '@href'
thumbnail:
- dt.badge_img img
- '@style'
title:
- dd.badge_name
- TEXT
game_title:
- a.badge_game
- TEXT
lastfm:
tracks:
name: Tracks
description: Songs you recently listened to (High spam potential!)
html_form: '[_1] heard <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/recenttracks.rss'
rss: 1
lovedtracks:
name: Loved Tracks
description: Songs you marked as "loved"
fields:
- artist
html_form: '[_1] loved <a href="[_2]">[_3]</a> by [_4]'
html_params:
- url
- title
- artist
url: 'http://pipes.yahoo.com/pipes/pipe.run?_id=4smlkvMW3RGPpBPfTqoASA&_render=rss&lastFM_UserName={{ident}}'
identifier: url
rss:
artist: description
journalentries:
name: Journal Entries
description: Your recent journal entries
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/journals.rss'
rss: 1
events:
name: Events
description: The events you said you'll be attending
html_form: '[_1] is attending <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/events.rss'
rss: 1
livejournal:
posts:
name: Posts
description: Your public posts to your journal
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://users.livejournal.com/{{ident}}/data/atom'
atom: 1
magnolia:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ma.gnolia.com/atom/full/people/{{ident}}'
identifier: url
atom:
tags: "category[@scheme='http://ma.gnolia.com/tags']/@term"
note: content
netflix:
queue:
name: Queue
description: Movies you added to your rental queue
fields:
- queue
html_form: '[_1] queued <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/QueueRSS?id={{ident}}'
rss:
thumbnail: description
recent:
name: Recent Movies
description: Recent Rental Activity
fields:
- recent
html_form: '[_1] is watching <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/TrackingRSS?id={{ident}}'
rss:
thumbnail: description
netvibes:
links:
name: Links
description: Links you saved
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www2.netvibes.com/rest/account/{{ident}}/timeline?format=atom'
atom: 1
+nytimes:
+ links:
+ name: Recommendations
+ description: Recommendations in your TimesPeople activities
+ html_form: '[_1] recommended <a href="[_2]">[_3]</a>'
+ html_params:
+ - url
+ - title
+ url: 'http://timespeople.nytimes.com/view/user/{{ident}}/rss.xml'
+ rss: 1
ohloh:
kudos:
name: Kudos
description: Kudos you have received
html_form: '[_1] received kudos from <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.ohloh.net/accounts/{{ident}}/kudos'
identifier: url
scraper:
foreach: 'div.received_kudo'
get:
url:
- a
- '@href'
title:
- a
- TEXT
pandora:
favorites:
name: Favorite Songs
description: Songs you marked as favorites
fields:
- album_art
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite song'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favorites.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
album_art: pandora:albumArtUrl
favoriteartists:
name: Favorite Artists
description: Artists you marked as favorites
fields:
- artist-photo-url
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite artist'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favoriteartists.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
artist-photo-url: pandora:stationImageUrl
stations:
name: Stations
description: Radio stations you added
fields:
- guid
- station-image-url
html_form: '[_1] added a new radio station named <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/stations.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: pandora:stationLink
station-image-url: pandora:stationImageUrl
picasaweb:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://picasaweb.google.com/data/feed/api/user/{{ident}}?kind=photo&max-results=15'
atom:
thumbnail: media:group/media:thumbnail[position()=2]/@url
p0pulist:
stuff:
name: List
description: Things you put in your list
html_form: '[_1] is enjoying <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://p0p.com/list/hot_list/{{ident}}.rss'
rss:
thumbnail: image/url
pownce:
statuses:
name: Notes
description: Your public notes
fields:
- note
html_form: '[_1] <a href="[_2]">posted</a>, "[_3]"'
html_params:
- url
- note
url: 'http://pownce.com/feeds/public/{{ident}}/'
atom:
note: summary
reddit:
comments:
name: Comments
description: Comments you posted
html_form: '[_1] commented on <a href="[_2]">[_3]</a> at Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/comments/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
submitted:
name: Submissions
description: Articles you submitted
html_form: '[_1] submitted <a href="[_2]">[_3]</a> to Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/submitted/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
favorites:
name: Likes
description: Articles you liked (your votes must be public)
html_form: '[_1] liked <a href="[_2]">[_3]</a> from Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/liked/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
dislikes:
name: Dislikes
description: Articles you disliked (your votes must be public)
html_form: '[_1] disliked <a href="[_2]">[_3]</a> on Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/disliked/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
slideshare:
favorites:
name: Favorites
description: Slideshows you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite slideshow'
html_params:
- url
- title
url: 'http://www.slideshare.net/rss/user/{{ident}}/favorites'
rss:
thumbnail: media:content/media:thumbnail/@url
created_on: ''
slideshows:
name: Slideshows
description: Slideshows you posted
html_form: '[_1] posted the slideshow <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.slideshare.net/rss/user/{{ident}}'
rss:
thumbnail: media:content/media:thumbnail/@url
smugmug:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">a photo</a>'
html_params:
- url
url: 'http://www.smugmug.com/hack/feed.mg?Type=nicknameRecentPhotos&Data={{ident}}&format=atom10&ImageCount=15'
atom:
thumbnail: id
steam:
achievements:
name: Achievements
description: Your achievements for achievement-enabled games
html_form: '[_1] won the <strong>[_2]</strong> achievement in <a href="http://steamcommunity.com/id/[_3]/stats/[_4]?tab=achievements">[_5]</a>'
html_params:
- title
- ident
- gamecode
- game
class: Steam
tumblr:
events:
name: Stuff
description: Things you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://{{ident}}.tumblr.com/rss'
rss: 1
twitter:
statuses:
name: Tweets
description: Your public tweets
class: TwitterTweet
html_form: '[_1] <a href="[_2]">tweeted</a>, "[_3]"'
html_params:
- url
- title
url: 'http://twitter.com/statuses/user_timeline/{{ident}}.atom'
atom: 1
favorites:
name: Favorites
description: Public tweets you saved as favorites
class: TwitterFavorite
fields:
- tweet_author
html_form: '[_1] saved <a href="[_2]">[_3]''s tweet</a>, "[_4]" as a favorite'
html_params:
- url
- tweet_author
- title
url: 'http://twitter.com/favorites/{{ident}}.atom'
atom:
created_on: ''
modified_on: ''
typepad:
comments:
name: Comments
description: Comments you posted
html_form: '[_1] left a comment on <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://profile.typepad.com/{{ident}}/comments/atom.xml'
atom: 1
uncrate:
saved:
name: Saved
description: Things you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> on Uncrate'
html_params:
- url
- title
url: 'http://www.uncrate.com/stuff/{{ident}}'
identifier: url
scraper:
foreach: '#profile-recent-actions h2'
get:
title:
- a
- TEXT
url:
- a
- '@href'
upcoming:
events:
name: Events
description: Events you are watching or attending
fields:
- venue
html_form: '[_1] is attending <a href="[_2]">[_3]</a> at [_4]'
html_params:
- url
- title
- venue
url: 'http://upcoming.yahoo.com/syndicate/v2/my_events/{{ident}}'
xpath:
foreach: //item
get:
title: xCal:summary
url: link
created_on: dc:date
modified_on: dc:date
venue: 'xCal:x-calconnect-venue/xCal:adr/xCal:x-calconnect-venue-name'
identifier: guid
viddler:
videos:
name: Videos
description: Videos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.viddler.com/explore/{{ident}}/videos/feed/'
rss:
thumbnail: media:content/media:thumbnail/@url
vimeo:
videos:
name: Videos
description: Videos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://vimeo.com/{{ident}}/videos/rss
rss:
thumbnail: media:thumbnail/@url
like:
name: Likes
description: Videos you liked
html_form: '[_1] liked <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://vimeo.com/{{ident}}/likes/rss
rss:
thumbnail: media:thumbnail/@url
created_on: ''
modified_on: ''
vox:
favorites:
name: Favorites
description: Public assets you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite'
html_params:
- url
- title
class: Vox
photos:
name: Photos
description: Your public photos in your Vox library
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://{{ident}}.vox.com/library/photos/rss.xml'
rss:
thumbnail: media:thumbnail/@url
tags: category
posts:
name: Posts
description: Your public posts to your Vox
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://{{ident}}.vox.com/library/posts/atom.xml'
atom:
tags: category/@label
website:
posted:
name: Posts
description: The posts available from the website's feed
html_form: '[_1] posted <a href="[_2]">[_3]</a> on <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- source_url
- source_title
class: Website
wists:
wists:
name: Wists
description: Stuff you saved
html_form: '[_1] wants <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.wists.com/{{ident}}?out=rdf'
identifier: url
rss:
created_on: dc:date
tags: dc:tag
thumbnail: content:encoded
xboxlive:
gamerscore:
name: Gamerscore
description: Notes when your gamerscore passes an even number
html_form: '[_1] passed <strong>[_2]</strong> gamerscore <a href="[_3]">on Xbox Live</a>'
html_params:
- score
- url
class: XboxGamerscore
yelp:
reviews:
name: Reviews
description: Places you reviewed
html_form: '[_1] reviewed <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.yelp.com/syndicate/user/{{ident}}/atom.xml'
atom:
url: link/@href
youtube:
favorites:
name: Favorites
description: Videos you saved as favorites
fields:
- by
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video'
html_params:
- url
- title
url: 'http://gdata.youtube.com/feeds/users/{{ident}}/favorites'
atom:
by: author/name
url: "link[@rel='alternate' and @type='text/html']/@href"
thumbnail: "media:group/media:thumbnail[position()=1]/@url"
created_on: ''
modified_on: ''
videos:
name: Videos
description: Videos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a> to YouTube'
html_params:
- url
- title
url: 'http://gdata.youtube.com/feeds/users/{{ident}}/uploads'
atom:
url: "link[@rel='alternate' and @type='text/html']/@href"
thumbnail: "media:group/media:thumbnail[position()=1]/@url"
zooomr:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">a photo</a>'
html_params:
- url
url: 'http://www.zooomr.com/services/feeds/public_photos/?id={{ident}}&format=rss_200'
xpath:
foreach: //item
get:
identifier: link
thumbnail: media:content/@url
|
markpasc/mt-plugin-action-streams
|
aff501705b0998dbb2ea19857b1f1fb74fbb3b1d
|
Deprecate Dodgeball and Magnolia services Clean up the Motion ident_hints Fix capitalization of "iStockphoto" Update service and stream for p0p.com nee p0pulist Update service and stream for Uncrate
|
diff --git a/plugins/ActionStreams/services.yaml b/plugins/ActionStreams/services.yaml
index 55395f0..da5eb8a 100644
--- a/plugins/ActionStreams/services.yaml
+++ b/plugins/ActionStreams/services.yaml
@@ -1,331 +1,335 @@
oneup:
name: 1up.com
url: http://{{ident}}.1up.com/
fortythreethings:
name: 43Things
url: http://www.43things.com/person/{{ident}}/
aim:
name: AIM
url: aim:goim?screenname={{ident}}
ident_label: Screen name
service_type: contact
backtype:
name: backtype
url: http://www.backtype.com/{{ident}}
service_type: comments
bebo:
name: Bebo
url: http://www.bebo.com/Profile.jsp?MemberId={{ident}}
service_type: network
catster:
name: Catster
url: http://www.catster.com/cats/{{ident}}
colourlovers:
name: COLOURlovers
url: http://www.colourlovers.com/lover/{{ident}}
corkd:
name: 'Cork''d'
url: http://www.corkd.com/people/{{ident}}
delicious:
name: Delicious
url: http://delicious.com/{{ident}}/
service_type: links
destructoid:
name: Destructoid
url: http://www.destructoid.com/elephant/profile.phtml?un={{ident}}
digg:
name: Digg
url: http://digg.com/users/{{ident}}/
service_type: links
dodgeball:
name: Dodgeball
url: http://www.dodgeball.com/user?uid={{ident}}
+ deprecated: 1
dogster:
name: Dogster
url: http://www.dogster.com/dogs/{{ident}}
dopplr:
name: Dopplr
url: http://www.dopplr.com/traveller/{{ident}}/
facebook:
name: Facebook
url: http://www.facebook.com/profile.php?id={{ident}}
ident_label: User ID
ident_example: 12345
service_type: network
- ident_hint: You can find your Facebook userid within your profile URL. For example, http://www.facebook.com/profile.php?id=24400320.
+ ident_hint: You can find your Facebook user ID in your profile URL. For example: http://www.facebook.com/profile.php?id=12345
ffffound:
name: FFFFOUND!
url: http://ffffound.com/home/{{ident}}/found/
service_type: photos
flickr:
name: Flickr
url: http://flickr.com/photos/{{ident}}/
ident_example: 36381329@N00
service_type: photos
- ident_hint: Enter your Flickr userid which contains "@" in it, e.g. 36381329@N00. Flickr userid is NOT the username in the URL of your photostream.
+ ident_hint: Enter your Flickr user ID that has a "@" in it. Your Flickr user ID is NOT the username in the URL of your photo stream.
friendfeed:
name: FriendFeed
url: http://friendfeed.com/{{ident}}
ident_example: JoeUsername
gametap:
name: Gametap
url: http://www.gametap.com/profile/show/profile.do?sn={{ident}}
goodreads:
name: Goodreads
url: http://www.goodreads.com/user/show/{{ident}}
ident_label: User ID
ident_example: 12345
- ident_hint: You can find your Goodreads userid within your profile URL. For example, http://www.goodreads.com/user/show/123456.
+ ident_hint: You can find your Goodreads user ID in your profile URL. For example: http://www.goodreads.com/user/show/12345
googlereader:
name: Google Reader
url: http://www.google.com/reader/shared/{{ident}}
ident_label: Sharing ID
ident_example: http://www.google.com/reader/shared/16793324975410272738
service_type: links
hi5:
name: Hi5
url: http://hi5.com/friend/profile/displayProfile.do?userid={{ident}}
service_type: network
iconbuffet:
name: IconBuffet
url: http://www.iconbuffet.com/people/{{ident}}
icq:
name: ICQ
url: http://www.icq.com/people/about_me.php?uin={{ident}}
ident_label: UIN
ident_example: 12345
service_type: contact
identica:
name: Identi.ca
url: http://identi.ca/{{ident}}
service_type: status
iminta:
name: Iminta
url: http://iminta.com/people/{{ident}}
istockphoto:
- name: iStockPhoto
+ name: iStockphoto
url: http://www.istockphoto.com/user_view.php?id={{ident}}
ident_label: User ID
ident_example: 123456
- ident_hint: You can find your istockphoto userid within your profile URL. For example, http://www.istockphoto.com/user_view.php?id=1234567.
+ ident_hint: You can find your iStockphoto user ID in your profile URL. For example: http://www.istockphoto.com/user_view.php?id=123456
iusethis:
name: IUseThis
url: http://osx.iusethis.com/user/{{ident}}
iwatchthis:
name: iwatchthis
url: http://iwatchthis.com/{{ident}}
jabber:
name: Jabber
url: jabber://{{ident}}
ident_label: Jabber ID
ident_example: [email protected]
service_type: contact
jaiku:
name: Jaiku
url: http://{{ident}}.jaiku.com/
ident_suffix: .jaiku.com
service_type: status
kongregate:
name: Kongregate
url: http://www.kongregate.com/accounts/{{ident}}
lastfm:
name: Last.fm
url: http://www.last.fm/user/{{ident}}/
ident_example: JoeUsername
linkedin:
name: LinkedIn
url: http://www.linkedin.com/in/{{ident}}
ident_example: MelodyNelson
ident_prefix: http://www.linkedin.com/in/
ident_label: Profile URL
service_type: network
livejournal:
name: LiveJournal
url: http://{{ident}}.livejournal.com/
ident_suffix: .livejournal.com
service_type: blog
magnolia:
name: Ma.gnolia
url: http://ma.gnolia.com/people/{{ident}}
service_type: links
+ deprecated: 1
mog:
name: MOG
url: http://mog.com/{{ident}}
msn:
name: 'MSN Messenger'
url: msnim:chat?contact={{ident}}
service_type: contact
multiply:
name: Multiply
url: http://{{ident}}.multiply.com/
myspace:
name: MySpace
url: http://www.myspace.com/{{ident}}
ident_label: User ID
ident_prefix: http://www.myspace.com/
service_type: network
netflix:
name: Netflix
url: http://rss.netflix.com/QueueRSS?id={{ident}}
ident_label: Netflix RSS ID
ident_example: P0000006746939516625352861892808956
ident_hint: To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.
netvibes:
name: Netvibes
url: http://www.netvibes.com/{{ident}}
service_type: links
newsvine:
name: Newsvine
url: http://{{ident}}.newsvine.com/
ning:
name: Ning
url: http://{{ident}}.ning.com/
service_type: network
ident_suffix: .ning.com/
ident_prefix: http://
ident_label: Social Network URL
ohloh:
name: Ohloh
url: http://ohloh.net/accounts/{{ident}}
orkut:
name: Orkut
url: http://www.orkut.com/Profile.aspx?uid={{ident}}
ident_label: User ID
ident_example: 1234567890123456789
service_type: network
- ident_hint: You can find your orkut uid within your profile URL. For example, http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789
+ ident_hint: You can find your Orkut user ID in your profile URL. For example: http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789
pandora:
name: Pandora
url: http://pandora.com/people/{{ident}}
ident_example: JoeUsername
picasaweb:
name: Picasa Web Albums
url: http://picasaweb.google.com/{{ident}}
service_type: photos
p0pulist:
- name: p0pulist
- url: http://p0pulist.com/list/hot_list/{{ident}}
+ name: p0p
+ url: http://p0p.com/list/hot_list/{{ident}}
ident_label: User ID
ident_example: 12345
- ident_hint: You can find your p0pulist user id within your Hot List URL. for example, http://p0pulist.com/list/hot_list/10000
+ ident_hint: You can find your p0p user ID in your Hot List URL. For example: http://p0pulist.com/list/hot_list/12345
pownce:
name: Pownce
url: http://pownce.com/{{ident}}/
service_type: status
deprecated: 1
reddit:
name: Reddit
url: http://reddit.com/user/{{ident}}/
service_type: links
skype:
name: Skype
url: callto://{{ident}}
slideshare:
name: SlideShare
url: http://www.slideshare.net/{{ident}}
smugmug:
name: Smugmug
url: http://{{ident}}.smugmug.com/
service_type: photos
sonicliving:
name: SonicLiving
url: http://www.sonicliving.com/user/{{ident}}/
ident_label: User ID
ident_example: 12345
- ident_hint: You can find your SonicLiving userid within your share&subscribe URL. For example, http://sonicliving.com/user/12345/feeds
+ ident_hint: You can find your SonicLiving user ID in your Share & Subscribe URL. For example: http://sonicliving.com/user/12345/feeds
steam:
name: Steam
url: http://steamcommunity.com/id/{{ident}}
stumbleupon:
name: StumbleUpon
url: http://{{ident}}.stumbleupon.com/
tabblo:
name: Tabblo
url: http://www.tabblo.com/studio/person/{{ident}}/
technorati:
name: Technorati
url: http://technorati.com/people/technorati/{{ident}}
tribe:
name: Tribe
url: http://people.tribe.net/{{ident}}
service_type: network
ident_label: User ID
- ident_hint: You can find your tribe userid within your profile URL. For example, http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a.
+ ident_example: dcdc61ed-696a-40b5-80c1-e9a9809a726a
+ ident_hint: You can find your Tribe user ID in your profile URL. For example: http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a
tumblr:
name: Tumblr
url: http://{{ident}}.tumblr.com
icon: images/services/tumblr.gif
ident_label: URL
ident_suffix: .tumblr.com
service_type: blog
twitter:
name: Twitter
url: http://twitter.com/{{ident}}
service_type: status
typepad:
name: TypePad
ident_prefix: http://profile.typepad.com/
ident_label: Profile URL
url: http://profile.typepad.com/{{ident}}
uncrate:
name: Uncrate
- url: http://uncrate.com/stuff/{{ident}}
+ url: http://www.uncrate.com/stuff/{{ident}}
upcoming:
name: Upcoming
url: http://upcoming.yahoo.com/user/{{ident}}
ident_label: User ID
ident_example: 12345
viddler:
name: Viddler
url: http://www.viddler.com/explore/{{ident}}
service_type: video
vimeo:
name: Vimeo
url: http://www.vimeo.com/{{ident}}
service_type: video
virb:
name: Virb
url: http://www.virb.com/{{ident}}
service_type: network
ident_label: User ID
- ident_hint: You can find your VIRB userid within your home URL. For example, http://www.virb.com/backend/2756504321310091/your_home.
+ ident_example: 2756504321310091
+ ident_hint: You can find your Virb user ID in your home URL. For example: http://www.virb.com/backend/2756504321310091/your_home
vox:
name: Vox
url: http://{{ident}}.vox.com/
ident_label: Vox name
ident_suffix: .vox.com
service_type: blog
website:
name: Website
url: '{{ident}}'
ident_label: URL
ident_example: http://www.example.com/
ident_exact: 1
can_many: 1
service_type: blog
wists:
name: Wists
url: http://www.wists.com/{{ident}}
xboxlive:
name: 'Xbox Live'
url: http://live.xbox.com/member/{{ident}}
ident_label: Gamertag
yahoo:
name: 'Yahoo! Messenger'
url: http://edit.yahoo.com/config/send_webmesg?.target={{ident}}
service_type: contact
yelp:
name: Yelp
url: http://www.yelp.com/user_details?userid={{ident}}
ident_label: User ID
ident_example: 4BXqlLKW8oP0RBCW1FvaIg
youtube:
name: YouTube
url: http://www.youtube.com/user/{{ident}}
service_type: video
zooomr:
name: Zooomr
url: http://www.zooomr.com/photos/{{ident}}
ident_example: 1234567@Z01
service_type: photos
diff --git a/plugins/ActionStreams/streams.yaml b/plugins/ActionStreams/streams.yaml
index a856683..00ceb41 100644
--- a/plugins/ActionStreams/streams.yaml
+++ b/plugins/ActionStreams/streams.yaml
@@ -143,881 +143,881 @@ digg:
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
submitted:
name: Submissions
description: Links you submitted
html_form: '[_1] submitted the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://digg.com/users/{{ident}}/history/submissions.rss
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
ffffound:
favorites:
name: Found
description: Photos you found
html_form: '[_1] ffffound <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://ffffound.com/home/{{ident}}/found/feed
rss: 1
flickr:
favorites:
name: Favorites
description: Photos you marked as favorites
fields:
- by
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite photo'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_faves.gne?nsid={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
by: author/name
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_public.gne?id={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
friendfeed:
likes:
name: Likes
description: Things from your friends that you "like"
html_form: '[_1] likes <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://friendfeed.com/{{ident}}/likes?format=atom'
atom:
url: link/@href
gametap:
scores:
name: Leaderboard scores
description: Your high scores in games with leaderboards
fields:
- score
html_form: '[_1] scored <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- score
- url
- title
url: http://www.gametap.com/profile/leaderboards.do?sn={{ident}}
identifier: title,score
scraper:
foreach: 'div.buddy-leaderboards div.tr'
get:
url:
- 'div.name a'
- '@href'
title:
- 'div.name strong'
- TEXT
score:
- 'div.name div'
- TEXT
goodreads:
toread:
name: To read
description: Books on your "to-read" shelf
fields:
- by
html_form: '[_1] saved <a href="[_2]"><i>[_3]</i> by [_4]</a> to read'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=to-read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
reading:
name: Reading
description: Books on your "currently-reading" shelf
fields:
- by
html_form: '[_1] started reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=currently-reading'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
read:
name: Read
description: Books on your "read" shelf
fields:
- by
html_form: '[_1] finished reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
googlereader:
links:
name: Shared
description: Your shared items
html_form: '[_1] shared <a href="[_2]">[_3]</a> from <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- source_url
- source_title
class: GoogleReader
iconbuffet:
icons:
name: Deliveries
description: Icon sets you were delivered
html_form: '[_1] received the icon set <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.iconbuffet.com/people/{{ident}};received_packages'
identifier: url
scraper:
foreach: 'div#icons div.preview-sm'
get:
title:
- a span
- TEXT
url:
- a
- '@href'
identica:
statuses:
name: Notices
description: Notices you posted
html_form: '[_1] <a href="[_2]">said</a>, “[_3]”'
html_params:
- url
- title
url: 'http://identi.ca/{{ident}}/rss'
rss:
created_on: dc:date
class: Identica
iminta:
links:
name: Intas
description: Links you saved
html_form: '[_1] is inta <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://iminta.com/people/{{ident}}/rss.xml?inta_source_id=11'
rss: 1
istockphoto:
photos:
name: Photos
description: Photos you posted that were approved
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.istockphoto.com/webservices/feeds/?feedFormat=IStockAtom_1_0&feedName=istockfeed.image.newestUploads&feedParams=UserID={{ident}}'
identifier: url
atom:
thumbnail: content/div/a/img/@src
iusethis:
events:
name: Recent events
description: Events from your recent events feed
html_form: '[_1] <a href="[_2]">[_3]</a>'
html_params:
- url
- title
rss: 1
url: 'http://osx.iusethis.com/user/feed.rss/{{ident}}?following=0'
osxapps:
name: Apps you use
description: The applications you saved as ones you use
fields:
- favorite
html_form: '[_1] started using <a href="[_2]">[_3]</a>[quant,_4, (and loves it),,]'
html_params:
- url
- title
- favorite
url: 'http://osx.iusethis.com/user/{{ident}}'
iwatchthis:
favorites:
name: Favorites
description: Videos you saved as watched
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video'
html_params:
- url
- title
url: 'http://iwatchthis.com/rss/{{ident}}'
rss: 1
jaiku:
jaikus:
name: Jaikus
description: Jaikus you posted
html_form: '[_1] <a href="[_2]">jaiku''d</a>, "[_3]"'
html_params:
- url
- title
url: 'http://{{ident}}.jaiku.com/feed/atom'
atom: 1
kongregate:
favorites:
name: Favorites
description: Games you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite game'
html_params:
- url
- title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url
scraper:
foreach: #favorites dl
get:
url:
- dd a
- '@href'
title:
- dd a
- TEXT
thumbnail:
- dt img
- '@src'
achievements:
name: Achievements
description: Achievements you won
fields:
- game_title
html_form: '[_1] won the <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- title
- url
- game_title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url,title
scraper:
foreach: #achievements .badge_details
get:
url:
- dt.badge_img a
- '@href'
thumbnail:
- dt.badge_img img
- '@style'
title:
- dd.badge_name
- TEXT
game_title:
- a.badge_game
- TEXT
lastfm:
tracks:
name: Tracks
description: Songs you recently listened to (High spam potential!)
html_form: '[_1] heard <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/recenttracks.rss'
rss: 1
lovedtracks:
name: Loved Tracks
description: Songs you marked as "loved"
fields:
- artist
html_form: '[_1] loved <a href="[_2]">[_3]</a> by [_4]'
html_params:
- url
- title
- artist
url: 'http://pipes.yahoo.com/pipes/pipe.run?_id=4smlkvMW3RGPpBPfTqoASA&_render=rss&lastFM_UserName={{ident}}'
identifier: url
rss:
artist: description
journalentries:
name: Journal Entries
description: Your recent journal entries
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/journals.rss'
rss: 1
events:
name: Events
description: The events you said you'll be attending
html_form: '[_1] is attending <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/events.rss'
rss: 1
livejournal:
posts:
name: Posts
description: Your public posts to your journal
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://users.livejournal.com/{{ident}}/data/atom'
atom: 1
magnolia:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ma.gnolia.com/atom/full/people/{{ident}}'
identifier: url
atom:
tags: "category[@scheme='http://ma.gnolia.com/tags']/@term"
note: content
netflix:
queue:
name: Queue
description: Movies you added to your rental queue
fields:
- queue
html_form: '[_1] queued <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/QueueRSS?id={{ident}}'
rss:
thumbnail: description
recent:
name: Recent Movies
description: Recent Rental Activity
fields:
- recent
html_form: '[_1] is watching <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/TrackingRSS?id={{ident}}'
rss:
thumbnail: description
netvibes:
links:
name: Links
description: Links you saved
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www2.netvibes.com/rest/account/{{ident}}/timeline?format=atom'
atom: 1
ohloh:
kudos:
name: Kudos
description: Kudos you have received
html_form: '[_1] received kudos from <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.ohloh.net/accounts/{{ident}}/kudos'
identifier: url
scraper:
foreach: 'div.received_kudo'
get:
url:
- a
- '@href'
title:
- a
- TEXT
pandora:
favorites:
name: Favorite Songs
description: Songs you marked as favorites
fields:
- album_art
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite song'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favorites.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
album_art: pandora:albumArtUrl
favoriteartists:
name: Favorite Artists
description: Artists you marked as favorites
fields:
- artist-photo-url
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite artist'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favoriteartists.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
artist-photo-url: pandora:stationImageUrl
stations:
name: Stations
description: Radio stations you added
fields:
- guid
- station-image-url
html_form: '[_1] added a new radio station named <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/stations.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: pandora:stationLink
station-image-url: pandora:stationImageUrl
picasaweb:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://picasaweb.google.com/data/feed/api/user/{{ident}}?kind=photo&max-results=15'
atom:
thumbnail: media:group/media:thumbnail[position()=2]/@url
p0pulist:
stuff:
name: List
description: Things you put in your list
html_form: '[_1] is enjoying <a href="[_2]">[_3]</a>'
html_params:
- url
- title
- url: 'http://p0pulist.com/list/hot_list/{{ident}}.rss'
+ url: 'http://p0p.com/list/hot_list/{{ident}}.rss'
rss:
thumbnail: image/url
pownce:
statuses:
name: Notes
description: Your public notes
fields:
- note
html_form: '[_1] <a href="[_2]">posted</a>, "[_3]"'
html_params:
- url
- note
url: 'http://pownce.com/feeds/public/{{ident}}/'
atom:
note: summary
reddit:
comments:
name: Comments
description: Comments you posted
html_form: '[_1] commented on <a href="[_2]">[_3]</a> at Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/comments/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
submitted:
name: Submissions
description: Articles you submitted
html_form: '[_1] submitted <a href="[_2]">[_3]</a> to Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/submitted/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
favorites:
name: Likes
description: Articles you liked (your votes must be public)
html_form: '[_1] liked <a href="[_2]">[_3]</a> from Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/liked/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
dislikes:
name: Dislikes
description: Articles you disliked (your votes must be public)
html_form: '[_1] disliked <a href="[_2]">[_3]</a> on Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/disliked/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
slideshare:
favorites:
name: Favorites
description: Slideshows you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite slideshow'
html_params:
- url
- title
url: 'http://www.slideshare.net/rss/user/{{ident}}/favorites'
rss:
thumbnail: media:content/media:thumbnail/@url
created_on: ''
slideshows:
name: Slideshows
description: Slideshows you posted
html_form: '[_1] posted the slideshow <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.slideshare.net/rss/user/{{ident}}'
rss:
thumbnail: media:content/media:thumbnail/@url
smugmug:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">a photo</a>'
html_params:
- url
url: 'http://www.smugmug.com/hack/feed.mg?Type=nicknameRecentPhotos&Data={{ident}}&format=atom10&ImageCount=15'
atom:
thumbnail: id
steam:
achievements:
name: Achievements
description: Your achievements for achievement-enabled games
html_form: '[_1] won the <strong>[_2]</strong> achievement in <a href="http://steamcommunity.com/id/[_3]/stats/[_4]?tab=achievements">[_5]</a>'
html_params:
- title
- ident
- gamecode
- game
class: Steam
tumblr:
events:
name: Stuff
description: Things you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://{{ident}}.tumblr.com/rss'
rss: 1
twitter:
statuses:
name: Tweets
description: Your public tweets
class: TwitterTweet
html_form: '[_1] <a href="[_2]">tweeted</a>, "[_3]"'
html_params:
- url
- title
url: 'http://twitter.com/statuses/user_timeline/{{ident}}.atom'
atom: 1
favorites:
name: Favorites
description: Public tweets you saved as favorites
class: TwitterFavorite
fields:
- tweet_author
html_form: '[_1] saved <a href="[_2]">[_3]''s tweet</a>, "[_4]" as a favorite'
html_params:
- url
- tweet_author
- title
url: 'http://twitter.com/favorites/{{ident}}.atom'
atom:
created_on: ''
modified_on: ''
typepad:
comments:
name: Comments
description: Comments you posted
html_form: '[_1] left a comment on <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://profile.typepad.com/{{ident}}/comments/atom.xml'
atom: 1
uncrate:
saved:
name: Saved
description: Things you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> on Uncrate'
html_params:
- url
- title
- url: 'http://uncrate.com/stuff/{{ident}}'
+ url: 'http://www.uncrate.com/stuff/{{ident}}'
identifier: url
scraper:
- foreach: '#widget h2'
+ foreach: '#profile-recent-actions h2'
get:
title:
- a
- TEXT
url:
- a
- '@href'
upcoming:
events:
name: Events
description: Events you are watching or attending
fields:
- venue
html_form: '[_1] is attending <a href="[_2]">[_3]</a> at [_4]'
html_params:
- url
- title
- venue
url: 'http://upcoming.yahoo.com/syndicate/v2/my_events/{{ident}}'
xpath:
foreach: //item
get:
title: xCal:summary
url: link
created_on: dc:date
modified_on: dc:date
venue: 'xCal:x-calconnect-venue/xCal:adr/xCal:x-calconnect-venue-name'
identifier: guid
viddler:
videos:
name: Videos
description: Videos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.viddler.com/explore/{{ident}}/videos/feed/'
rss:
thumbnail: media:content/media:thumbnail/@url
vimeo:
videos:
name: Videos
description: Videos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://vimeo.com/{{ident}}/videos/rss
rss:
thumbnail: media:thumbnail/@url
like:
name: Likes
description: Videos you liked
html_form: '[_1] liked <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://vimeo.com/{{ident}}/likes/rss
rss:
thumbnail: media:thumbnail/@url
created_on: ''
modified_on: ''
vox:
favorites:
name: Favorites
description: Public assets you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite'
html_params:
- url
- title
class: Vox
photos:
name: Photos
description: Your public photos in your Vox library
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://{{ident}}.vox.com/library/photos/rss.xml'
rss:
thumbnail: media:thumbnail/@url
tags: category
posts:
name: Posts
description: Your public posts to your Vox
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://{{ident}}.vox.com/library/posts/atom.xml'
atom:
tags: category/@label
website:
posted:
name: Posts
description: The posts available from the website's feed
html_form: '[_1] posted <a href="[_2]">[_3]</a> on <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- source_url
- source_title
class: Website
wists:
wists:
name: Wists
description: Stuff you saved
html_form: '[_1] wants <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.wists.com/{{ident}}?out=rdf'
identifier: url
rss:
created_on: dc:date
tags: dc:tag
thumbnail: content:encoded
xboxlive:
gamerscore:
name: Gamerscore
description: Notes when your gamerscore passes an even number
html_form: '[_1] passed <strong>[_2]</strong> gamerscore <a href="[_3]">on Xbox Live</a>'
html_params:
- score
- url
class: XboxGamerscore
yelp:
reviews:
name: Reviews
description: Places you reviewed
html_form: '[_1] reviewed <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.yelp.com/syndicate/user/{{ident}}/atom.xml'
atom:
url: link/@href
youtube:
favorites:
name: Favorites
description: Videos you saved as favorites
fields:
- by
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video'
html_params:
- url
- title
url: 'http://gdata.youtube.com/feeds/users/{{ident}}/favorites'
atom:
by: author/name
url: "link[@rel='alternate' and @type='text/html']/@href"
thumbnail: "media:group/media:thumbnail[position()=1]/@url"
created_on: ''
modified_on: ''
videos:
name: Videos
description: Videos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a> to YouTube'
html_params:
- url
- title
url: 'http://gdata.youtube.com/feeds/users/{{ident}}/uploads'
atom:
url: "link[@rel='alternate' and @type='text/html']/@href"
thumbnail: "media:group/media:thumbnail[position()=1]/@url"
zooomr:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">a photo</a>'
html_params:
- url
url: 'http://www.zooomr.com/services/feeds/public_photos/?id={{ident}}&format=rss_200'
xpath:
foreach: //item
get:
identifier: link
thumbnail: media:content/@url
|
markpasc/mt-plugin-action-streams
|
360eab61ddc2a77a45d0ef4fff1415c50f3340ad
|
Renumerate for next version
|
diff --git a/Makefile.PL b/Makefile.PL
index a83b792..893d5a8 100644
--- a/Makefile.PL
+++ b/Makefile.PL
@@ -1,7 +1,7 @@
use ExtUtils::MakeMaker;
WriteMakefile(
NAME => 'ActionStreams',
- VERSION => '2.0',
+ VERSION => '2.2',
DISTNAME => 'ActionStreams',
);
diff --git a/README.txt b/README.txt
index 439de50..eb4efb5 100644
--- a/README.txt
+++ b/README.txt
@@ -1,119 +1,131 @@
# Action Streams Plugin for Movable Type
-# Authors: Mark Paschal, Bryan Tighe, Brad Choate, Alex Bain
-# Copyright 2008 Six Apart, Ltd.
+# Authors: Mark Paschal, Akira Sawada, Fumiaki Yoshimatsu, Bryan Tighe,
+# Brad Choate, Alex Bain
+# Copyright 2009 Six Apart, Ltd.
# License: Artistic, licensed under the same terms as Perl itself
OVERVIEW
Action Streams for Movable Type collects your action on third party web sites
into your Movable Type web site. Using it, you can aggregate those actions for
your reference, promote specific items to blog posts, and stream the whole set
to your friends and readers. Action Streams are a powerful part of your web
profile.
The plugin adds the ability for your Movable Type authors to list their
accounts on third party web services. A periodic task then automatically
imports your authors' activity on those services using XML feeds (where
provided) and scraping HTML pages (where necessary). Your authors can then
publish their action streams completely under their control: the provided
template tags make it possible to display authors' accounts and actions on any
page powered by Movable Type. The example templates and the provided template
set also use the XFN and hAtom microformats and provide web feeds to integrate
with tools your readers may be using.
PREREQUISITES
- Movable Type 4.2 or higher
- Scheduled task or cron job to execute the Periodic Tasks script (see below)
The Action Streams plugin ships with all of the external libraries you should
need to run it.
Note: Action Streams does not work when run-periodic-tasks is run in daemon
mode.
INSTALLATION
1. Configure a cronjob (see below) for the script run-periodic-tasks.
2. Unpack the ActionStreams archive.
3. Copy the contents of ActionStreams/extlib into /path/to/mt/extlib/
3. Copy the contents of ActionStreams/mt-static into /path/to/mt/mt-static/
4. Copy the contents of ActionStreams/plugins into /path/to/mt/plugins/
5. Navigate to your profile, and click on "Other Profiles."
6. Build a list of your accounts from which to display and stream actions.
7. Edit your stylesheet to include needed CSS. (see STYLES below)
8. Edit your templates to display your other profiles and your Action
Stream. (See the Template Author Guide in the doc/ folder.) A template
set is also provided for convenience.
9. Edit the plugin's settings to enable automatically rebuilding your blog
as new actions are imported. This setting is under each of your blog's
plugin settings.
CRONJOB
Action Streams uses Movable Type's scheduled task system to collect your
action data from remote services. To run scheduled tasks, configure a cron job
to run MT's tools/run-periodic-tasks script periodically.
Add the following lines to your crontab to execute the script every 10
minutes:
# Movable Type scheduled tasks
*/10 * * * * cd /path/to/mt; perl ./tools/run-periodic-tasks
STYLES
To add icons to your Action Streams and other basic styling, add the following
line to the top of your main stylesheet (normally styles.css).
@import url(<MT:StaticWebPath>plugins/ActionStreams/css/action-streams.css);
The classes used in the template code examples use the same classes as the
default templates and thus they work well with the default themes.
TEMPLATE CODE
See the Template Author Guide in the doc/ folder for help with Action Streams'
template tags.
CHANGES
-2.0 30 January 2009
+2.2 in development
+ Improved Delicious stream.
+ Fixed error when rebuilding blogs with deactivated templates.
+ Support for "not" operator in mt:ActionStreams "service" and "stream"
+ tag attributes when used individually.
+ Quieter operation when used with Log4MT.
+ Fixed bug that prevented use of methods other than get() with the HTTP
+ caching system.
+
+2.1 17 March 2009
+ Localized into several pleasing world languages. (Thanks, Six Apart
+ Motion Team!)
Wrote documentation (see plugin's doc/ directory or web site).
Provided editing of external profiles that have already been added.
Added "Update Now" button to profiles list.
Hotlinking of Twitter and Identi.ca tweets in default rendering.
Support for conditional HTTP requests when collecting actions.
Provided filtering of the "Action Streams" listing in the app.
Added `StreamActionRollup` tag for "rolling up" similar actions.
Bundled the "Recent Actions" blog dashboard widget. (Thanks, Bryan!)
Added support for RSS feeds in the Website stream.
Provided code to make easy "rss" recipes from RSS feeds.
Improved template set (incl. fixes for MT 4.2 support).
Switched to asynchronous job processing for action collecting.
Made installation easier (less dependent on Web::Scraper, moved extlib
into plugin as per MT 4.2 capability, removed Iwtst plugin).
Added many new profiles and streams!
1.0 30 January 2008
Initial release.
CREDITS
Thanks to Bryan Tighe, Brad Choate, and Alex Bain for their contributions of
various features and stream recipes.
This distribution contains icons from Silk, an icon set by Mark James,
licensed under the Creative Commons Attribution 2.5 License.
http://www.famfamfam.com/lab/icons/silk/
diff --git a/plugins/ActionStreams/config.yaml b/plugins/ActionStreams/config.yaml
index 935c407..c67b3e2 100644
--- a/plugins/ActionStreams/config.yaml
+++ b/plugins/ActionStreams/config.yaml
@@ -1,194 +1,194 @@
name: Action Streams
id: ActionStreams
key: ActionStreams
author_link: http://www.sixapart.com/
author_name: Six Apart Ltd.
description: <MT_TRANS phrase="Manages authors' accounts and actions on sites elsewhere around the web">
schema_version: 16
-version: 2.0
+version: 2.2
plugin_link: http://www.sixapart.com/
settings:
rebuild_for_action_stream_events:
Default: 0
Scope: blog
l10n_class: ActionStreams::L10N
blog_config_template: blog_config_template.tmpl
init_app: $ActionStreams::ActionStreams::Init::init_app
applications:
cms:
methods:
list_profileevent: $ActionStreams::ActionStreams::Plugin::list_profileevent
other_profiles: $ActionStreams::ActionStreams::Plugin::other_profiles
dialog_add_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile
dialog_edit_profile: $ActionStreams::ActionStreams::Plugin::dialog_add_edit_profile
add_other_profile: $ActionStreams::ActionStreams::Plugin::add_other_profile
edit_other_profile: $ActionStreams::ActionStreams::Plugin::edit_other_profile
remove_other_profile: $ActionStreams::ActionStreams::Plugin::remove_other_profile
itemset_update_profiles: $ActionStreams::ActionStreams::Plugin::itemset_update_profiles
itemset_hide_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_events
itemset_show_events: $ActionStreams::ActionStreams::Plugin::itemset_show_events
itemset_hide_all_events: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events
itemset_show_all_events: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events
community:
methods:
profile_add_external_profile: $ActionStreams::ActionStreams::Plugin::profile_add_external_profile
profile_delete_external_profile: $ActionStreams::ActionStreams::Plugin::profile_delete_external_profile
callbacks:
post_add_profile: $ActionStreams::ActionStreams::Plugin::profile_first_update_events
callbacks:
MT::App::CMS::template_param.edit_author: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::template_param.list_member: $ActionStreams::ActionStreams::Plugin::param_list_member
MT::App::CMS::template_param.other_profiles: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::template_param.list_profileevent: $ActionStreams::ActionStreams::Plugin::users_content_nav
MT::App::CMS::post_add_profile: $ActionStreams::ActionStreams::Plugin::first_profile_update
post_action_streams_task: $ActionStreams::ActionStreams::Plugin::rebuild_action_stream_blogs
pre_build_action_streams_event.flickr_favorites: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail
pre_build_action_streams_event.flickr_photos: $ActionStreams::ActionStreams::Fix::flickr_photo_thumbnail
pre_build_action_streams_event.gametap_scores: $ActionStreams::ActionStreams::Fix::gametap_score_stuff
pre_build_action_streams_event.identica_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name
pre_build_action_streams_event.iminta_links: $ActionStreams::ActionStreams::Fix::iminta_link_title
pre_build_action_streams_event.iusethis_events: $ActionStreams::ActionStreams::Fix::iusethis_event_title
pre_build_action_streams_event.kongregate_achievements: $ActionStreams::ActionStreams::Fix::kongregate_achievement_title_thumb
pre_build_action_streams_event.magnolia_links: $ActionStreams::ActionStreams::Fix::magnolia_link_notes
pre_build_action_streams_event.netflix_queue: $ActionStreams::ActionStreams::Fix::netflix_queue_prefix_thumb
pre_build_action_streams_event.netflix_recent: $ActionStreams::ActionStreams::Fix::netflix_recent_prefix_thumb
pre_build_action_streams_event.p0pulist_stuff: $ActionStreams::ActionStreams::Fix::p0pulist_stuff_urls
pre_build_action_streams_event.twitter_favorites: $ActionStreams::ActionStreams::Fix::twitter_favorite_author
pre_build_action_streams_event.twitter_statuses: $ActionStreams::ActionStreams::Fix::twitter_tweet_name
pre_build_action_streams_event.typepad_comments: $ActionStreams::ActionStreams::Fix::typepad_comment_titles
pre_build_action_streams_event.wists_wists: $ActionStreams::ActionStreams::Fix::wists_thumb
object_types:
profileevent: ActionStreams::Event
as: ActionStreams::Event
as_ua_cache: ActionStreams::UserAgent::Cache
list_actions:
profileevent:
hide_all:
label: Hide All
order: 100
js: finishPluginActionAll
code: $ActionStreams::ActionStreams::Plugin::itemset_hide_all_events
continue_prompt_handler: >
sub { MT->translate('Are you sure you want to hide EVERY event in EVERY action stream?') }
show_all:
label: Show All
order: 200
js: finishPluginActionAll
code: $ActionStreams::ActionStreams::Plugin::itemset_show_all_events
continue_prompt_handler: >
sub { MT->translate('Are you sure you want to show EVERY event in EVERY action stream?') }
delete:
label: Delete
order: 300
code: $core::MT::App::CMS::delete
continue_prompt_handler: >
sub { MT->translate('Deleted events that are still available from the remote service will be added back in the next scan. Only events that are no longer available from your profile will remain deleted. Are you sure you want to delete the selected event(s)?') }
tags:
function:
StreamAction: $ActionStreams::ActionStreams::Tags::stream_action
StreamActionID: $ActionStreams::ActionStreams::Tags::stream_action_id
StreamActionVar: $ActionStreams::ActionStreams::Tags::stream_action_var
StreamActionDate: $ActionStreams::ActionStreams::Tags::stream_action_date
StreamActionModifiedDate: $ActionStreams::ActionStreams::Tags::stream_action_modified_date
StreamActionTitle: $ActionStreams::ActionStreams::Tags::stream_action_title
StreamActionURL: $ActionStreams::ActionStreams::Tags::stream_action_url
StreamActionThumbnailURL: $ActionStreams::ActionStreams::Tags::stream_action_thumbnail_url
StreamActionVia: $ActionStreams::ActionStreams::Tags::stream_action_via
OtherProfileVar: $ActionStreams::ActionStreams::Tags::other_profile_var
block:
ActionStreams: $ActionStreams::ActionStreams::Tags::action_streams
StreamActionTags: $ActionStreams::ActionStreams::Tags::stream_action_tags
OtherProfiles: $ActionStreams::ActionStreams::Tags::other_profiles
ProfileServices: $ActionStreams::ActionStreams::Tags::profile_services
StreamActionRollup: $ActionStreams::ActionStreams::Tags::stream_action_rollup
tasks:
UpdateEvents:
frequency: 1800
label: Poll for new events
code: $ActionStreams::ActionStreams::Plugin::update_events
task_workers:
UpdateEvents:
label: Update Events
class: ActionStreams::Worker
widgets:
asotd:
label: Recent Actions
template: widget_recent.mtml
permission: post
singular: 1
set: sidebar
handler: $ActionStreams::ActionStreams::Plugin::widget_recent
condition: $ActionStreams::ActionStreams::Plugin::widget_blog_dashboard_only
template_sets:
streams:
label: Action Stream
base_path: 'blog_tmpl'
base_css: themes-base/blog.css
order: 100
templates:
index:
main_index:
label: Main Index (Recent Actions)
outfile: index.html
rebuild_me: 1
archive:
label: Action Archive
outfile: archive.html
rebuild_me: 1
styles:
label: Stylesheet
outfile: styles.css
rebuild_me: 1
feed_recent:
label: Feed - Recent Activity
outfile: atom.xml
rebuild_me: 1
module:
html_head:
label: HTML Head
banner_header:
label: Banner Header
banner_footer:
label: Banner Footer
sidebar:
label: Sidebar
widget:
elsewhere:
label: Find Authors Elsewhere
actions:
label: Recent Actions
widgetset:
2column_layout_sidebar:
label: 2-column layout - Sidebar
widgets:
- Find Authors Elsewhere
upgrade_functions:
enable_existing_streams:
version_limit: 9
updater:
type: author
label: Enabling default action streams for selected profiles...
code: $ActionStreams::ActionStreams::Upgrade::enable_existing_streams
reclass_actions:
version_limit: 15
handler: $ActionStreams::ActionStreams::Upgrade::reclass_actions
priority: 8
rename_action_metadata:
version_limit: 15
handler: $ActionStreams::ActionStreams::Upgrade::rename_action_metadata
priority: 9
upgrade_data:
reclass_actions:
twitter_tweets: twitter_statuses
pownce_notes: pownce_statuses
googlereader_shared: googlereader_links
rename_action_metadata:
- action_type: delicious_links
old: annotation
new: note
- action_type: googlereader_links
old: annotation
new: note
profile_services: services.yaml
action_streams: streams.yaml
|
markpasc/mt-plugin-action-streams
|
1deb6700b11105a6c5e77e84aa04160039c929c7
|
Add localizations from Motion AS (compare revision 1536)
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/L10N.pm b/plugins/ActionStreams/lib/ActionStreams/L10N.pm
new file mode 100644
index 0000000..4b3da22
--- /dev/null
+++ b/plugins/ActionStreams/lib/ActionStreams/L10N.pm
@@ -0,0 +1,12 @@
+# Movable Type (r) (C) 2001-2008 Six Apart, Ltd. All Rights Reserved.
+# This code cannot be redistributed without permission from www.sixapart.com.
+# For more information, consult your Movable Type license.
+#
+# $Id: $
+
+package ActionStreams::L10N;
+
+use strict;
+use base 'MT::Plugin::L10N';
+
+1;
diff --git a/plugins/ActionStreams/lib/ActionStreams/L10N/de.pm b/plugins/ActionStreams/lib/ActionStreams/L10N/de.pm
new file mode 100644
index 0000000..f042380
--- /dev/null
+++ b/plugins/ActionStreams/lib/ActionStreams/L10N/de.pm
@@ -0,0 +1,354 @@
+# Movable Type (r) (C) 2001-2008 Six Apart, Ltd. All Rights Reserved.
+# This code cannot be redistributed without permission from www.sixapart.com.
+# For more information, consult your Movable Type license.
+#
+# $Id: de.pm 99820 2009-03-09 13:55:28Z mschenk $
+
+package ActionStreams::L10N::de;
+
+use strict;
+use base 'ActionStreams::L10N::en_us';
+use vars qw( %Lexicon );
+%Lexicon = (
+
+# plugins/ActionStreams/blog_tmpl/sidebar.mtml
+
+## plugins/ActionStreams/blog_tmpl/main_index.mtml
+
+## plugins/ActionStreams/blog_tmpl/actions.mtml
+ 'Recent Actions' => 'Aktuelle Aktionen',
+
+## plugins/ActionStreams/blog_tmpl/archive.mtml
+
+## plugins/ActionStreams/blog_tmpl/banner_footer.mtml
+
+## plugins/ActionStreams/blog_tmpl/elsewhere.mtml
+ 'Find [_1] Elsewhere' => '[_1] anderswo finden',
+
+## plugins/ActionStreams/streams.yaml
+ 'Currently Playing' => 'Aktuelle Spiele',
+ 'The games in your collection you\'re currently playing' => 'Die Spiele aus Ihrer Sammlung, die Sie derzeit spielen',
+ 'Comments you have made on the web' => 'Kommentare, die Sie im Web geschrieben haben',
+ 'Colors' => 'Farben',
+ 'Colors you saved' => 'Ihre gespeicherten Farben',
+ 'Palettes' => 'Paletten',
+ 'Palettes you saved' => 'Ihre gespeicherten Paletten',
+ 'Patterns' => 'Muster',
+ 'Patterns you saved' => 'Ihre gespeicherten Muster',
+ 'Favorite Palettes' => 'Lieblings-Paletten',
+ 'Palettes you saved as favorites' => 'Paletten, die Sie als Favoriten gespeichert haben',
+ 'Reviews' => 'Kritiken',
+ 'Your wine reviews' => 'Ihre Wein-Kritiken',
+ 'Cellar' => 'Weinkeller',
+ 'Wines you own' => 'Weine in Ihrer Sammlung',
+ 'Shopping List' => 'Shopping-Liste',
+ 'Wines you want to buy' => 'Weine, die Sie kaufen möchten',
+ 'Links' => 'Links',
+ 'Your public links' => 'Ihre öffentlichen Links',
+ 'Dugg' => 'Gediggt',
+ 'Links you dugg' => 'Links, die Sie gediggt haben',
+ 'Submissions' => 'Eingereicht',
+ 'Links you submitted' => 'Links, die Sie eingereicht haben',
+ 'Found' => 'Gefunden',
+ 'Photos you found' => 'Fotos, die Sie gefunden haben',
+ 'Favorites' => 'Favoriten',
+ 'Photos you marked as favorites' => 'Fotos, die Sie als Favoriten gespeichert haben',
+ 'Photos' => 'Fotos',
+ 'Photos you posted' => 'Fotos, die Sie veröffentlicht haben',
+ 'Likes' => 'Gefallen',
+ 'Things from your friends that you "like"' => 'Veröffentlichungen Ihrer Freude, die Ihnen gefallen haben',
+ 'Leaderboard scores' => 'Leaderboard-Scores',
+ 'Your high scores in games with leaderboards' => 'Ihre High Scores in Leaderboard-Spielen',
+ 'Posts' => 'Einträge',
+ 'Blog posts about your search term' => 'Blog-Einträge zu Ihrem Suchbegriff',
+ 'Stories' => 'Nachrichten',
+ 'News Stories matching your search' => 'Nachrichten zu Ihrem Suchbegriff',
+ 'To read' => 'Zu lesen',
+ 'Books on your "to-read" shelf' => 'Bücher, die Sie noch lesen möchten',
+ 'Reading' => 'Aktuelle Lektüre',
+ 'Books on your "currently-reading" shelf' => 'Bücher, die Sie derzeit lesen',
+ 'Read' => 'Gelesen',
+ 'Books on your "read" shelf' => 'Bücher, die Sie bereits gelesen haben',
+ 'Shared' => 'Geteilt',
+ 'Your shared items' => 'Geteilte Artikel',
+ 'Deliveries' => 'Lieferungen',
+ 'Icon sets you were delivered' => 'Ihre gelieferten Icon-Gruppen',
+ 'Notices' => 'Hinweise',
+ 'Notices you posted' => 'Hinweise, die Sie veröffentlicht haben',
+ 'Intas' => 'Intas',
+ 'Links you saved' => 'Ihre veröffentlichten Links',
+ 'Photos you posted that were approved' => 'Fotos von Ihnen, die auf Zustimmung gestoÃen sind',
+ 'Recent events' => 'Aktuelle Ereignisse',
+ 'Events from your recent events feed' => 'Ereignisse von Ihrem Aktuelle Ereignisse-Feed',
+ 'Apps you use' => 'Anwendungen',
+ 'The applications you saved as ones you use' => 'Anwendungen, die Sie einsetzen',
+ 'Videos you saved as watched' => 'Videos, die Sie gesehen haben',
+ 'Jaikus' => 'Jaikus',
+ 'Jaikus you posted' => 'Ihre Jaikus',
+ 'Games you saved as favorites' => 'Spiele, die Sie als Favoriten gespeichert haben',
+ 'Achievements' => 'Erfolge',
+ 'Achievements you won' => 'Erfolge, die Sie erzielt haben',
+ 'Tracks' => 'Lieder',
+ 'Songs you recently listened to (High spam potential!)' => 'Lieder, die Sie kürzlich gehört haben (hohe Spam-Gefahr!)',
+ 'Loved Tracks' => 'Lieblingslieder',
+ 'Songs you marked as "loved"' => 'Ihre Lieblingslieder',
+ 'Journal Entries' => 'Tagebuch-Einträge',
+ 'Your recent journal entries' => 'Ihre aktuellen Tagebuch-Einträge',
+ 'Events' => 'Veranstaltungen',
+ 'The events you said you\'ll be attending' => 'Veranstaltungen, an denen Sie vorhaben teilzunehmen',
+ 'Your public posts to your journal' => 'Ihre öffentlichen Tagebuch-Einträge',
+ 'Queue' => 'Ausleihliste',
+ 'Movies you added to your rental queue' => 'Filme auf Ihrer Ausleihliste',
+ 'Recent Movies' => 'Aktuelle Filme',
+ 'Recent Rental Activity' => 'Kürzlich ausgeliehene Filme',
+ 'Kudos' => 'Kudos',
+ 'Kudos you have received' => 'Kudos, die Sie erhalten haben',
+ 'Favorite Songs' => 'Lieblings-Lieder',
+ 'Songs you marked as favorites' => 'Ihre Lieblings-Lieder',
+ 'Favorite Artists' => 'Lieblings-Musiker',
+ 'Artists you marked as favorites' => 'Ihre Lieblings-Musiker',
+ 'Stations' => 'Sender',
+ 'Radio stations you added' => 'Radiostationen, die Sie in Ihre Liste aufgenommen haben',
+ 'List' => 'Liste',
+ 'Things you put in your list' => 'Dinge auf Ihrer Liste',
+ 'Notes' => 'Notizen',
+ 'Your public notes' => 'Ihre öffentlichen Notizen',
+ 'Comments you posted' => 'Ihre Kommentare',
+ 'Articles you submitted' => 'Artikel, die Sie eingereicht haben',
+ 'Articles you liked (your votes must be public)' => 'Artikel, die Ihnen gefallen haben (bei öffentlicher Abstimmung)',
+ 'Dislikes' => 'Nicht gefallen',
+ 'Articles you disliked (your votes must be public)' => 'Artikel, die Ihnen nicht gefallen haben (bei öffentlicher Abstimmung)',
+ 'Slideshows you saved as favorites' => 'Slideshows, die Sie als Favoriten gespeichert haben',
+ 'Slideshows' => 'Slideshows',
+ 'Slideshows you posted' => 'Slideshows, die Sie veröffentlicht haben',
+ 'Your achievements for achievement-enabled games' => 'Ihre Achievements bei Spielen, die das Achievements-System unterstützen',
+ 'Stuff' => 'Sachen',
+ 'Things you posted' => 'Sachen, die Sie veröffentlicht haben',
+ 'Tweets' => 'Tweets',
+ 'Your public tweets' => 'Ihre öffentlichen Tweets',
+ 'Public tweets you saved as favorites' => 'Ãffentliche Tweets, die Sie als Ihre Favoriten gespeichert haben',
+ 'Tweets about your search term' => 'Tweets zu Ihren Suchbegriffen',
+ 'Saved' => 'Gespeichert',
+ 'Things you saved as favorites' => 'Dinge, die Sie als Favoriten gespeichert haben',
+ 'Events you are watching or attending' => 'Veranstaltungen, an denen Sie teilnehmen',
+ 'Videos you posted' => 'Videos, die Sie veröffentlicht haben',
+ 'Videos you liked' => 'Videos, die Ihnen gefallen haben',
+ 'Public assets you saved as favorites' => 'Ãffentliche Assets, die Sie als Favoriten gespeichert haben',
+ 'Your public photos in your Vox library' => 'Ihre öffentlichen Fotos in Ihrer Vox-Sammlung',
+ 'Your public posts to your Vox' => 'Ihre öffentlichen Einträge auf Vox',
+ 'The posts available from the website\'s feed' => 'Die im Feed der Website verfügbaren Einträge.',
+ 'Wists' => 'Wists',
+ 'Stuff you saved' => 'Sachen, die Sie gespeichert haben',
+ 'Gamerscore' => 'Gamerscore',
+ 'Notes when your gamerscore passes an even number' => 'Benachrichtigt Sie, wenn Ihr Gamerscore eine gerade Zahl überschritten wird',
+ 'Places you reviewed' => 'Orte, über die Sie Kritiken geschrieben haben',
+ 'Videos you saved as favorites' => 'Vidoes, die Sie als Favoriten gespeichert haben',
+
+## plugins/ActionStreams/services.yaml
+ '1up.com' => '1up.com',
+ '43Things' => '43Things',
+ 'Screen name' => 'Bildschirmname',
+ 'backtype' => 'backtype', # Translate - New # OK
+ 'Bebo' => 'Bebo',
+ 'Catster' => 'Catster',
+ 'COLOURlovers' => 'COLOURlovers',
+ 'Cork\'\'d\'' => 'Cork\'d',
+ 'Delicious' => 'Delicious',
+ 'Destructoid' => 'Destructoid',
+ 'Digg' => 'Digg',
+ 'Dodgeball' => 'Dodgeball',
+ 'Dogster' => 'Dogster',
+ 'Dopplr' => 'Dopplr',
+ 'Facebook' => 'Facebook',
+ 'User ID' => 'Benutzerkennung',
+ 'You can find your Facebook userid within your profile URL. For example, http://www.facebook.com/profile.php?id=24400320.' => 'Ihre Facebook-Benutzerkennung ist die Zahl in der Webadresse Ihres Profils; z.B. http://www.facebook.com/profile.php?id=24400320',
+ 'FFFFOUND!' => 'FFFFOUND!',
+ 'Flickr' => 'Flickr',
+ 'Enter your Flickr userid which contains "@" in it, e.g. 36381329@N00. Flickr userid is NOT the username in the URL of your photostream.' => 'Ihre Flickr-Benutzerkennung ist NICHT Ihr Benutzername, sondern der Teil der Webadresse Ihres Profils mit dem "@"-Zeichen; z.B. 36381329@N00',
+ 'FriendFeed' => 'FriendFeed',
+ 'Gametap' => 'Gametap',
+ 'Google Blogs' => 'Google Blogs',
+ 'Search term' => 'Suchbegriff',
+ 'Google News' => 'Google News',
+ 'Search for' => 'Suchen nach',
+ 'Goodreads' => 'Goodreads',
+ 'You can find your Goodreads userid within your profile URL. For example, http://www.goodreads.com/user/show/123456.' => 'Ihre Goodreads-Benutzerkennung ist die Zahl in der Webadresse Ihres Profils; z.B. http://www.goodreads.com/user/show/123456',
+ 'Google Reader' => 'Google Reader',
+ 'Sharing ID' => 'Sharing-ID',
+ 'Hi5' => 'Hi5',
+ 'IconBuffet' => 'IconBuffet',
+ 'ICQ' => 'ICQ',
+ 'UIN' => 'UIN',
+ 'Identi.ca' => 'Identi.ca',
+ 'Iminta' => 'Iminta',
+ 'iStockPhoto' => 'iStockPhoto',
+ 'You can find your istockphoto userid within your profile URL. For example, http://www.istockphoto.com/user_view.php?id=1234567.' => 'Ihre istockphoto-Benutzerkennung ist die Zahl in der Webadresse Ihres Profils; z.B. http://www.istockphoto.com/user_view.php?id=1234567',
+ 'IUseThis' => 'IUseThis',
+ 'iwatchthis' => 'iwatchthis',
+ 'Jabber' => 'Jabber',
+ 'Jabber ID' => 'Jabber-ID',
+ 'Jaiku' => 'Jaiku',
+ 'Kongregate' => 'Kongregate',
+ 'Last.fm' => 'Last.fm',
+ 'LinkedIn' => 'LinkedIn',
+ 'Profile URL' => 'Profil-URL',
+ 'Ma.gnolia' => 'Ma.gnolia',
+ 'MOG' => 'MOG',
+ 'MSN Messenger\'' => 'MSN Messenger',
+ 'Multiply' => 'Multiply',
+ 'MySpace' => 'MySpace',
+ 'Netflix' => 'Netflix',
+ 'Netflix RSS ID' => 'Netflix RSS-ID',
+ 'To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.' => 'Ihre Netflix RSS-ID finden Sie, indem Sie auf einer beliebigen Netflix-Seite unten auf "RSS" klicken und dann den "Queue"-Link koppieren',
+ 'Netvibes' => 'Netvibes',
+ 'Newsvine' => 'Newsvine',
+ 'Ning' => 'Ning',
+ 'Social Network URL' => 'Social Network-URL',
+ 'Ohloh' => 'Ohloh',
+ 'Orkut' => 'Orkut',
+ 'You can find your orkut uid within your profile URL. For example, http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789' => 'Ihre Orkut-Benutzerkennung ist die Zahl in der Webadresse Ihres Profils nach "uid="; z.B. http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789',
+ 'Pandora' => 'Pandora',
+ 'Picasa Web Albums' => 'Picasa Web-Alben',
+ 'p0pulist' => 'p0pulist',
+ 'You can find your p0pulist user id within your Hot List URL. for example, http://p0pulist.com/list/hot_list/10000' => 'Ihre p0pulist-Benutzerkennung ist die Zahl in der Webadresse Ihres Profil; z.B. http://p0pulist.com/list/hot_list/10000',
+ 'Pownce' => 'Pownce',
+ 'Reddit' => 'Reddit',
+ 'Skype' => 'Skype',
+ 'SlideShare' => 'SlideShare',
+ 'Smugmug' => 'Smugmug',
+ 'SonicLiving' => 'SonicLiving',
+ 'You can find your SonicLiving userid within your share&subscribe URL. For example, http://sonicliving.com/user/12345/feeds' => 'Ihre SonicLiving-Benutzerkennung ist die Zahl in der Webadresse Ihrer Share&Subscribe-Seite; z.B. http://sonicliving.com/user/12345/feeds',
+ 'Steam' => 'Steam',
+ 'StumbleUpon' => 'StumbleUpon',
+ 'Tabblo' => 'Tabblo',
+ 'Blank should be replaced by positive sign (+).' => 'Verwenden Sie statt Leerzeichen Pluszeichen (+)',
+ 'Tribe' => 'Tribe',
+ 'You can find your tribe userid within your profile URL. For example, http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a.' => 'Ihre Tribe-Benutzerkennung ist die Zahl in der Webadresse Ihres Profils; z.B. http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a',
+ 'Tumblr' => 'Tumblr',
+ 'Twitter' => 'Twitter',
+ 'TwitterSearch' => 'TwitterSearch',
+ 'Uncrate' => 'Uncrate',
+ 'Upcoming' => 'Upcoming',
+ 'Viddler' => 'Viddler',
+ 'Vimeo' => 'Vimeo',
+ 'Virb' => 'Virb',
+ 'You can find your VIRB userid within your home URL. For example, http://www.virb.com/backend/2756504321310091/your_home.' => 'Ihre Virb-Benutzerkennung ist die Zahl in der Webadresse Ihrer Startseite; z.B. http://www.virb.com/backend/2756504321310091/your_home',
+ 'Vox name' => 'Vox-Name',
+ 'Website' => 'Website',
+ 'Xbox Live\'' => 'Xbox Live',
+ 'Gamertag' => 'Gamertag',
+ 'Yahoo! Messenger\'' => 'Yahoo! Messenger',
+ 'Yelp' => 'Yelp',
+ 'YouTube' => 'YouTube',
+ 'Zooomr' => 'Zooomr',
+
+## plugins/ActionStreams/config.yaml
+ 'Manages authors\' accounts and actions on sites elsewhere around the web' => 'Verwaltet die Benutzerkonten und Ereignisse des Autors auf anderen Websites',
+ 'Are you sure you want to hide EVERY event in EVERY action stream?' => 'Wirklich ALLE Ereignisse in ALLEN Action Streams verstecken?',
+ 'Are you sure you want to show EVERY event in EVERY action stream?' => 'Wirklich ALLE Ereignisse in ALLEN Action Streams anzeigen?',
+ 'Deleted events that are still available from the remote service will be added back in the next scan. Only events that are no longer available from your profile will remain deleted. Are you sure you want to delete the selected event(s)?' => 'Gelöschte Ereignisse, die bei dem jeweiligen Web-Dienst noch aufgeführt sind, werden bei der nächsten Aktualisierung wieder hinzugefügt. Gelöscht werden nur Ereignisse, die nicht mehr in Ihrem Profil verfügbar sind. Gewählte Ereignisse wirklich löschen?',
+ 'Hide All' => 'Alle verbergen',
+ 'Show All' => 'Alle zeigen',
+ 'Poll for new events' => 'Auf neue Ereignisse abfragen',
+ 'Update Events' => 'Ereignisse aktualisieren',
+ 'Action Stream' => 'Action Streams',
+ 'Main Index (Recent Actions)' => 'Startseite (aktuelle Aktionen)',
+ 'Action Archive' => 'Aktions-Archiv',
+ 'Feed - Recent Activity' => 'Feed - Aktuelle Aktivitäten',
+ 'Find Authors Elsewhere' => 'Autoren anderswo finden',
+ 'Enabling default action streams for selected profiles...' => 'Aktiviere Standard-Action Streams für die gewählten Profile...',
+
+## plugins/ActionStreams/lib/ActionStreams/Upgrade.pm
+ 'Updating classification of [_1] [_2] actions...' => 'Aktualisiere Klassifizierungen von [_1] [_2]-Aktionen',
+ 'Renaming "[_1]" data of [_2] [_3] actions...' => 'Benenne "[_1]"-Daten von [_2] [_3]-Aktionen um...',
+
+## plugins/ActionStreams/lib/ActionStreams/Worker.pm
+ 'No such author with ID [_1]' => 'Kein solcher Autor mit ID [_1]',
+
+## plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+ 'Other Profiles' => 'Andere Profile',
+ 'Profiles' => 'Profile',
+ 'Actions from the service [_1]' => 'Aktionen bei [_1]',
+ 'Actions that are shown' => 'Angezeigte Ereignisse',
+ 'Actions that are hidden' => 'Versteckte Ereignisse',
+ 'No such event [_1]' => 'Kein solches Ereignis [_1]',
+ '[_1] Profile' => '[_1] Profil',
+
+## plugins/ActionStreams/lib/ActionStreams/Tags.pm
+ 'No user [_1]' => 'Kein Benutzer [_1]',
+
+## plugins/ActionStreams/lib/ActionStreams/Event.pm
+ '[_1] updating [_2] events for [_3]' => '[_1] aktualisiert [_2]-Ereignisse für [_3]',
+ 'Error updating events for [_1]\'s [_2] stream (type [_3] ident [_4]): [_5]' => 'Fehler bei der Aktualisierung der Ereignisse für [_1]s [_2]-Stream (Typ [_3], Ident [_4]): [_5]',
+ 'Could not load class [_1] for stream [_2] [_3]: [_4]' => 'Konnte Klasse [_1] für Stream [_2] [_3] nicht laden: [_4]',
+ 'No URL to fetch for [_1] results' => 'Keine URL zum Einlesen von [_1]-Ergebnissen', # Translate - New # OK
+ 'Could not fetch [_1]: [_2]' => '[_1] konnte nicht einlesen gewerden: [_2]', # Translate - New # OK
+ 'Aborted fetching [_1]: [_2]' => 'Einlesen von [_1] abgebrochen: [_2]', # Translate - New # OK
+
+## plugins/ActionStreams/tmpl/dialog_edit_profile.tmpl
+ 'Your user name or ID is required.' => 'Ihr Benutzername oder Ihre ID ist erforderlich.',
+ 'Edit a profile on a social networking or instant messaging service.' => 'Bearbeiten Sie Ihr Profil bei einem Social Network oder Instant Messaging-Dienst.',
+ 'Service' => 'Dienst',
+ 'Enter your account on the selected service.' => 'Geben Sie Ihren Benutzernamen beim gewählten Dienst ein.',
+ 'For example:' => 'Beispiel:',
+ 'Action Streams' => 'Action Streams:',
+ 'Select the action streams to collect from the selected service.' => 'Wählen Sie, welche Action Streams beim gewählten Dienst abgefragt werden sollen.',
+ 'No streams are available for this service.' => 'Für diesen Dienst sind keine Action Streams verfügbar.',
+
+## plugins/ActionStreams/tmpl/other_profiles.tmpl
+ 'The selected profile was added.' => 'Gewähltes Profil hinzugefügt.',
+ 'The selected profiles were removed.' => 'Gewählte Profile entfernt.',
+ 'The selected profiles were scanned for updates.' => 'Gewählte Profile auf Aktualisierungen überprüft.',
+ 'The changes to the profile have been saved.' => 'Profiländerungen gespeichert.',
+ 'Add Profile' => 'Profil hinzufügen',
+ 'profile' => 'Profil',
+ 'profiles' => 'Profile',
+ 'Delete selected profiles (x)' => 'Gewählte Profile löschen (x)',
+ 'to update' => 'zu aktualisieren',
+ 'Scan now for new actions' => 'Jetzt auf neue Aktionen überprüfen',
+ 'Update Now' => 'Jetzt aktualisieren',
+ 'No profiles were found.' => 'Keine Profile gefunden.',
+ 'external_link_target' => 'external_link_target',
+ 'View Profile' => 'Proil ansehen',
+
+## plugins/ActionStreams/tmpl/dialog_add_profile.tmpl
+ 'Add a profile on a social networking or instant messaging service.' => 'Profil bei einem Social Network oder Instant Messaging-Dienst hinzufügen',
+ 'Select a service where you already have an account.' => 'Wählen Sie einen Dienst, bei dem Sie bereits ein Benutzerkonto haben.',
+ 'Add Profile (s)' => 'Profil hinzufügen (s)', # Translate - New # OK
+
+## plugins/ActionStreams/tmpl/list_profileevent.tmpl
+ 'The selected events were deleted.' => 'Die gewählten Ereignisse wurden gelöscht.',
+ 'The selected events were hidden.' => 'Die gewählten Ereignisse werden verborgen.',
+ 'The selected events were shown.' => 'Die gewählten Ereignisse werden angezeigt.',
+ 'All action stream events were hidden.' => 'Die Action Stream-Ereignisse werden verborgen.',
+ 'All action stream events were shown.' => 'Alle Action Stream-Ereignisse werden angezeigt.',
+ 'event' => 'Ereignis',
+ 'events' => 'Ereignisse',
+ 'Hide selected events (h)' => 'Gewählte Ereignisse verbergen (h)',
+ 'Hide' => 'Verbergen',
+ 'Show selected events (h)' => 'Gewählte Ereignisse anzeigen (h)',
+ 'Show' => 'Anzeigen',
+ 'All stream actions' => 'Alle Ereignisse des Streams',
+ 'Show only actions where' => 'Nur Ereignisse zeigen',
+ 'service' => 'bei Dienst',
+ 'visibility' => 'mit Sichtbarkeit',
+ 'hidden' => 'versteckt',
+ 'shown' => 'sichtbar',
+ 'No events could be found.' => 'Keine Ereignisse gefunden',
+ 'Event' => 'Ereignis',
+ 'Shown' => 'Angezeigt',
+ 'Hidden' => 'Verborgen',
+ 'View action link' => 'Action Link anzeigen',
+
+## plugins/ActionStreams/tmpl/widget_recent.mtml
+ 'Your Recent Actions' => 'Ihre aktuellen Aktionen',
+ 'blog this' => 'Diese Sache bloggen',
+
+## plugins/ActionStreams/tmpl/blog_config_template.tmpl
+ 'Rebuild Indexes' => 'Indizes neu aufbauen',
+ 'If selected, this blog\'s indexes will be rebuilt when new action stream events are discovered.' => 'Falls aktiviert, werden die Indizes dieses Blogs neu aufgebaut, wenn neue Action Stream-Ereignisse eintreffen',
+ 'Enable rebuilding' => 'Neuaufbau aktivieren',
+
+);
+
+1;
diff --git a/plugins/ActionStreams/lib/ActionStreams/L10N/en_us.pm b/plugins/ActionStreams/lib/ActionStreams/L10N/en_us.pm
new file mode 100644
index 0000000..8c80ac7
--- /dev/null
+++ b/plugins/ActionStreams/lib/ActionStreams/L10N/en_us.pm
@@ -0,0 +1,14 @@
+# Movable Type (r) (C) 2001-2008 Six Apart, Ltd. All Rights Reserved.
+# This code cannot be redistributed without permission from www.sixapart.com.
+# For more information, consult your Movable Type license.
+#
+# $Id: $
+
+package ActionStreams::L10N::en_us;
+
+use strict;
+use base 'ActionStreams::L10N';
+use vars qw( %Lexicon );
+%Lexicon = ();
+
+1;
diff --git a/plugins/ActionStreams/lib/ActionStreams/L10N/es.pm b/plugins/ActionStreams/lib/ActionStreams/L10N/es.pm
new file mode 100644
index 0000000..6f21cf2
--- /dev/null
+++ b/plugins/ActionStreams/lib/ActionStreams/L10N/es.pm
@@ -0,0 +1,354 @@
+# Movable Type (r) (C) 2001-2008 Six Apart, Ltd. All Rights Reserved.
+# This code cannot be redistributed without permission from www.sixapart.com.
+# For more information, consult your Movable Type license.
+#
+# $Id: es.pm 99820 2009-03-09 13:55:28Z mschenk $
+
+package ActionStreams::L10N::es;
+
+use strict;
+use base 'ActionStreams::L10N::en_us';
+use vars qw( %Lexicon );
+%Lexicon = (
+
+## plugins/ActionStreams/blog_tmpl/sidebar.mtml
+
+## plugins/ActionStreams/blog_tmpl/main_index.mtml
+
+## plugins/ActionStreams/blog_tmpl/actions.mtml
+ 'Recent Actions' => 'Acciones recientes',
+
+## plugins/ActionStreams/blog_tmpl/archive.mtml
+
+## plugins/ActionStreams/blog_tmpl/banner_footer.mtml
+
+## plugins/ActionStreams/blog_tmpl/elsewhere.mtml
+ 'Find [_1] Elsewhere' => 'Buscar [_1] en otro sitio',
+
+## plugins/ActionStreams/streams.yaml
+ 'Currently Playing' => 'Juegos recientes',
+ 'The games in your collection you\'re currently playing' => 'Juegos de su colección a los que esté jugando actualmente',
+ 'Comments you have made on the web' => 'Comentarios que ha realizado en el web',
+ 'Colors' => 'Colores',
+ 'Colors you saved' => 'Colores que ha guardado',
+ 'Palettes' => 'Paletas',
+ 'Palettes you saved' => 'Paletas que ha guardado',
+ 'Patterns' => 'Patrones',
+ 'Patterns you saved' => 'Patrones que ha guardado',
+ 'Favorite Palettes' => 'Paletas favoritas',
+ 'Palettes you saved as favorites' => 'Paletas que ha guardado como favoritas',
+ 'Reviews' => 'Reseñas',
+ 'Your wine reviews' => 'Reseñas de vino que ha realizado',
+ 'Cellar' => 'Bodega',
+ 'Wines you own' => 'Vinos que posee',
+ 'Shopping List' => 'Lista de compras',
+ 'Wines you want to buy' => 'Vinos que desea comprar',
+ 'Links' => 'Enlaces',
+ 'Your public links' => 'Sus enlaces públicos',
+ 'Dugg' => 'Dugg',
+ 'Links you dugg' => 'Enlaces que ha enviado a digg',
+ 'Submissions' => 'EnvÃos',
+ 'Links you submitted' => 'Enlaces que ha enviado',
+ 'Found' => 'Encontrado',
+ 'Photos you found' => 'Fotos que ha encontrado',
+ 'Favorites' => 'Favoritos',
+ 'Photos you marked as favorites' => 'Fotos que ha marcado como favoritas',
+ 'Photos' => 'Fotos',
+ 'Photos you posted' => 'Fotos que ha publicado',
+ 'Likes' => 'Gustos',
+ 'Things from your friends that you "like"' => 'Cosas de sus amigos que le gustan',
+ 'Leaderboard scores' => 'Máximas puntuaciones',
+ 'Your high scores in games with leaderboards' => 'Sus puntuaciones máximas en los juegos con ránking',
+ 'Posts' => 'Entradas',
+ 'Blog posts about your search term' => 'Entradas en los blogs con el término buscado',
+ 'Stories' => 'Noticias',
+ 'News Stories matching your search' => 'Noticias con el término buscado',
+ 'To read' => 'Para leer',
+ 'Books on your "to-read" shelf' => 'Libros para leer',
+ 'Reading' => 'Leyendo',
+ 'Books on your "currently-reading" shelf' => 'Libros que actualmente está leyendo',
+ 'Read' => 'Lecturas',
+ 'Books on your "read" shelf' => 'Libros pendientes de lectura',
+ 'Shared' => 'Compartidos',
+ 'Your shared items' => 'Elementos compartidos',
+ 'Deliveries' => 'EnvÃos',
+ 'Icon sets you were delivered' => 'Conjuntos de iconos que ha enviado',
+ 'Notices' => 'Notas',
+ 'Notices you posted' => 'Notas que ha publicado',
+ 'Intas' => 'Intas',
+ 'Links you saved' => 'Enlaces que ha guardado',
+ 'Photos you posted that were approved' => 'Fotos que ha publicado y han sido aprobadas',
+ 'Recent events' => 'Eventos recientes',
+ 'Events from your recent events feed' => 'Eventos de su fuente de sindicación de eventos',
+ 'Apps you use' => 'Aplicaciones que usa',
+ 'The applications you saved as ones you use' => 'Aplicaciones que ha indicado que usa',
+ 'Videos you saved as watched' => 'VÃdeos que ha guardado como vistos',
+ 'Jaikus' => 'Jaikus',
+ 'Jaikus you posted' => 'Jaikus que ha publicado',
+ 'Games you saved as favorites' => 'Juegos que ha guardado como favoritos',
+ 'Achievements' => 'Logros',
+ 'Achievements you won' => 'Ãxitos que ha realizado',
+ 'Tracks' => 'Canciones',
+ 'Songs you recently listened to (High spam potential!)' => 'Canciones que escuchado recientemente (¡alto potencial de spam!)',
+ 'Loved Tracks' => 'Canciones favoritas',
+ 'Songs you marked as "loved"' => 'Canciones que ha seleccionado como favoritas',
+ 'Journal Entries' => 'Entradas del diario',
+ 'Your recent journal entries' => 'Las entradas recientes en su diario',
+ 'Events' => 'Eventos',
+ 'The events you said you\'ll be attending' => 'Eventos a los que confirmó su asistencia',
+ 'Your public posts to your journal' => 'Entradas públicas en su diario',
+ 'Queue' => 'Cola',
+ 'Movies you added to your rental queue' => 'PelÃculas que ha añadido a la lista de pendientes por alquilar',
+ 'Recent Movies' => 'PelÃculas rcientes',
+ 'Recent Rental Activity' => 'Actividad reciente de alquiler',
+ 'Kudos' => 'Felicitaciones',
+ 'Kudos you have received' => 'Felicitaciones que ha recibido',
+ 'Favorite Songs' => 'Canciones favoritas',
+ 'Songs you marked as favorites' => 'Canciones que ha seleccionado como favoritas',
+ 'Favorite Artists' => 'Artistas favoritos',
+ 'Artists you marked as favorites' => 'Artistas que ha marcado como favoritos',
+ 'Stations' => 'Estaciones',
+ 'Radio stations you added' => 'Estaciones de radio que ha añadido',
+ 'List' => 'Lista',
+ 'Things you put in your list' => 'Elementos que ha añadido a su lista',
+ 'Notes' => 'Notas',
+ 'Your public notes' => 'Sus notas públicas',
+ 'Comments you posted' => 'Comentarios que ha publicado',
+ 'Articles you submitted' => 'ArtÃculos que ha escrito',
+ 'Articles you liked (your votes must be public)' => 'ArtÃculos que le han gustado (los votos debe ser públicos)',
+ 'Dislikes' => 'No recomendable',
+ 'Articles you disliked (your votes must be public)' => 'ArtÃculos que no lo han gustado (los votos deben ser públicos)',
+ 'Slideshows you saved as favorites' => 'Presentaciones que ha guardado como favoritas',
+ 'Slideshows' => 'Presentaciones',
+ 'Slideshows you posted' => 'Presentaciones que ha publicado',
+ 'Your achievements for achievement-enabled games' => 'Logros que ha conseguidos en juegos con fases',
+ 'Stuff' => 'Cosas',
+ 'Things you posted' => 'Cosas que ha publicado',
+ 'Tweets' => 'Tweets',
+ 'Your public tweets' => 'Sus envÃos a twitter',
+ 'Public tweets you saved as favorites' => 'EnvÃos a twitter que ha marcado como favoritos',
+ 'Tweets about your search term' => 'EnvÃos a twitter que coinciden con la búsqueda',
+ 'Saved' => 'Guardado',
+ 'Things you saved as favorites' => 'Cosas que ha guardado como favoritos',
+ 'Events you are watching or attending' => 'Eventos que está presenciando',
+ 'Videos you posted' => 'VÃdeos que ha publicado',
+ 'Videos you liked' => 'VÃdeos que le han gustado',
+ 'Public assets you saved as favorites' => 'Elementos públicos que ha guardado como favoritos',
+ 'Your public photos in your Vox library' => 'Sus fotos públicas en la librerÃa de Vox',
+ 'Your public posts to your Vox' => 'Sus entradas públicas en Vox',
+ 'The posts available from the website\'s feed' => 'Las entradas disponibles en la sindicación del web',
+ 'Wists' => 'Wists',
+ 'Stuff you saved' => 'Cosas que ha guardado',
+ 'Gamerscore' => 'Puntuaciones',
+ 'Notes when your gamerscore passes an even number' => 'Anotaciones de cuando su puntuación en los juegos pasan algún número concreto',
+ 'Places you reviewed' => 'Lugares reseñados',
+ 'Videos you saved as favorites' => 'VÃdeos guardados como favoritos',
+
+## plugins/ActionStreams/services.yaml
+ '1up.com' => '1up.com',
+ '43Things' => '43Things',
+ 'Screen name' => 'Usuario',
+ 'backtype' => 'backtype',
+ 'Bebo' => 'Bebo',
+ 'Catster' => 'Catster',
+ 'COLOURlovers' => 'COLOURlovers',
+ 'Cork\'\'d\'' => 'Cork\'\'d\'',
+ 'Delicious' => 'Delicious',
+ 'Destructoid' => 'Destructoid',
+ 'Digg' => 'Digg',
+ 'Dodgeball' => 'Dodgeball',
+ 'Dogster' => 'Dogster',
+ 'Dopplr' => 'Dopplr',
+ 'Facebook' => 'Facebook',
+ 'User ID' => 'ID de usuario',
+ 'You can find your Facebook userid within your profile URL. For example, http://www.facebook.com/profile.php?id=24400320.' => 'Puede encontrar el ID de Facebook en la URL de su perfil. Por ejemplo, http://www.facebook.com/profile.php?id=24400320.',
+ 'FFFFOUND!' => 'FFFFOUND!',
+ 'Flickr' => 'Flickr',
+ 'Enter your Flickr userid which contains "@" in it, e.g. 36381329@N00. Flickr userid is NOT the username in the URL of your photostream.' => 'Introduzca el identificador de usuario de Flickr, que contiene una "@", p.e. 36381329@N00. El identificador NO es el nombre de usuario en la URL de la galerÃa.',
+ 'FriendFeed' => 'FriendFeed',
+ 'Gametap' => 'Gametap',
+ 'Google Blogs' => 'Google Blogs',
+ 'Search term' => 'Buscar palabra',
+ 'Google News' => 'Google News',
+ 'Search for' => 'Buscar',
+ 'Goodreads' => 'Goodreads',
+ 'You can find your Goodreads userid within your profile URL. For example, http://www.goodreads.com/user/show/123456.' => 'Puede encontrar el identificador de usuario de Gooreads en la URL del perfil. Por ejemplo, http://www.goodreads.com/user/show/123456.',
+ 'Google Reader' => 'Google Reader',
+ 'Sharing ID' => 'Sharing ID',
+ 'Hi5' => 'Hi5',
+ 'IconBuffet' => 'IconBuffet',
+ 'ICQ' => 'ICQ',
+ 'UIN' => 'UIN',
+ 'Identi.ca' => 'Identi.ca',
+ 'Iminta' => 'Iminta',
+ 'iStockPhoto' => 'iStockPhoto',
+ 'You can find your istockphoto userid within your profile URL. For example, http://www.istockphoto.com/user_view.php?id=1234567.' => 'Puede encontrar el identificador de usuario en la URL del perfil. Por ejemplo, http://www.istockphoto.com/user_view.php?id=1234567.',
+ 'IUseThis' => 'IUseThis',
+ 'iwatchthis' => 'iwatchthis',
+ 'Jabber' => 'Jabber',
+ 'Jabber ID' => 'ID de Jabber',
+ 'Jaiku' => 'Jaiku',
+ 'Kongregate' => 'Kongregate',
+ 'Last.fm' => 'Last.fm',
+ 'LinkedIn' => 'LinkedIn',
+ 'Profile URL' => 'URL del perfil',
+ 'Ma.gnolia' => 'Ma.gnolia',
+ 'MOG' => 'MOG',
+ 'MSN Messenger\'' => 'MSN Messenger\'',
+ 'Multiply' => 'Multiply',
+ 'MySpace' => 'MySpace',
+ 'Netflix' => 'Netflix',
+ 'Netflix RSS ID' => 'Netflix RSS ID',
+ 'To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.' => 'Para encontrar su ID de RSS de Netflix, haga clic en "RSS" al pie de cualquier página del sitio de Netflix, y copie y pegue el enlace "Queue".',
+ 'Netvibes' => 'Netvibes',
+ 'Newsvine' => 'Newsvine',
+ 'Ning' => 'Ning',
+ 'Social Network URL' => 'URL de la red social',
+ 'Ohloh' => 'Ohloh',
+ 'Orkut' => 'Orkut',
+ 'You can find your orkut uid within your profile URL. For example, http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789' => 'Puede encontrar el identificador de usuario de orkut en la URL del perfil. Por ejemplo, http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789',
+ 'Pandora' => 'Pandora',
+ 'Picasa Web Albums' => 'Ãlbumes de Picasa',
+ 'p0pulist' => 'p0pulist',
+ 'You can find your p0pulist user id within your Hot List URL. for example, http://p0pulist.com/list/hot_list/10000' => 'Puede encontrar el identificador de usuario de p0pulist en la URL de la lista de éxitos. Por ejemplo, http://p0pulist.com/list/hot_list/10000',
+ 'Pownce' => 'Pownce',
+ 'Reddit' => 'Reddit',
+ 'Skype' => 'Skype',
+ 'SlideShare' => 'SlideShare',
+ 'Smugmug' => 'Smugmug',
+ 'SonicLiving' => 'SonicLiving',
+ 'You can find your SonicLiving userid within your share&subscribe URL. For example, http://sonicliving.com/user/12345/feeds' => 'Puede encontrar el identificador de usuario de SonicLiving en la URL de compartir y suscribir. Por ejemplo, http://sonicliving.com/user/12345/feeds',
+ 'Steam' => 'Steam',
+ 'StumbleUpon' => 'StumbleUpon',
+ 'Tabblo' => 'Tabblo',
+ 'Blank should be replaced by positive sign (+).' => 'El espacio se reemplazará con el signo positivo (+).',
+ 'Tribe' => 'Tribe',
+ 'You can find your tribe userid within your profile URL. For example, http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a.' => 'Puede encontrar el identificador de usuario de tribe en la URL del perfil. Por ejemplo, http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a.',
+ 'Tumblr' => 'Tumblr',
+ 'Twitter' => 'Twitter',
+ 'TwitterSearch' => 'TwitterSearch',
+ 'Uncrate' => 'Uncrate',
+ 'Upcoming' => 'Upcoming',
+ 'Viddler' => 'Viddler',
+ 'Vimeo' => 'Vimeo',
+ 'Virb' => 'Virb',
+ 'You can find your VIRB userid within your home URL. For example, http://www.virb.com/backend/2756504321310091/your_home.' => 'Puede encontrar el identificador de usuario de VIRB en la URL de inicio. Por ejemplo, http://www.virb.com/backend/2756504321310091/your_home.',
+ 'Vox name' => 'Usuario de Vox',
+ 'Website' => 'Website',
+ 'Xbox Live\'' => 'Xbox Live\'',
+ 'Gamertag' => 'Gamertag',
+ 'Yahoo! Messenger\'' => 'Yahoo! Messenger\'',
+ 'Yelp' => 'Yelp',
+ 'YouTube' => 'YouTube',
+ 'Zooomr' => 'Zooomr',
+
+## plugins/ActionStreams/config.yaml
+ 'Manages authors\' accounts and actions on sites elsewhere around the web' => 'Administra la cuenta de los autores y acciones en los sitios externos',
+ 'Are you sure you want to hide EVERY event in EVERY action stream?' => '¿Está seguro de que desea ocultar TODOS los eventos de TODOS los torrentes de acciones?',
+ 'Are you sure you want to show EVERY event in EVERY action stream?' => '¿Está seguro de que desea mostrar TODOS los eentos de TODOS los torrentes de acciones?',
+ 'Deleted events that are still available from the remote service will be added back in the next scan. Only events that are no longer available from your profile will remain deleted. Are you sure you want to delete the selected event(s)?' => 'Los eventos eliminados que aún están disponibles en el servicio remoto se volverán a añadir en la siguiente consulta. Solo los eventos que ya no estén disponibles en el perfil permanecerán eliminados. ¿Está seguro de que desea borrar los eventos seleccionados?',
+ 'Hide All' => 'Ocultar todo',
+ 'Show All' => 'Mostrar todo',
+ 'Poll for new events' => 'Buscar nuevos eventos',
+ 'Update Events' => 'Actualizar eventos',
+ 'Action Stream' => 'Torrente de acciones',
+ 'Main Index (Recent Actions)' => 'Ãndice principal (acciones recientes)',
+ 'Action Archive' => 'Archivo de acciones',
+ 'Feed - Recent Activity' => 'Sindicación - Actividad reciente',
+ 'Find Authors Elsewhere' => 'Buscar autores en otros sitios',
+ 'Enabling default action streams for selected profiles...' => 'Activando los torrentes de acciones predefinidos para los perfiles seleccionados...',
+
+## plugins/ActionStreams/lib/ActionStreams/Upgrade.pm
+ 'Updating classification of [_1] [_2] actions...' => 'Actualizando la clasificación de [_1] [_2] acciones...',
+ 'Renaming "[_1]" data of [_2] [_3] actions...' => 'Renombrando los datos de "[_1]" de [_2] [_3] acciones...',
+
+## plugins/ActionStreams/lib/ActionStreams/Worker.pm
+ 'No such author with ID [_1]' => 'No existe un autor con el ID [_1]',
+
+## plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+ 'Other Profiles' => 'Otros perfiles',
+ 'Profiles' => 'perfiles',
+ 'Actions from the service [_1]' => 'Acciones del servicio [_1]',
+ 'Actions that are shown' => 'Acciones mostradas',
+ 'Actions that are hidden' => 'Acciones ocultas',
+ 'No such event [_1]' => 'No existe el evento [_1]',
+ '[_1] Profile' => 'Perfil de [_1]',
+
+## plugins/ActionStreams/lib/ActionStreams/Tags.pm
+ 'No user [_1]' => 'No existe el usuario [_1]',
+
+## plugins/ActionStreams/lib/ActionStreams/Event.pm
+ '[_1] updating [_2] events for [_3]' => '[_1] actualizando [_2] eventos para [_3]',
+ 'Error updating events for [_1]\'s [_2] stream (type [_3] ident [_4]): [_5]' => 'Error actualizando eventos para el torrente [_2] de [_1] (tipo [_3] ident [_4]): [_5]',
+ 'Could not load class [_1] for stream [_2] [_3]: [_4]' => 'No se pudo cargar la clase [_1] del torrente [_2] [_3]: [_4]',
+ 'No URL to fetch for [_1] results' => 'Sin URL para obtener resultados de [_1]', # Translate - New
+ 'Could not fetch [_1]: [_2]' => 'No se pudo obtener [_1]: [_2]', # Translate - New
+ 'Aborted fetching [_1]: [_2]' => 'Se abortó durante la obtención de [_1]: [_2]', # Translate - New
+
+## plugins/ActionStreams/tmpl/dialog_edit_profile.tmpl
+ 'Your user name or ID is required.' => 'El usuario o el ID es obligatorio.',
+ 'Edit a profile on a social networking or instant messaging service.' => 'Editar un perfil en una red social o servicio de mensajarÃa instantánea.',
+ 'Service' => 'Servicio',
+ 'Enter your account on the selected service.' => 'Introduzca su cuenta en el servicio seleccionado.',
+ 'For example:' => 'Por ejemplo:',
+ 'Action Streams' => 'Torrente de acciones',
+ 'Select the action streams to collect from the selected service.' => 'Seleccione el torrente de acciones para obtenerlos del servicio elegido.',
+ 'No streams are available for this service.' => 'No hay torrentes disponibles para este servicio.',
+
+## plugins/ActionStreams/tmpl/other_profiles.tmpl
+ 'The selected profile was added.' => 'Se añadió el perfil seleccionado.',
+ 'The selected profiles were removed.' => 'Se borraron los perfiles seleccionados.',
+ 'The selected profiles were scanned for updates.' => 'Se escanearon las actualizaciones de los perfiles seleccionados.',
+ 'The changes to the profile have been saved.' => 'Se han guardado los cambios al perfil.',
+ 'Add Profile' => 'Añadir perfil',
+ 'profile' => 'Perfil',
+ 'profiles' => 'perfiles',
+ 'Delete selected profiles (x)' => 'Borrar los perfiles seleccionados (x)',
+ 'to update' => 'para actualizar',
+ 'Scan now for new actions' => 'Buscar nuevas acciones',
+ 'Update Now' => 'Actualizar ahora',
+ 'No profiles were found.' => 'No se encontraron perfiles.',
+ 'external_link_target' => 'external_link_target',
+ 'View Profile' => 'Ver perfil',
+
+## plugins/ActionStreams/tmpl/dialog_add_profile.tmpl
+ 'Add a profile on a social networking or instant messaging service.' => 'Añadir un perfil de una red social o servicio de mensajerÃa instantánea.',
+ 'Select a service where you already have an account.' => 'Seleccione un servicio donde ya tenga una cuenta.',
+ 'Add Profile (s)' => 'Añadir perfil (s)', # Translate - New
+
+## plugins/ActionStreams/tmpl/list_profileevent.tmpl
+ 'The selected events were deleted.' => 'Se borraron los eventos seleccionados.',
+ 'The selected events were hidden.' => 'Se ocultaron los eventos seleccionados.',
+ 'The selected events were shown.' => 'Se mostraron los eventos seleccionados.',
+ 'All action stream events were hidden.' => 'Se ocultaron todos los torrentes de acciones.',
+ 'All action stream events were shown.' => 'Se mostraron todos los torrentes de acciones.',
+ 'event' => 'evento',
+ 'events' => 'eventos',
+ 'Hide selected events (h)' => 'Ocultar eventos seleccionados (h)',
+ 'Hide' => 'Ocultar',
+ 'Show selected events (h)' => 'Mostrar eventos seleccionados (h)',
+ 'Show' => 'Mostrar',
+ 'All stream actions' => 'Todas las acciones',
+ 'Show only actions where' => 'Mostrar solo acciones donde',
+ 'service' => 'Servicio',
+ 'visibility' => 'visibilidad',
+ 'hidden' => 'Oculto',
+ 'shown' => 'Mostrado',
+ 'No events could be found.' => 'No se encontró ningún evento.',
+ 'Event' => 'Evento',
+ 'Shown' => 'Mostrado',
+ 'Hidden' => 'Oculto',
+ 'View action link' => 'Ver enlace de la acción',
+
+## plugins/ActionStreams/tmpl/widget_recent.mtml
+ 'Your Recent Actions' => 'Sus acciones recientes',
+ 'blog this' => 'bloguear esto',
+
+## plugins/ActionStreams/tmpl/blog_config_template.tmpl
+ 'Rebuild Indexes' => 'Reconstruir Ãndices',
+ 'If selected, this blog\'s indexes will be rebuilt when new action stream events are discovered.' => 'Si se selecciona, los Ãndices de este blog se reconstruirán al descubrir nuevos eventos de los torrentes de acciones.',
+ 'Enable rebuilding' => 'Activar reconstrucción',
+
+);
+
+1;
diff --git a/plugins/ActionStreams/lib/ActionStreams/L10N/fr.pm b/plugins/ActionStreams/lib/ActionStreams/L10N/fr.pm
new file mode 100644
index 0000000..63a1d45
--- /dev/null
+++ b/plugins/ActionStreams/lib/ActionStreams/L10N/fr.pm
@@ -0,0 +1,354 @@
+# Movable Type (r) (C) 2001-2008 Six Apart, Ltd. All Rights Reserved.
+# This code cannot be redistributed without permission from www.sixapart.com.
+# For more information, consult your Movable Type license.
+#
+# $Id: fr.pm 99820 2009-03-09 13:55:28Z mschenk $
+
+package ActionStreams::L10N::fr;
+
+use strict;
+use base 'ActionStreams::L10N::en_us';
+use vars qw( %Lexicon );
+%Lexicon = (
+
+## plugins/ActionStreams/blog_tmpl/sidebar.mtml
+
+## plugins/ActionStreams/blog_tmpl/main_index.mtml
+
+## plugins/ActionStreams/blog_tmpl/actions.mtml
+ 'Recent Actions' => 'Actions récentes',
+
+## plugins/ActionStreams/blog_tmpl/archive.mtml
+
+## plugins/ActionStreams/blog_tmpl/banner_footer.mtml
+
+## plugins/ActionStreams/blog_tmpl/elsewhere.mtml
+ 'Find [_1] Elsewhere' => 'Trouver [_1] ailleurs',
+
+## plugins/ActionStreams/streams.yaml
+ 'Currently Playing' => 'En train de jouer',
+ 'The games in your collection you\'re currently playing' => 'Les jeux de votre collection auxquels vous jouez en ce moment',
+ 'Comments you have made on the web' => 'Commentaires que vous avez écrits sur le web',
+ 'Colors' => 'Couleurs',
+ 'Colors you saved' => 'Couleurs que vous avez sauvegardées',
+ 'Palettes' => 'Palettes',
+ 'Palettes you saved' => 'Palettes que vous avez sauvegardées',
+ 'Patterns' => 'Motifs',
+ 'Patterns you saved' => 'Motifs que vous avez sauvegardés',
+ 'Favorite Palettes' => 'Palettes favorites',
+ 'Palettes you saved as favorites' => 'Palettes que vous avez sauvegardées comme favorites',
+ 'Reviews' => 'Critiques',
+ 'Your wine reviews' => 'Vos critiques de vins',
+ 'Cellar' => 'Cellier',
+ 'Wines you own' => 'Vins que vous possédez',
+ 'Shopping List' => 'Liste de courses',
+ 'Wines you want to buy' => 'Vins que vous voulez acheter',
+ 'Links' => 'Liens',
+ 'Your public links' => 'Vos liens publics',
+ 'Dugg' => 'Dugg',
+ 'Links you dugg' => 'Liens postés sur Digg',
+ 'Submissions' => 'Soumissions',
+ 'Links you submitted' => 'Liens que vous avez soumis',
+ 'Found' => 'Trouvé',
+ 'Photos you found' => 'Photos que vous avez trouvées',
+ 'Favorites' => 'Favorites',
+ 'Photos you marked as favorites' => 'Photos que vous avez marquées comme favorites',
+ 'Photos' => 'Photos',
+ 'Photos you posted' => 'Photos que vous avez postées',
+ 'Likes' => 'Likes',
+ 'Things from your friends that you "like"' => 'Infos de vos amis que vous avez aimées',
+ 'Leaderboard scores' => 'Scores',
+ 'Your high scores in games with leaderboards' => 'Vos meilleurs scores dans les jeux avec championnat',
+ 'Posts' => 'Notes',
+ 'Blog posts about your search term' => 'Notes du blog à propos de votre recherche',
+ 'Stories' => 'Articles',
+ 'News Stories matching your search' => 'Nouveaux articles correspondant à votre recherche',
+ 'To read' => 'A lire',
+ 'Books on your "to-read" shelf' => 'Livres dans votre liste "Ã lire"',
+ 'Reading' => 'En cours de lecture',
+ 'Books on your "currently-reading" shelf' => 'Livres dans votre liste "en cours de lecture"',
+ 'Read' => 'Lus',
+ 'Books on your "read" shelf' => 'Livres dans votre liste "lus"',
+ 'Shared' => 'Partagés',
+ 'Your shared items' => 'Vos élémens partagés',
+ 'Deliveries' => 'Livrés',
+ 'Icon sets you were delivered' => 'Sets d\'icones livrées',
+ 'Notices' => 'Notices',
+ 'Notices you posted' => 'Notices postées',
+ 'Intas' => 'Intas',
+ 'Links you saved' => 'Liens sauvegardés',
+ 'Photos you posted that were approved' => 'Photos postées et approuvées',
+ 'Recent events' => 'Evénements récents',
+ 'Events from your recent events feed' => 'Evénements de votre flux des événements récents',
+ 'Apps you use' => 'Applications que vous utilisez',
+ 'The applications you saved as ones you use' => 'Les applications que vous avez marquées comme utilisées',
+ 'Videos you saved as watched' => 'Videos que vous avez saugardées comme regardées',
+ 'Jaikus' => 'Jaikus',
+ 'Jaikus you posted' => 'Jaikus que vous avez postés',
+ 'Games you saved as favorites' => 'Jeux que vous avez sauvegardés comme favoris',
+ 'Achievements' => 'Réalisations',
+ 'Achievements you won' => 'Réalisations que vous avez atteintes',
+ 'Tracks' => 'Morceaux',
+ 'Songs you recently listened to (High spam potential!)' => 'Chansons que vous avez écoutées récemment (spam potentiel!)',
+ 'Loved Tracks' => 'Morceaux aimés',
+ 'Songs you marked as "loved"' => 'Chansons que vous avez marquées comme "aimées"',
+ 'Journal Entries' => 'Notes du journal',
+ 'Your recent journal entries' => 'Les notes récentes de votre journal',
+ 'Events' => 'événéments',
+ 'The events you said you\'ll be attending' => 'Les événements auquels vous allez assister',
+ 'Your public posts to your journal' => 'Les notes publiques sur votre journal',
+ 'Queue' => 'Liste d\'attente',
+ 'Movies you added to your rental queue' => 'Films que vous avez ajoutés à votre liste d\'attente',
+ 'Recent Movies' => 'Films récents',
+ 'Recent Rental Activity' => 'Films empreintés récemment',
+ 'Kudos' => 'Kudos',
+ 'Kudos you have received' => 'Kudos que vous avez reçus',
+ 'Favorite Songs' => 'Chansons favorites',
+ 'Songs you marked as favorites' => 'Chansons que vous avez marquées comme favorites',
+ 'Favorite Artists' => 'Artistes favoris',
+ 'Artists you marked as favorites' => 'Artistes que vous avez marqués comme favoris',
+ 'Stations' => 'Stations',
+ 'Radio stations you added' => 'Stations de radio que vous avez ajoutées',
+ 'List' => 'Liste',
+ 'Things you put in your list' => 'Choses que vous mettez sur votre liste',
+ 'Notes' => 'Notes',
+ 'Your public notes' => 'Vos notes publiques',
+ 'Comments you posted' => 'Commentaires que vous avez postés',
+ 'Articles you submitted' => 'Articles que vous avez soumis',
+ 'Articles you liked (your votes must be public)' => 'Articles que vous avez aimés (vos votes doivent être publiques)',
+ 'Dislikes' => 'Pas aimés',
+ 'Articles you disliked (your votes must be public)' => 'Articles que vous n\'avez pas aimés (vos votes doivent être publiques)',
+ 'Slideshows you saved as favorites' => 'Diaparamas que vous avez marqués comme favoris',
+ 'Slideshows' => 'Diaporamas',
+ 'Slideshows you posted' => 'Diaporamas que vous avez postés',
+ 'Your achievements for achievement-enabled games' => 'Vos résultats pour les jeux avec des objectifs',
+ 'Stuff' => 'Trucs',
+ 'Things you posted' => 'Choses que vous avez postées',
+ 'Tweets' => 'Tweets',
+ 'Your public tweets' => 'Vos tweets publiques',
+ 'Public tweets you saved as favorites' => 'Tweets publiques que vous avez sauvegardés comme favoris',
+ 'Tweets about your search term' => 'Tweets contenant votre terme de recherche',
+ 'Saved' => 'Sauvegardés',
+ 'Things you saved as favorites' => 'Choses que vous avez sauvegardées comme favorites',
+ 'Events you are watching or attending' => 'Evénements que vous regardez ou auxquels vous assistez',
+ 'Videos you posted' => 'Videos que vous avez postées',
+ 'Videos you liked' => 'Videos que vous avez aimées',
+ 'Public assets you saved as favorites' => 'Assets publiques que vous avez sauvegardées comme favorites',
+ 'Your public photos in your Vox library' => 'Vos photos publiques dans votre librairie Vox',
+ 'Your public posts to your Vox' => 'Vos notes publiques dans votre Vox',
+ 'The posts available from the website\'s feed' => 'Les notes publiques disponibles dans le flux du site',
+ 'Wists' => 'Wists',
+ 'Stuff you saved' => 'Choses que vous avez sauvegardées',
+ 'Gamerscore' => 'Score du joueur',
+ 'Notes when your gamerscore passes an even number' => 'Notes quand votre score dépasse un nombre pair',
+ 'Places you reviewed' => 'Places que vous avez critiquées',
+ 'Videos you saved as favorites' => 'Videos que vous avez sauvegardées comme favorites',
+
+## plugins/ActionStreams/services.yaml
+ '1up.com' => '1up.com',
+ '43Things' => '43Things',
+ 'Screen name' => 'Pseudonyme',
+ 'backtype' => 'backtype',
+ 'Bebo' => 'Bebo',
+ 'Catster' => 'Catster',
+ 'COLOURlovers' => 'COLOURlovers',
+ 'Cork\'\'d\'' => 'Cork\'\'d\'',
+ 'Delicious' => 'Delicious',
+ 'Destructoid' => 'Destructoid',
+ 'Digg' => 'Digg',
+ 'Dodgeball' => 'Dodgeball',
+ 'Dogster' => 'Dogster',
+ 'Dopplr' => 'Dopplr',
+ 'Facebook' => 'Facebook',
+ 'User ID' => 'ID d\'utilisateur',
+ 'You can find your Facebook userid within your profile URL. For example, http://www.facebook.com/profile.php?id=24400320.' => 'Vous pouvez trouver votre userid Facebook dans l\'URL de votre profil. Par exemple, http://www.facebook.com/profile.php?id=24400320.',
+ 'FFFFOUND!' => 'FFFFOUND!',
+ 'Flickr' => 'Flickr',
+ 'Enter your Flickr userid which contains "@" in it, e.g. 36381329@N00. Flickr userid is NOT the username in the URL of your photostream.' => 'Saisissez votre userid Flickr',
+ 'FriendFeed' => 'FriendFeed',
+ 'Gametap' => 'Gametap',
+ 'Google Blogs' => 'Google Blogs',
+ 'Search term' => 'Rerchercher le terme',
+ 'Google News' => 'Google News',
+ 'Search for' => 'Rechercher',
+ 'Goodreads' => 'Goodreads',
+ 'You can find your Goodreads userid within your profile URL. For example, http://www.goodreads.com/user/show/123456.' => 'Vous pouvez trouver votre userid Giidreads dans votre URL de profil. Par exemple, http://www.goodreads.com/user/show/123456.',
+ 'Google Reader' => 'Google Reader',
+ 'Sharing ID' => 'ID partagé',
+ 'Hi5' => 'Hi5',
+ 'IconBuffet' => 'IconBuffet',
+ 'ICQ' => 'ICQ',
+ 'UIN' => 'UIN',
+ 'Identi.ca' => 'Identi.ca',
+ 'Iminta' => 'Iminta',
+ 'iStockPhoto' => 'iStockPhoto',
+ 'You can find your istockphoto userid within your profile URL. For example, http://www.istockphoto.com/user_view.php?id=1234567.' => 'Vous pouvez trouver votre userid istockphoto dans l\'URL de votre profil. Par exemple, http://www.istockphoto.com/user_view.php?id=1234567.',
+ 'IUseThis' => 'IUseThis',
+ 'iwatchthis' => 'iwatchthis',
+ 'Jabber' => 'Jabber',
+ 'Jabber ID' => 'ID Jabber',
+ 'Jaiku' => 'Jaiku',
+ 'Kongregate' => 'Kongregate',
+ 'Last.fm' => 'Last.fm',
+ 'LinkedIn' => 'LinkedIn',
+ 'Profile URL' => 'URL du profil',
+ 'Ma.gnolia' => 'Ma.gnolia',
+ 'MOG' => 'MOG',
+ 'MSN Messenger\'' => 'MSN Messenger\'',
+ 'Multiply' => 'Multiply',
+ 'MySpace' => 'MySpace',
+ 'Netflix' => 'Netflix',
+ 'Netflix RSS ID' => 'ID Netflix RSS',
+ 'To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.' => 'Pour trouver votre RSS ID Netflix, cliquez sur "RSS" en bas de n\'importe quelle page sur le site de Netflix, puis copiez-collez le votre lien "Queue".',
+ 'Netvibes' => 'Netvibes',
+ 'Newsvine' => 'Newsvine',
+ 'Ning' => 'Ning',
+ 'Social Network URL' => 'URL du réseau social',
+ 'Ohloh' => 'Ohloh',
+ 'Orkut' => 'Orkut',
+ 'You can find your orkut uid within your profile URL. For example, http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789' => 'Vous pouvez trouver votre userid orkut dans l\'URL de votre profil. Par exemple, http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789',
+ 'Pandora' => 'Pandora',
+ 'Picasa Web Albums' => 'Picasa Web Albums',
+ 'p0pulist' => 'p0pulist',
+ 'You can find your p0pulist user id within your Hot List URL. for example, http://p0pulist.com/list/hot_list/10000' => 'Vous pouvez trouver votre user id p0pulist dans votre URL Hot List. Par exemple, http://p0pulist.com/list/hot_list/10000',
+ 'Pownce' => 'Pownce',
+ 'Reddit' => 'Reddit',
+ 'Skype' => 'Skype',
+ 'SlideShare' => 'SlideShare',
+ 'Smugmug' => 'Smugmug',
+ 'SonicLiving' => 'SonicLiving',
+ 'You can find your SonicLiving userid within your share&subscribe URL. For example, http://sonicliving.com/user/12345/feeds' => 'Vous pouvez trouver votre userid SonicLiving dans votre URL share&subscribe. Par exemple, http://sonicliving.com/user/12345/feeds',
+ 'Steam' => 'Steam',
+ 'StumbleUpon' => 'StumbleUpon',
+ 'Tabblo' => 'Tabblo',
+ 'Blank should be replaced by positive sign (+).' => 'Les espaces doivent être remplacés par un signe plus (+)',
+ 'Tribe' => 'Tribe',
+ 'You can find your tribe userid within your profile URL. For example, http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a.' => 'Vous pouvez trouver votre userid tribe dans l\'URL de votre profil. Par exemple, http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a.',
+ 'Tumblr' => 'Tumblr',
+ 'Twitter' => 'Twitter',
+ 'TwitterSearch' => 'TwitterSearch',
+ 'Uncrate' => 'Uncrate',
+ 'Upcoming' => 'Upcoming',
+ 'Viddler' => 'Viddler',
+ 'Vimeo' => 'Vimeo',
+ 'Virb' => 'Virb',
+ 'You can find your VIRB userid within your home URL. For example, http://www.virb.com/backend/2756504321310091/your_home.' => 'Vous pouvez trouver votre userid VIRB dans l\'URL d\'accueil. Par exemple, http://www.virb.com/backend/2756504321310091/your_home.',
+ 'Vox name' => 'Nom Vox',
+ 'Website' => 'Website',
+ 'Xbox Live\'' => 'Xbox Live\'',
+ 'Gamertag' => 'Gamertag',
+ 'Yahoo! Messenger\'' => 'Yahoo! Messenger\'',
+ 'Yelp' => 'Yelp',
+ 'YouTube' => 'YouTube',
+ 'Zooomr' => 'Zooomr',
+
+## plugins/ActionStreams/config.yaml
+ 'Manages authors\' accounts and actions on sites elsewhere around the web' => 'Gérer les comptes et les actions des utilisatreurs sur les sites ailleurs sur le web',
+ 'Are you sure you want to hide EVERY event in EVERY action stream?' => 'Ãtes-vous sûr de vouloir masquer TOUS les événement dans TOUS les flux d\'actions ?',
+ 'Are you sure you want to show EVERY event in EVERY action stream?' => 'Ãtes-vous sûr de vouloir afficher TOUS les événement dans TOUS les flux d\'actions ?',
+ 'Deleted events that are still available from the remote service will be added back in the next scan. Only events that are no longer available from your profile will remain deleted. Are you sure you want to delete the selected event(s)?' => 'Les événements supprimés qui sont toujours disponibles sur le service distant seront ajoutés à nouveau dans le prochain scan. Seuls les événements qui ne sont plus disponibles dans votre profil resteront supprimés. Etes-vous sûr de vouloir supprimer les événements sélectionnés?',
+ 'Hide All' => 'Cacher tout',
+ 'Show All' => 'Tout afficher',
+ 'Poll for new events' => 'Emplacement pour les nouveaux événements',
+ 'Update Events' => 'Mettre à jour les événements',
+ 'Action Stream' => 'Action Stream',
+ 'Main Index (Recent Actions)' => 'Index principal (Actions récentes)',
+ 'Action Archive' => 'Archive des actions',
+ 'Feed - Recent Activity' => 'Flux - Activité récente',
+ 'Find Authors Elsewhere' => 'Trouver les auteurs ailleurs',
+ 'Enabling default action streams for selected profiles...' => 'Activer les flux d\'actions par défaut des profils sélectionnés...',
+
+## plugins/ActionStreams/lib/ActionStreams/Upgrade.pm
+ 'Updating classification of [_1] [_2] actions...' => 'Mise à jour de la classification des actions [_1] [_2]...',
+ 'Renaming "[_1]" data of [_2] [_3] actions...' => 'Renommage "[_1]" des données des actions [_1] [_2]...',
+
+## plugins/ActionStreams/lib/ActionStreams/Worker.pm
+ 'No such author with ID [_1]' => 'Aucun auteur n\'a été trouvé avec l\'ID [_1]',
+
+## plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+ 'Other Profiles' => 'Autres profils',
+ 'Profiles' => 'Profiles',
+ 'Actions from the service [_1]' => 'Actions pour le service [_1]',
+ 'Actions that are shown' => 'Actions affichées',
+ 'Actions that are hidden' => 'Actions masquées',
+ 'No such event [_1]' => 'Aucun événement [_1] trouvé',
+ '[_1] Profile' => 'Profil [_1]',
+
+## plugins/ActionStreams/lib/ActionStreams/Tags.pm
+ 'No user [_1]' => 'Aucun utilisateur [_1]',
+
+## plugins/ActionStreams/lib/ActionStreams/Event.pm
+ '[_1] updating [_2] events for [_3]' => '[_1] mets à jour [_2] événements pour [_3]',
+ 'Error updating events for [_1]\'s [_2] stream (type [_3] ident [_4]): [_5]' => 'Erreur lors de la mise à jour des événements pour le flux [_2] de [_1] (type [_3] ident [_4]) : [_5]',
+ 'Could not load class [_1] for stream [_2] [_3]: [_4]' => 'Impossible de charger la classe [_1] pour le flux [_2] [_3] : [_4]',
+ 'No URL to fetch for [_1] results' => 'Aucune URL à joindre pour les résultats [_1]', # Translate - New
+ 'Could not fetch [_1]: [_2]' => 'Impossible de joindre [_1] : [_2]', # Translate - New
+ 'Aborted fetching [_1]: [_2]' => 'Opération abandonnée [_1] : [_2]', # Translate - New
+
+## plugins/ActionStreams/tmpl/dialog_edit_profile.tmpl
+ 'Your user name or ID is required.' => 'Votre nom d\'utilisateur ou ID est requis.',
+ 'Edit a profile on a social networking or instant messaging service.' => 'Editer un profil sur un service de réseau social ou de messagerie instantanée.',
+ 'Service' => 'Service',
+ 'Enter your account on the selected service.' => 'Entrez votre compte sur le service sélectionné.',
+ 'For example:' => 'Par exemple :',
+ 'Action Streams' => 'Flux d\'actions',
+ 'Select the action streams to collect from the selected service.' => 'Sélectionner le flux d\'action pour collecter les données depuis les services sélectionnées.',
+ 'No streams are available for this service.' => 'Aucun flux n\'est disponible pour ce service.',
+
+## plugins/ActionStreams/tmpl/other_profiles.tmpl
+ 'The selected profile was added.' => 'Le profil sélectionné a été ajouté.',
+ 'The selected profiles were removed.' => 'Les profils sélectionnés ont été retirés.',
+ 'The selected profiles were scanned for updates.' => 'La présence de nouveaux événements sur les profils sélectionnés a été effectuée.',
+ 'The changes to the profile have been saved.' => 'Les modifications sur le profil ont été enregistrées.',
+ 'Add Profile' => 'Ajouter un profil',
+ 'profile' => 'profil',
+ 'profiles' => 'profiles',
+ 'Delete selected profiles (x)' => 'Supprimer les profils sélectionnés (x)',
+ 'to update' => 'à mettre à jour',
+ 'Scan now for new actions' => 'Vérifier la présence de nouveaux événements',
+ 'Update Now' => 'Mettre à jour maintenant',
+ 'No profiles were found.' => 'Aucun profil n\'a été trouvé.',
+ 'external_link_target' => 'external_link_target',
+ 'View Profile' => 'Voir le profil',
+
+## plugins/ActionStreams/tmpl/dialog_add_profile.tmpl
+ 'Add a profile on a social networking or instant messaging service.' => 'Ajouter un profil sur un service de réseau social ou de messagerie instantanée.',
+ 'Select a service where you already have an account.' => 'Sélectionnez un service où vous avez déjà un compte.',
+ 'Add Profile (s)' => 'Ajouter le Profil (s)', # Translate - New
+
+## plugins/ActionStreams/tmpl/list_profileevent.tmpl
+ 'The selected events were deleted.' => 'Les événements sélectionnés ont été supprimés.',
+ 'The selected events were hidden.' => 'Les événements sélectionnés ont été masqués.',
+ 'The selected events were shown.' => 'Les événements sélectionnés ont été affichés.',
+ 'All action stream events were hidden.' => 'Tous les événements du flux d\'activité ont été masqués.',
+ 'All action stream events were shown.' => 'Tous les événements du flux d\'activité ont été affichés.',
+ 'event' => 'événement',
+ 'events' => 'événéments',
+ 'Hide selected events (h)' => 'Masquer les événements sélectionnés (h)',
+ 'Hide' => 'Masquer',
+ 'Show selected events (h)' => 'Afficher les événements sélectionnés (h)',
+ 'Show' => 'Afficher',
+ 'All stream actions' => 'Tous les flux d\'actions',
+ 'Show only actions where' => 'Afficher uniquement les actions où',
+ 'service' => 'le service est',
+ 'visibility' => 'la visibilité est',
+ 'hidden' => 'masqué',
+ 'shown' => 'affiché',
+ 'No events could be found.' => 'Aucun événement n\'a été trouvé.',
+ 'Event' => 'Ãvénement',
+ 'Shown' => 'Affiché',
+ 'Hidden' => 'Masqué',
+ 'View action link' => 'Voir le lien de l\'action',
+
+## plugins/ActionStreams/tmpl/widget_recent.mtml
+ 'Your Recent Actions' => 'Votre activité récente',
+ 'blog this' => 'bloguer ceci',
+
+## plugins/ActionStreams/tmpl/blog_config_template.tmpl
+ 'Rebuild Indexes' => 'Republier les index',
+ 'If selected, this blog\'s indexes will be rebuilt when new action stream events are discovered.' => 'Si sélectionner, les index des blogs seront republiés lorsque de nouveaux événements du flux d\'activité seront découverts.',
+ 'Enable rebuilding' => 'Activer la republication',
+
+);
+
+1;
diff --git a/plugins/ActionStreams/lib/ActionStreams/L10N/ja.pm b/plugins/ActionStreams/lib/ActionStreams/L10N/ja.pm
new file mode 100644
index 0000000..6fdcb5f
--- /dev/null
+++ b/plugins/ActionStreams/lib/ActionStreams/L10N/ja.pm
@@ -0,0 +1,425 @@
+# Movable Type (r) (C) 2001-2008 Six Apart, Ltd. All Rights Reserved.
+# This code cannot be redistributed without permission from www.sixapart.com.
+# For more information, consult your Movable Type license.
+#
+# $Id: $
+
+package ActionStreams::L10N::ja;
+
+use strict;
+use base 'ActionStreams::L10N::en_us';
+use vars qw( %Lexicon );
+%Lexicon = (
+
+## plugins/ActionStreams/services.yaml
+ '1up.com' => '1up.com',
+ '43Things' => '43Things',
+ 'Screen name' => '表示å',
+ 'backtype' => 'backtype',
+ 'Bebo' => 'Bebo',
+ 'Catster' => 'Catster',
+ 'COLOURlovers' => 'COLOURlovers',
+ 'Cork\'\'d\'' => 'Cork\'\'d\'',
+ 'Delicious' => 'Delicious',
+ 'Destructoid' => 'Destructoid',
+ 'Digg' => 'Digg',
+ 'Dodgeball' => 'Dodgeball',
+ 'Dogster' => 'Dogster',
+ 'Dopplr' => 'Dopplr',
+ 'Facebook' => 'Facebook',
+ 'User ID' => 'ã¦ã¼ã¶ã¼ID',
+ 'You can find your Facebook userid within your profile URL. For example, http://www.facebook.com/profile.php?id=24400320.' => 'Facebookã®ã¦ã¼ã¶ã¼IDã¯ãããã£ã¼ã«ã®URLå
ã«ããã¾ããä¾: http://www.facebook.com/profile.php?id=24400320',
+ 'FFFFOUND!' => 'FFFFOUND!',
+ 'Flickr' => 'Flickr',
+ 'Enter your Flickr userid which contains "@" in it, e.g. 36381329@N00. Flickr userid is NOT the username in the URL of your photostream.' => 'Flickrã®ã¦ã¼ã¶ã¼ID(@ãå«ã)ãå
¥åãã¦ãã ããã ä¾: 36381329@N00 Flickrã®ã¦ã¼ã¶ã¼IDã¯photostreamã®URLå
ã®IDã§ã¯ããã¾ããã',
+ 'FriendFeed' => 'FriendFeed',
+ 'Gametap' => 'Gametap',
+ 'Google Blogs' => 'Google Blogs',
+ 'Search term' => 'æ¤ç´¢ã¯ã¼ã',
+ 'Google News' => 'Google News',
+ 'Search for' => 'æ¤ç´¢ ',
+ 'Goodreads' => 'Goodreads',
+ 'You can find your Goodreads userid within your profile URL. For example, http://www.goodreads.com/user/show/123456.' => 'Goodreadsã®ã¦ã¼ã¶ã¼IDã¯ãããã£ã¼ã«ã®URLã«ããã¾ããä¾: http://www.goodreads.com/user/show/123456',
+ 'Google Reader' => 'Google Reader',
+ 'Sharing ID' => 'å
±æID',
+ 'Hi5' => 'Hi5',
+ 'IconBuffet' => 'IconBuffet',
+ 'ICQ' => 'ICQ',
+ 'UIN' => 'UIN',
+ 'Identi.ca' => 'Identi.ca',
+ 'Iminta' => 'Iminta',
+ 'iStockPhoto' => 'iStockPhoto',
+ 'You can find your istockphoto userid within your profile URL. For example, http://www.istockphoto.com/user_view.php?id=1234567.' => 'istockphotoã®ã¦ã¼ã¶ã¼IDã¯ãããã£ã¼ã«ã®URLã«ããã¾ããä¾: http://www.istockphoto.com/user_view.php?id=1234567',
+ 'IUseThis' => 'IUseThis',
+ 'iwatchthis' => 'iwatchthis',
+ 'Jabber' => 'Jabber',
+ 'Jabber ID' => 'Jabber ID',
+ 'Jaiku' => 'Jaiku',
+ 'Kongregate' => 'Kongregate',
+ 'Last.fm' => 'Last.fm',
+ 'LinkedIn' => 'LinkedIn',
+ 'Profile URL' => 'ãããã£ã¼ã«ID',
+ 'Ma.gnolia' => 'Ma.gnolia',
+ 'MOG' => 'MOG',
+ 'MSN Messenger\'' => 'MSN Messenger\'',
+ 'Multiply' => 'Multiply',
+ 'MySpace' => 'MySpace',
+ 'Netflix' => 'Netflix',
+ 'Netflix RSS ID' => 'Netflix RSS ID',
+ 'To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.' => 'Netflix RSS IDã¯Netflixãµã¤ãã®ã©ããã®ãã¼ã¸ã§"RSS"ãã¯ãªãã¯ã¨ããã¾ãããããã"Queue"ãªã³ã¯ãã³ãã¼ãã¦è²¼ãä»ãã¦ãã ããã',
+ 'Netvibes' => 'Netvibes',
+ 'Newsvine' => 'Newsvine',
+ 'Ning' => 'Ning',
+ 'Social Network URL' => 'ã½ã¼ã·ã£ã«ãããã¯ã¼ã¯URL',
+ 'Ohloh' => 'Ohloh',
+ 'Orkut' => 'Orkut',
+ 'You can find your orkut uid within your profile URL. For example, http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789' => 'orkutã®ã¦ã¼ã¶ã¼IDã¯ãããã£ã¼ã«ã®URLå
ã«ããã¾ããä¾: http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789',
+ 'Pandora' => 'Pandora',
+ 'Picasa Web Albums' => 'Picasa Web Albums',
+ 'p0pulist' => 'p0pulist',
+ 'You can find your p0pulist user id within your Hot List URL. for example, http://p0pulist.com/list/hot_list/10000' => 'p0pulistã®ã¦ã¼ã¶ã¼IDã¯Hot Listã®URLå
ã«ããã¾ããä¾: http://p0pulist.com/list/hot_list/10000',
+ 'Pownce' => 'Pownce',
+ 'Reddit' => 'Reddit',
+ 'Skype' => 'Skype',
+ 'SlideShare' => 'SlideShare',
+ 'Smugmug' => 'Smugmug',
+ 'SonicLiving' => 'SonicLiving',
+ 'You can find your SonicLiving userid within your share&subscribe URL. For example, http://sonicliving.com/user/12345/feeds' => 'SonicLivingã®ã¦ã¼ã¶ã¼IDã¯share&subscribeã®URLã«ããã¾ããä¾: http://sonicliving.com/user/12345/feeds',
+ 'Steam' => 'Steam',
+ 'StumbleUpon' => 'StumbleUpon',
+ 'Tabblo' => 'Tabblo',
+ 'Blank should be replaced by positive sign (+).' => '空ç½ã¯ + ã§ç½®ãæãã¦ãã ããã',
+ 'Tribe' => 'Tribe',
+ 'You can find your tribe userid within your profile URL. For example, http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a.' => 'tribeã®ã¦ã¼ã¶ã¼IDã¯ãããã£ã¼ã«ã®URLã«ããã¾ããä¾: http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a',
+ 'Tumblr' => 'Tumblr',
+ 'Twitter' => 'Twitter',
+ 'TwitterSearch' => 'TwitterSearch',
+ 'Uncrate' => 'Uncrate',
+ 'Upcoming' => 'Upcoming',
+ 'Viddler' => 'Viddler',
+ 'Vimeo' => 'Vimeo',
+ 'Virb' => 'Virb',
+ 'You can find your VIRB userid within your home URL. For example, http://www.virb.com/backend/2756504321310091/your_home.' => 'VIRBã®ã¦ã¼ã¶ã¼IDã¯ãã¼ã ã®URLã«ããã¾ããä¾: http://www.virb.com/backend/2756504321310091/your_home',
+ 'Vox name' => 'Voxã¦ã¼ã¶ã¼å',
+ 'Website' => 'Website',
+ 'Wists' => 'Wists',
+ 'Xbox Live\'' => 'Xbox Live\'',
+ 'Gamertag' => 'ã²ã¼ãã¼ã¿ã°',
+ 'Yahoo! Messenger\'' => 'Yahoo! Messenger\'',
+ 'Yelp' => 'Yelp',
+ 'YouTube' => 'YouTube',
+ 'Zooomr' => 'Zooomr',
+
+## plugins/ActionStreams/blog_tmpl/elsewhere.mtml
+ 'Find [_1] Elsewhere' => '[_1]ã®å©ç¨ãµã¼ãã¹',
+
+## plugins/ActionStreams/blog_tmpl/banner_footer.mtml
+
+## plugins/ActionStreams/bl3og_tmpl/actions.mtml
+ 'Recent Actions' => 'æè¿ã®ã¢ã¯ã·ã§ã³',
+
+## plugins/ActionStreams/blog_tmpl/main_index.mtml
+
+## plugins/ActionStreams/blog_tmpl/sidebar.mtml
+
+## plugins/ActionStreams/blog_tmpl/archive.mtml
+
+## plugins/ActionStreams/tmpl/blog_config_template.tmpl
+ 'Rebuild Indexes' => 'ã¤ã³ããã¯ã¹åæ§ç¯',
+ 'If selected, this blog\'s indexes will be rebuilt when new action stream events are discovered.' => 'æ°ããã¢ã¯ã·ã§ã³ã¹ããªã¼ã ã¤ãã³ããè¦ã¤ãã£ãæã«ãããã°ã®ã¤ã³ããã¯ã¹ãåæ§ç¯ããã',
+ 'Enable rebuilding' => 'åæ§ç¯ãæå¹ã«ãã',
+
+## plugins/ActionStreams/tmpl/dialog_edit_profile.tmpl
+ 'Your user name or ID is required.' => 'ã¦ã¼ã¶ã¼åã¾ãã¯IDãå¿
é ã§ãã',
+ 'Edit a profile on a social networking or instant messaging service.' => 'SNSãIMãµã¼ãã¹ãªã©ã®ãããã¡ã¤ã«ãç·¨éãã¾ãã',
+ 'Service' => 'ãµã¼ãã¹',
+ 'Enter your account on the selected service.' => '鏿ãããµã¼ãã¹ã®ã¢ã«ã¦ã³ããå
¥åãã¦ãã ããã',
+ 'For example:' => 'ä¾: ',
+ 'Action Streams' => 'ã¢ã¯ã·ã§ã³ã¹ããªã¼ã ',
+ 'Select the action streams to collect from the selected service.' => '鏿ãããµã¼ãã¹ããéããã¢ã¯ã·ã§ã³ã¹ããªã¼ã ããã§ãã¯ãã¦ãã ããã',
+ 'No streams are available for this service.' => 'ãã®ãµã¼ãã¹ã§ã¯å©ç¨ã§ããã¹ããªã¼ã ãããã¾ããã',
+
+## plugins/ActionStreams/tmpl/list_profileevent.tmpl
+ 'Action Stream' => 'ã¢ã¯ã·ã§ã³ã¹ããªã¼ã ',
+ 'The selected events were deleted.' => '鏿ããã¤ãã³ãã¯åé¤ããã¾ããã',
+ 'The selected events were hidden.' => '鏿ããã¤ãã³ããé表示ã«ãã¾ããã',
+ 'The selected events were shown.' => '鏿ããã¤ãã³ãã表示ã«ãã¾ããã',
+ 'All action stream events were hidden.' => 'å
¨ã¢ã¯ã·ã§ã³ã¹ããªã¼ã ã¤ãã³ããé表示ã«ãã¾ããã',
+ 'All action stream events were shown.' => 'å
¨ã¢ã¯ã·ã§ã³ã¹ããªã¼ã ã¤ãã³ãã表示ã«ãã¾ããã',
+ 'event' => 'ã¤ãã³ã',
+ 'events' => 'ã¤ãã³ã',
+ 'Hide selected events (h)' => '鏿ããã¤ãã³ããé表示ã«ãã (h)',
+ 'Hide' => 'é表示',
+ 'Show selected events (h)' => '鏿ããã¤ãã³ãã表示ã«ãã (h)',
+ 'Show' => '表示',
+ 'All stream actions' => 'ãã¹ã¦ã®ã¹ããªã¼ã ã¢ã¯ã·ã§ã³',
+ 'Show only actions where' => 'ã¢ã¯ã·ã§ã³ã表示: ',
+ 'service' => 'ãµã¼ãã¹',
+ 'visibility' => '表示/é表示',
+ 'hidden' => 'é表示',
+ 'shown' => '表示',
+ 'No events could be found.' => 'ã¤ãã³ããè¦ã¤ããã¾ããã',
+ 'Event' => 'ã¤ãã³ã',
+ 'Shown' => '表示',
+ 'Hidden' => 'é表示',
+ 'View action link' => 'ã¢ã¯ã·ã§ã³ãªã³ã¯è¡¨ç¤º',
+
+## plugins/ActionStreams/tmpl/widget_recent.mtml
+ 'Your Recent Actions' => 'æè¿ã®ã¢ã¯ã·ã§ã³',
+ 'blog this' => 'è¨äºä½æ',
+
+## plugins/ActionStreams/tmpl/dialog_add_profile.tmpl
+ 'Add a profile on a social networking or instant messaging service.' => 'ã½ã¼ã·ã£ã«ãããã¯ã¼ã¯ãã¾ãã¯ã¤ã³ã¹ã¿ã³ãã¡ãã»ã¼ã¸ãµã¼ãã¹ã®ãããã£ã¼ã«ã追å ãã¾ãã',
+ 'Select a service where you already have an account.' => 'ã¢ã«ã¦ã³ãããã£ã¦ãããµã¼ãã¹ã鏿ãã¦ãã ããã',
+ 'Add Profile (s)' => 'ãããã£ã¼ã«è¿½å (s)',
+
+## plugins/ActionStreams/tmpl/other_profiles.tmpl
+ 'Other Profiles' => 'å©ç¨ãµã¼ãã¹',
+ 'The selected profile was added.' => '鏿ãããããã£ã¼ã«ã¯è¿½å ããã¾ããã',
+ 'The selected profiles were removed.' => '鏿ãããããã£ã¼ã«ã¯åé¤ããã¾ããã',
+ 'The selected profiles were scanned for updates.' => '鏿ãããããã£ã¼ã«ã®æ´æ°ã調ã¹ã¾ããã',
+ 'The changes to the profile have been saved.' => 'ãããã£ã¼ã«ã®å¤æ´ãä¿åããã¾ããã',
+ 'Add Profile' => 'ãããã£ã¼ã«è¿½å ',
+ 'profile' => 'ãããã£ã¼ã«',
+ 'profiles' => 'ãããã£ã¼ã«',
+ 'Delete selected profiles (x)' => '鏿ãããããã£ã¼ã«åé¤(x)',
+ 'to update' => 'æ´æ°',
+ 'Scan now for new actions' => 'æ°ããã¢ã¯ã·ã§ã³ã調ã¹ã',
+ 'Update Now' => 'ä»ããæ´æ°ãã',
+ 'No profiles were found.' => 'ãããã£ã¼ã«ãè¦ã¤ããã¾ããã',
+ 'external_link_target' => 'å¤é¨ãªã³ã¯ã¿ã¼ã²ãã',
+ 'View Profile' => 'ãããã£ã¼ã«è¡¨ç¤º',
+
+## plugins/ActionStreams/config.yaml
+ 'Manages authors\' accounts and actions on sites elsewhere around the web' => 'ã¦ã¼ã¶ã¼ãã¦ã§ãã§å©ç¨ãã¦ãããµã¼ãã¹ã®ã¢ã«ã¦ã³ãã¨ã¢ã¯ã·ã§ã³ã管çãã¾ã',
+ 'Are you sure you want to hide EVERY event in EVERY action stream?' => 'å
¨ã¢ã¯ã·ã§ã³ã¹ããªã¼ã ã®å
¨ã¤ãã³ããé表示ã«ãã¦ããããã§ãã?',
+ 'Are you sure you want to show EVERY event in EVERY action stream?' => 'å
¨ã¢ã¯ã·ã§ã³ã¹ããªã¼ã ã®å
¨ã¤ãã³ãã表示ã«ãã¦ããããã§ãã?',
+ 'Deleted events that are still available from the remote service will be added back in the next scan. Only events that are no longer available from your profile will remain deleted. Are you sure you want to delete the selected event(s)?' => 'ã¤ãã³ããåé¤ãã¦ããªã¢ã¼ããµã¼ãã¹ã¯æå¹ã¨ãªã£ã¦ãã¾ããæ¬¡ã®æ´æ°èª¿æ»æã«è¿½å ããã¾ããã¦ã¼ã¶ãããã£ã¼ã«ããã¤ãã³ããç¡å¹ã«ããã°åé¤ããã¾ãã鏿ããã¤ãã³ããåé¤ãã¦ããããã§ãã?',
+ 'Hide All' => 'å
¨ã¦é表示',
+ 'Show All' => 'å
¨ã¦è¡¨ç¤º',
+ 'Poll for new events' => 'æ°ããã¤ãã³ãã®ç²å¾',
+ 'Update Events' => 'ã¤ãã³ãã®æ´æ°',
+ 'Main Index (Recent Actions)' => 'ã¡ã¤ã³ã¤ã³ããã¯ã¹(æè¿ã®ã¢ã¯ã·ã§ã³)',
+ 'Action Archive' => 'ã¢ã¯ã·ã§ã³ã¢ã¼ã«ã¤ã',
+ 'Feed - Recent Activity' => 'ãã£ã¼ã - æè¿ã®ã¢ã¯ãã£ããã£ã¼',
+ 'Find Authors Elsewhere' => 'ã¦ã¼ã¶ã¼ã®å©ç¨ãµã¼ãã¹',
+ 'Enabling default action streams for selected profiles...' => '鏿ãããããã£ã¼ã«ã®æ¢åã¢ã¯ã·ã§ã³ã¹ããªã¼ã ãæå¹ã«ãã¦ãã¾ã...',
+
+## plugins/ActionStreams/lib/ActionStreams/Tags.pm
+ 'No user [_1]' => 'ã¦ã¼ã¶ã¼([_1])ã¯è¦ã¤ããã¾ãã',
+
+## plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+ 'Other Profiles' => 'å©ç¨ãµã¼ãã¹',
+ 'Profiles' => 'ãããã£ã¼ã«',
+ 'Action Stream' => 'ã¢ã¯ã·ã§ã³ã¹ããªã¼ã ',
+ 'Profiles' => 'ãããã£ã¼ã«',
+ 'Actions from the service [_1]' => 'ãµã¼ãã¹([_1])ã®ã¢ã¯ã·ã§ã³',
+ 'Actions that are shown' => '表示ã¢ã¯ã·ã§ã³',
+ 'Actions that are hidden' => 'é表示ã¢ã¯ã·ã§ã³',
+ 'No such event [_1]' => '[_1]ã¤ãã³ãã¯ããã¾ãã',
+ '[_1] Profile' => '[_1]',
+
+## plugins/ActionStreams/lib/ActionStreams/Event.pm
+ '[_1] updating [_2] events for [_3]' => '[_3]ã®[_2]ã¤ãã³ããæ´æ°ãã¦ãã¾ã: [_1]',
+ 'Error updating events for [_1]\'s [_2] stream (type [_3] ident [_4]): [_5]' => '[_1]ã®[_2]ã¹ããªã¼ã ([_3]ã¿ã¤ãã®[_4])ã®æ´æ°ã«å¤±æãã¾ãã: [_5]',
+ 'Could not load class [_1] for stream [_2] [_3]: [_4]' => '[_2]([_3])ã¹ããªã¼ã ã®[_1]ã¯ã©ã¹ã®ãã¼ããã§ãã¾ãã: [_4]',
+ 'No URL to fetch for [_1] results' => '[_1]ã®æ´æ°æ
å ±ã®URLãè¨å®ããã¦ãã¾ãã',
+ 'Could not fetch [_1]: [_2]' => '[_1]ã®æ´æ°ã«å¤±æãã¾ãã: [_2]',
+ 'Aborted fetching [_1]: [_2]' => '[_1]ã®æ´æ°ã䏿¢ãã¾ãã: [_2]',
+
+## plugins/ActionStreams/lib/ActionStreams/Upgrade.pm
+ 'Updating classification of [_1] [_2] actions...' => '[_1]ã®[_2]ã¢ã¯ã·ã§ã³ã®åé¡ãæ´æ°ä¸...',
+ 'Renaming "[_1]" data of [_2] [_3] actions...' => '[_2]ã®[_3]ã¢ã¯ã·ã§ã³ãã¼ã¿ã"[_1]"ã«å¤æ´ä¸...',
+
+## plugins/ActionStreams/lib/ActionStreams/Worker.pm
+ 'No such author with ID [_1]' => 'ã¦ã¼ã¶ã¼ID([_1])ã¯è¦ã¤ããã¾ããã',
+
+## plugins/ActionStreams/streams.yaml
+ 'Currently Playing' => 'ç¾å¨ãã¬ã¼ä¸',
+ 'The games in your collection you\'re currently playing' => 'ã³ã¬ã¯ã·ã§ã³ã®ä¸ã§ç¾å¨ãã¬ã¼ãã¦ããã²ã¼ã ',
+ 'Comments you have made on the web' => 'ã¦ã§ãã§æç¨¿ããã³ã¡ã³ã',
+ '[_1] commented on <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ã«ã³ã¡ã³ããã¾ãã',
+ 'Colors' => 'ã«ã©ã¼',
+ 'Colors you saved' => 'ä¿åããã«ã©ã¼',
+ '[_1] saved the color <a href="[_2]">[_3]</a>' => '[_1]ã¯ã«ã©ã¼(<a href="[_2]">[_3]</a>)ãä¿åãã¾ãã',
+ 'Palettes' => 'ãã¬ãã',
+ 'Palettes you saved' => 'ä¿åãããã¬ãã',
+ '[_1] saved the palette <a href="[_2]">[_3]</a>' => '[_1]ã¯ãã¬ãã(<a href="[_2]">[_3]</a>)ãä¿åãã¾ãã',
+ 'Patterns' => 'ãã¿ã¼ã³',
+ 'Patterns you saved' => 'ä¿åãããã¿ã¼ã³',
+ '[_1] saved the pattern <a href="[_2]">[_3]</a>' => '[_1]ã¯ãã¿ã¼ã³(<a href="[_2]">[_3]</a>)ãä¿åãã¾ãã',
+ 'Favorite Palettes' => 'ãæ°ã«å
¥ãã®ãã¬ãã',
+ 'Palettes you saved as favorites' => 'ä¿åãããæ°ã«å
¥ãã®ãã¬ãã',
+ '[_1] saved <a href="[_2]">[_3]</a> as a favorite palette' => '[_1]ã¯ãæ°ã«å
¥ãã®ãã¬ãã(<a href="[_2]">[_3]</a>)ãä¿åãã¾ããã',
+ 'Reviews' => 'ã¬ãã¥ã¼',
+ 'Your wine reviews' => 'ã¯ã¤ã³ã¬ãã¥ã¼',
+ '[_1] reviewed <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ãã¬ãã¥ã¼ãã¾ãã',
+ 'Cellar' => 'ã»ã©ã¼',
+ 'Wines you own' => 'ææãã¦ããã¯ã¤ã³',
+ '[_1] owns <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ãææãã¾ã',
+ 'Shopping List' => 'è²·ç©ãªã¹ã',
+ 'Wines you want to buy' => 'è²·ãããã¯ã¤ã³',
+ '[_1] wants <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ãæ±ãã¦ã¾ã',
+ 'Links' => 'ãªã³ã¯',
+ 'Your public links' => 'å
¬éãªã³ã¯',
+ '[_1] saved the link <a href="[_2]">[_3]</a>' => '[_1]ã¯ãªã³ã¯(<a href="[_2]">[_3]</a>)ãä¿åãã¾ãã',
+ 'Dugg' => 'ãã°',
+ 'Links you dugg' => 'ãã°ãããªã³ã¯',
+ '[_1] dugg the link <a href="[_2]">[_3]</a>' => '[_1]ã¯ãªã³ã¯(<a href="[_2]">[_3]</a>)ããã°ãã¾ãã',
+ 'Submissions' => 'æ¿èª',
+ 'Links you submitted' => 'æ¿èªãããªã³ã¯',
+ '[_1] submitted the link <a href="[_2]">[_3]</a>' => '[_1]ã¯ãªã³ã¯(<a href="[_2]">[_3]</a>)ãæç¨¿ãã¾ãã',
+ 'Found' => 'è¦ã¤ãã',
+ 'Photos you found' => 'è¦ã¤ããåç',
+ '[_1] ffffound <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ãè¦ã¤ãã¾ãã',
+ 'Favorites' => 'ãæ°ã«å
¥ã',
+ 'Photos you marked as favorites' => 'ãæ°ã«å
¥ãã«ããåç',
+ '[_1] saved <a href="[_2]">[_3]</a> as a favorite photo' => '[_1]ã¯ãæ°ã«å
¥ãã®åç(<a href="[_2]">[_3]</a>)ãä¿åãã¾ãã',
+ 'Photos' => 'åç',
+ 'Photos you posted' => 'ä¿åããåç',
+ '[_1] posted <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ãæç¨¿ãã¾ãã',
+ 'Likes' => 'ãªã³ã¯',
+ 'Things from your friends that you "like"' => '好ã¿ã®ã¦ã¼ã¶ã¼ã®ç©',
+ '[_1] likes <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ããªã³ã¯ãã¾ã',
+ 'Leaderboard scores' => 'ãªã¼ãã¼ãã¼ãã¹ã³ã¢',
+ 'Your high scores in games with leaderboards' => 'ãªã¼ãã¼ãã¼ãã®ã²ã¼ã ã®ãã¤ã¹ã³ã¢',
+ '[_1] scored <strong>[_2]</strong> in <a href="[_3]">[_4]</a>' => '[_1]ã¯<a href="[_3]">[_4]</a>ã®<strong>[_2]</strong>ã«ç¹æ°ãã¤ãã¾ãã',
+ 'Posts' => 'è¨äº',
+ 'Blog posts about your search term' => 'æ¤ç´¢ã¯ã¼ãã«ã¤ãã¦ã®ããã°è¨äº',
+ 'Google Blog Search result: <a href="[_2]">[_3]</a>' => 'Googleããã°æ¤ç´¢çµæ: <a href="[_2]">[_3]</a>',
+ 'Stories' => 'ã¹ãã¼ãªã¼',
+ 'News Stories matching your search' => 'æ¤ç´¢ã§ã®æ°ããã¹ãã¼ãªã¼ã¨ã®ä¸è´',
+ 'Google News search result: <a href="[_2]">[_3]</a>' => 'Googleãã¥ã¼ã¹æ¤ç´¢çµæ: <a href="[_2]">[_3]</a>',
+ 'To read' => 'ããããèªã',
+ 'Books on your "to-read" shelf' => 'æ¬æ£ã®ããããèªãæ¬',
+ '[_1] saved <a href="[_2]"><i>[_3]</i> by [_4]</a> to read' => '[_1]ã¯èªã¿ç©(<a href="[_2]">[_4]ã®<i>[_3]</i></a>)ãä¿åãã¾ãã',
+ 'Reading' => 'èªãã§ãã',
+ 'Books on your "currently-reading" shelf' => 'æ¬æ£ã®èªãã§ããæ¬',
+ '[_1] started reading <a href="[_2]"><i>[_3]</i> by [_4]</a>' => '[_1]ã¯<a href="[_2]">[_4]ã®<i>[_3]</i></a>ãèªã¿å§ãã¾ãã',
+ 'Read' => 'èªã',
+ 'Books on your "read" shelf' => 'æ¬æ£ã®èªãæ¬',
+ '[_1] finished reading <a href="[_2]"><i>[_3]</i> by [_4]</a>' => '[_1]ã¯<a href="[_2]">[_4]ã®<i>[_3]</i></a>ãèªã¿çµããã¾ãã',
+ 'Shared' => 'å
±æ',
+ 'Your shared items' => 'å
±æã¢ã¤ãã ',
+ '[_1] shared <a href="[_2]">[_3]</a> from <a href="[_4]">[_5]</a>' => '[_1]ã¯<a href="[_4]">[_5]</a>ã®<a href="[_2]">[_3]</a>ãå
±æãã¾ãã',
+ 'Deliveries' => 'é
å¸',
+ 'Icon sets you were delivered' => 'é
å¸ãããã¢ã¤ã³ã³ã»ãã',
+ '[_1] received the icon set <a href="[_2]">[_3]</a>' => '[_1]ã¯ã¢ã¤ã³ã³ã»ãã(<a href="[_2]">[_3]</a>)ãåãåãã¾ãã',
+ 'Notices' => 'éç¥',
+ 'Notices you posted' => 'æç¨¿ããéç¥',
+ '[_1] <a href="[_2]">said</a>, “[_3]”' => '[_1]㯓[_3]”ã¨<a href="[_2]">è¨ãã¾ãã</a>',
+ 'Intas' => 'Intas',
+ 'Links you saved' => 'ä¿åãããªã³ã¯',
+ '[_1] is inta <a href="[_2]">[_3]</a>' => '[_1]ã¯ã¤ã³ã¿(<a href="[_2]">[_3]</a>)ã§ã',
+ 'Photos you posted that were approved' => 'æ¿èªããæç¨¿ããåç',
+ 'Recent events' => 'æè¿ã®ã¤ãã³ã',
+ 'Events from your recent events feed' => 'æè¿ã®ã¤ãã³ããã£ã¼ãã®ã¤ãã³ã',
+ '[_1] <a href="[_2]">[_3]</a>' => '[_1] <a href="[_2]">[_3]</a>',
+ 'Apps you use' => '使ç¨ã¢ããª',
+ 'The applications you saved as ones you use' => '使ç¨ããã¢ããªã±ã¼ã·ã§ã³',
+ '[_1] started using <a href="[_2]">[_3]</a>[quant,_4, (and loves it),,]' => '[_1]ã¯<a href="[_2]">[_3]</a>([quant,_4, (大好ã),,])ã使ãå§ãã¾ãã',
+ 'Videos you saved as watched' => 'è¦ããããª',
+ '[_1] saved <a href="[_2]">[_3]</a> as a favorite video' => '[_1]ã¯ãæ°ã«å
¥ãã®ãããª(<a href="[_2]">[_3]</a>)ãä¿åãã¾ãã',
+ 'Jaikus' => 'Jaikus',
+ 'Jaikus you posted' => 'æç¨¿ããJaikus',
+ '[_1] <a href="[_2]">jaiku\'\'d</a>, "[_3]"' => '[_1]ã¯"[_3]"ã<a href="[_2]">Jaiku</a>ãã¾ãã',
+ 'Games you saved as favorites' => 'ãæ°ã«å
¥ãã«ããã²ã¼ã ',
+ '[_1] saved <a href="[_2]">[_3]</a> as a favorite game' => '[_1]ã¯ãæ°ã«å
¥ãã®ã²ã¼ã (<a href="[_2]">[_3]</a>)ãä¿åãã¾ãã',
+ 'Achievements' => 'ææ',
+ 'Achievements you won' => 'ç²å¾ããææ',
+ '[_1] won the <strong>[_2]</strong> in <a href="[_3]">[_4]</a>' => '[_1]ã¯<a href="[_3]">[_4]</a>ã®<strong>[_2]</strong>ãç²å¾ãã¾ãã',
+ 'Tracks' => 'æ²',
+ 'Songs you recently listened to (High spam potential!)' => 'æè¿èããæ(ã¹ãã ã®å¯è½æ§ãã)',
+ '[_1] heard <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ãèãã¾ãã',
+ 'Loved Tracks' => '大好ããªæ²',
+ 'Songs you marked as "loved"' => '大好ãã¨ãã¼ã¯ããæ',
+ '[_1] loved <a href="[_2]">[_3]</a> by [_4]' => '[_1]ã¯[_4]ã®<a href="[_2]">[_3]</a>ã大好ãã«ãªãã¾ãã',
+ 'Journal Entries' => 'ã¸ã£ã¼ãã«è¨äº',
+ 'Your recent journal entries' => 'æè¿ã®ã¸ã£ã¼ãã«è¨äº',
+ 'Events' => 'ã¤ãã³ã',
+ 'The events you said you\'ll be attending' => 'åå 表æããã¤ãã³ã',
+ '[_1] is attending <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ã«åå ãã¾ã',
+ 'Your public posts to your journal' => 'å
¬éæç¨¿ã®ã¸ã£ã¼ãã«',
+ 'Queue' => 'å¾
ã¡ãªã¹ã',
+ 'Movies you added to your rental queue' => 'ã¬ã³ã¿ã«ãªã¹ãã«å
¥ããæ ç»',
+ '[_1] queued <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ãå¾
ã¡ã¾ãã',
+ 'Recent Movies' => 'æè¿ã®æ ç»',
+ 'Recent Rental Activity' => 'æè¿ã®ã¬ã³ã¿ã«æ´»å',
+ '[_1] is watching <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ãè¦ã¦ãã¾ã',
+ 'Kudos' => 'Kudos',
+ 'Kudos you have received' => 'åãåã£ãKudos',
+ '[_1] received kudos from <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ããç§°è³ãå¾ã¾ãã',
+ 'Favorite Songs' => 'ãæ°ã«å
¥ãã®æ',
+ 'Songs you marked as favorites' => 'ãæ°ã«å
¥ãã«ããæ',
+ '[_1] saved <a href="[_2]">[_3]</a> as a favorite song' => '[_1]ã¯ãæ°ã«å
¥ãã®æ(<a href="[_2]">[_3]</a>)ãä¿åãã¾ãã',
+ 'Favorite Artists' => 'ãæ°ã«å
¥ãã®ã¢ã¼ãã£ã¹ã',
+ 'Artists you marked as favorites' => 'ãæ°ã«å
¥ãã«ããã¢ã¼ãã£ã¹ã',
+ '[_1] saved <a href="[_2]">[_3]</a> as a favorite artist' => '[_1]ã¯ãæ°ã«å
¥ãã®ã¢ã¼ãã£ã¹ã(<a href="[_2]">[_3]</a>)ãä¿åãã¾ãã',
+ 'Stations' => 'ã¹ãã¼ã·ã§ã³',
+ 'Radio stations you added' => '追å ããã©ã¸ãªã¹ãã¼ã·ã§ã³',
+ '[_1] added a new radio station named <a href="[_2]">[_3]</a>' => '[_1]ã¯æ°ããã©ã¸ãªã¹ãã¼ã·ã§ã³(<a href="[_2]">[_3]</a>)ã追å ãã¾ãã',
+ 'List' => 'ãªã¹ã',
+ 'Things you put in your list' => 'ãªã¹ãã«å
¥ããç©',
+ '[_1] is enjoying <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ãæ¥½ããã§ãã¾ã',
+ 'Notes' => 'ã¡ã¢',
+ 'Your public notes' => 'å
¬éã¡ã¢',
+ '[_1] <a href="[_2]">posted</a>, "[_3]"' => '[_1]ã¯"[_3]"ã<a href="[_2]">æç¨¿</a>ãã¾ãã',
+ 'Comments you posted' => 'æç¨¿ããã³ã¡ã³ã',
+ '[_1] commented on <a href="[_2]">[_3]</a> at Reddit' => '[_1]ã¯Redditã§<a href="[_2]">[_3]</a>ã«ã³ã¡ã³ããã¾ãã',
+ 'Articles you submitted' => 'æç¨¿ããè¨äº',
+ '[_1] submitted <a href="[_2]">[_3]</a> to Reddit' => '[_1]ã¯Redditã«<a href="[_2]">[_3]</a>ãæç¨¿ãã¾ãã',
+ 'Articles you liked (your votes must be public)' => '好ããªè¨äº(å
¬éã«ãã¦ãã¾ã)',
+ '[_1] liked <a href="[_2]">[_3]</a> from Reddit' => '[_1]ã¯Redditã®<a href="[_2]">[_3]</a>ã好ãã«ãªãã¾ãã',
+ 'Dislikes' => 'å«ã',
+ 'Articles you disliked (your votes must be public)' => 'å«ããªè¨äº(å
¬éã«ãã¦ãã¾ã)',
+ '[_1] disliked <a href="[_2]">[_3]</a> on Reddit' => '[_1]ã¯Redditã®<a href="[_2]">[_3]</a>ãå«ãã«ãªãã¾ãã',
+ 'Slideshows you saved as favorites' => 'ãæ°ã«å
¥ãã«ããã¹ã©ã¤ãã·ã§ã¼',
+ '[_1] saved <a href="[_2]">[_3]</a> as a favorite slideshow' => '[_1]ã¯ãæ°ã«å
¥ãã®ã¹ã©ã¤ãã·ã§ã¼(<a href="[_2]">[_3]</a>)ãä¿åãã¾ãã',
+ 'Slideshows' => 'ã¹ã©ã¤ãã·ã§ã¼',
+ 'Slideshows you posted' => 'æç¨¿ããã¹ã©ã¤ãã·ã§ã¼',
+ '[_1] posted the slideshow <a href="[_2]">[_3]</a>' => '[_1]ã¯ã¹ã©ã¤ãã·ã§ã¼(<a href="[_2]">[_3]</a>)ãä¿åãã¾ãã',
+ '[_1] posted <a href="[_2]">a photo</a>' => '[_1]ã¯<a href="[_2]">åç</a>ãä¿åãã¾ãã',
+ 'Your achievements for achievement-enabled games' => 'ææã®åºãã²ã¼ã ã§ã®ææ',
+ '[_1] won the <strong>[_2]</strong> achievement in <a href="http://steamcommunity.com/id/[_3]/stats/[_4]?tab=achievements">[_5]</a>' => '[_1]ã¯<a href="http://steamcommunity.com/id/[_3]/stats/[_4]?tab=achievements">[_5]</a>ã§ææ(<strong>[_2]</strong>)ãç²å¾ãã¾ãã',
+ 'Technorati blog search result: <a href="[_2]">[_3]</a>' => 'Technoratiããã°æ¤ç´¢çµæ: <a href="[_2]">[_3]</a>',
+ 'Stuff' => 'ç©',
+ 'Things you posted' => 'æç¨¿ããç©',
+ 'Tweets' => 'Tweet',
+ 'Your public tweets' => 'å
Žtweet',
+ '[_1] <a href="[_2]">tweeted</a>, "[_3]"' => '[_1]ã¯"[_3]"ã<a href="[_2]">tweet</a>ãã¾ãã',
+ 'Public tweets you saved as favorites' => 'ãæ°ã«å
¥ãã«ããå
Žtweet',
+ '[_1] saved <a href="[_2]">[_3]\'\'s tweet</a>, "[_4]" as a favorite' => '[_1]ã¯ãæ°ã«å
¥ãã®<a href="[_2]">[_3]ã®tweet</a>("[_4]")ãä¿åãã¾ãã',
+ 'Tweets about your search term' => 'æ¤ç´¢ã¯ã¼ãã«ã¤ãã¦ã®Tweet',
+ 'Twitter Search result: <a href="[_2]">[_3]</a>' => 'Twitteræ¤ç´¢çµæ: <a href="[_2]">[_3]</a>',
+ '[_1] left a comment on <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ã«ã³ã¡ã³ããæ®ãã¾ãã',
+ 'Saved' => 'ä¿å',
+ 'Things you saved as favorites' => 'ãæ°ã«å
¥ãã«ããç©',
+ '[_1] saved <a href="[_2]">[_3]</a> on Uncrate' => '[_1]ã¯Uncrateã®<a href="[_2]">[_3]</a>ãä¿åãã¾ãã',
+ 'Events you are watching or attending' => 'è¦ã¦ããã¾ãã¯åå ãã¦ããã¤ãã³ã',
+ '[_1] is attending <a href="[_2]">[_3]</a> at [_4]' => '[_1]ã¯[_4]ã§<a href="[_2]">[_3]</a>ã«åå ãã¦ãã¾ã',
+ 'Videos you posted' => 'æç¨¿ãããããª',
+ 'Videos you liked' => 'ãªã³ã¯ãããããª',
+ '[_1] liked <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ã好ãã«ãªãã¾ãã',
+ 'Public assets you saved as favorites' => 'ãæ°ã«å
¥ãã«ããå
¬éã¢ã¤ãã ',
+ '[_1] saved <a href="[_2]">[_3]</a> as a favorite' => '[_1]ã¯ãæ°ã«å
¥ã(<a href="[_2]">[_3]</a>)ãä¿åãã¾ãã',
+ 'Your public photos in your Vox library' => 'Voxã®å
¬éåç',
+ 'Your public posts to your Vox' => 'Voxã®å
¬éè¨äº',
+ 'The posts available from the website\'s feed' => 'ã¦ã§ããµã¤ãã®ãã£ã¼ãã§æå¹ãªè¨äº',
+ '[_1] posted <a href="[_2]">[_3]</a> on <a href="[_4]">[_5]</a>' => '[_1]ã¯<a href="[_4]">[_5]</a>ã§<a href="[_2]">[_3]</a>ãæç¨¿ãã¾ãã',
+ 'Stuff you saved' => 'ä¿åããç©',
+ 'Gamerscore' => 'ã²ã¼ã ã¹ã³ã¢',
+ 'Notes when your gamerscore passes an even number' => 'ã²ã¼ã ã¹ã³ã¢ãåç¹ããããæã®ã¡ã¢',
+ '[_1] passed <strong>[_2]</strong> gamerscore <a href="[_3]">on Xbox Live</a>' => '[_1]ã¯<a href="[_3]">Xbox Live</a>ã§ã²ã¼ã ã¹ã³ã¢(<strong>[_2]</strong>)ãæ¸¡ãã¾ãã',
+ 'Places you reviewed' => 'ã¬ãã¥ã¼ããå ´æ',
+ 'Videos you saved as favorites' => 'ãæ°ã«å
¥ãã«ãããããª',
+ '[_1] posted <a href="[_2]">[_3]</a> to YouTube' => '[_1]ã¯YouTubeã«<a href="[_2]">[_3]</a>ãæç¨¿ãã¾ãã',
+
+## plugins/CommunityActionStreams/config.yaml
+ '[_1] <a href="[_2]">commented</a> on <a href="[_3]">[_4]</a>' => '[_1]ã¯<a href="[_3]">[_4]</a>ã«<a href="[_2]">ã³ã¡ã³ã</a>ãã¾ãã',
+ '[_1] posted <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ãæç¨¿ãã¾ãã',
+ '[_1] saved <a href="[_2]">[_3]</a> as a favorite' => '[_1]ã¯<a href="[_2]">[_3]</a>ããæ°ã«å
¥ãã«è¿½å ãã¾ãã',
+ '[_1] is now following <a href="[_2]">[_3]</a>' => '[_1]ã¯<a href="[_2]">[_3]</a>ãæ³¨ç®ãã¦ãã¾ã',
+
+);
+
+1;
diff --git a/plugins/ActionStreams/lib/ActionStreams/L10N/nl.pm b/plugins/ActionStreams/lib/ActionStreams/L10N/nl.pm
new file mode 100644
index 0000000..b5a99ac
--- /dev/null
+++ b/plugins/ActionStreams/lib/ActionStreams/L10N/nl.pm
@@ -0,0 +1,352 @@
+# Movable Type (r) (C) 2001-2008 Six Apart, Ltd. All Rights Reserved.
+# This code cannot be redistributed without permission from www.sixapart.com.
+# For more information, consult your Movable Type license.
+#
+# $Id: nl.pm 99820 2009-03-09 13:55:28Z mschenk $
+
+package ActionStreams::L10N::nl;
+
+use strict;
+use base 'ActionStreams::L10N::en_us';
+use vars qw( %Lexicon );
+%Lexicon = (
+## plugins/ActionStreams/blog_tmpl/sidebar.mtml
+
+## plugins/ActionStreams/blog_tmpl/main_index.mtml
+
+## plugins/ActionStreams/blog_tmpl/actions.mtml
+ 'Recent Actions' => 'Recente acties',
+
+## plugins/ActionStreams/blog_tmpl/archive.mtml
+
+## plugins/ActionStreams/blog_tmpl/banner_footer.mtml
+
+## plugins/ActionStreams/blog_tmpl/elsewhere.mtml
+ 'Find [_1] Elsewhere' => 'Elders [_1] vinden',
+
+## plugins/ActionStreams/streams.yaml
+ 'Currently Playing' => 'Nu aan het spelen',
+ 'The games in your collection you\'re currently playing' => 'De spelletjes in uw collectie die u momenteel aan het spelen bent',
+ 'Comments you have made on the web' => 'Reacties die u elders op het web heeft achtergelaten',
+ 'Colors' => 'Kleuren',
+ 'Colors you saved' => 'Kleuren die u heeft opgeslagen',
+ 'Palettes' => 'Paletten',
+ 'Palettes you saved' => 'Paletten die u heeft opgeslagen',
+ 'Patterns' => 'Patronen',
+ 'Patterns you saved' => 'Patronen die u heeft opgeslagen',
+ 'Favorite Palettes' => 'Favoriete paletten',
+ 'Palettes you saved as favorites' => 'Paletten die u heeft opgeslagen als favorieten',
+ 'Reviews' => 'Besprekingen',
+ 'Your wine reviews' => 'Uw wijnbesprekingen',
+ 'Cellar' => 'Kelder',
+ 'Wines you own' => 'Wijnen die u bezit',
+ 'Shopping List' => 'Boodschappenlijstje',
+ 'Wines you want to buy' => 'Wijnen die u wenst te kopen',
+ 'Links' => 'Links',
+ 'Your public links' => 'Uw publieke links',
+ 'Dugg' => 'Dugg',
+ 'Links you dugg' => 'Links die u \'dugg\' op Digg',
+ 'Submissions' => 'Ingediend',
+ 'Links you submitted' => 'Links die u indiende',
+ 'Found' => 'Gevonden',
+ 'Photos you found' => 'Foto\'s die u vond',
+ 'Favorites' => 'Favorieten',
+ 'Photos you marked as favorites' => 'Foto\'s die u aanmerkte als favorieten',
+ 'Photos' => 'Foto\'s',
+ 'Photos you posted' => 'Foto\'s die u publiceerde',
+ 'Likes' => 'Geappreciëerd',
+ 'Things from your friends that you "like"' => 'Dingen van uw vrienden die u appreciëerde',
+ 'Leaderboard scores' => 'Scores in de rangschikkingen',
+ 'Your high scores in games with leaderboards' => 'Uw hoogste score in spelletjes met een rangschikking',
+ 'Posts' => 'Berichten',
+ 'Blog posts about your search term' => 'Blogberichten over uw zoekterm',
+ 'Stories' => 'Nieuws',
+ 'News Stories matching your search' => 'Nieuwsberichten over uw zoekterm',
+ 'To read' => 'Te lezen',
+ 'Books on your "to-read" shelf' => 'Boeken op uw \'te lezen\' boekenplank',
+ 'Reading' => 'Aan het lezen',
+ 'Books on your "currently-reading" shelf' => 'Boeken op uw \'momenteel aan het lezen\' boekenplank',
+ 'Read' => 'Gelezen',
+ 'Books on your "read" shelf' => 'Boeken op uw \'gelezen\' boekenplank',
+ 'Shared' => 'Gedeeld',
+ 'Your shared items' => 'Uw gedeelde items',
+ 'Deliveries' => 'Leveringen',
+ 'Icon sets you were delivered' => 'Icoonsets die u geleverd werden',
+ 'Notices' => 'Berichtjes',
+ 'Notices you posted' => 'Berichtjes die u plaatste',
+ 'Intas' => 'Intas',
+ 'Links you saved' => 'Links die u bewaarde',
+ 'Photos you posted that were approved' => 'Foto\'s die u publiceerde en die werden goedgekeurd',
+ 'Recent events' => 'Recente gebeurtenissen',
+ 'Events from your recent events feed' => 'Gebeurtenissen uit uw feed met recente gebeurtenissen',
+ 'Apps you use' => 'Applicaties die u gebruikt',
+ 'The applications you saved as ones you use' => 'De applicaties die u heeft opgeslagen als applicaties die u gebruikt',
+ 'Videos you saved as watched' => 'Video\'s die u heeft opgeslagen als bekeken',
+ 'Jaikus' => 'Jaikus',
+ 'Jaikus you posted' => 'Jaikus die u publiceerde',
+ 'Games you saved as favorites' => 'Spelletjes die u heeft opgeslagen als favorieten',
+ 'Achievements' => 'Mijlpalen',
+ 'Achievements you won' => 'Mijlpalen die u bereikt heeft',
+ 'Tracks' => 'Tracks',
+ 'Songs you recently listened to (High spam potential!)' => 'Liedjes waar u recent naar geluisterd heeft (hoge kans op spam!)',
+ 'Loved Tracks' => 'Geliefde tracks',
+ 'Songs you marked as "loved"' => 'Tracks waarvan u heeft aangegeven dat u ervan houdt',
+ 'Journal Entries' => 'Dagboekberichten',
+ 'Your recent journal entries' => 'Uw laatste berichten uit uw dagboek',
+ 'Events' => 'Gebeurtenissen',
+ 'The events you said you\'ll be attending' => 'De evenementen waarvan u gezegd hebt dat u er zal zijn',
+ 'Your public posts to your journal' => 'Uw publieke berichten op uw dagboek',
+ 'Queue' => 'Wachtrij',
+ 'Movies you added to your rental queue' => 'Films toegevoegd aan uw huurwachtrij',
+ 'Recent Movies' => 'Recente films',
+ 'Recent Rental Activity' => 'Recente huuractiviteit',
+ 'Kudos' => 'Kudos',
+ 'Kudos you have received' => 'Kudos die u heeft ontvangen',
+ 'Favorite Songs' => 'Favoriete liedjes',
+ 'Songs you marked as favorites' => 'Liedjes die u heeft aangemerkt als favorieten',
+ 'Favorite Artists' => 'Favoriete artiesten',
+ 'Artists you marked as favorites' => 'Artiesten die u heeft aangemerkt als favorieten',
+ 'Stations' => 'Zenders',
+ 'Radio stations you added' => 'Radiozenders die u heeft toegevoegd',
+ 'List' => 'Lijst',
+ 'Things you put in your list' => 'Dingen die u in uw lijst heeft gezet',
+ 'Notes' => 'Berichtjes',
+ 'Your public notes' => 'Uw publieke berichtjes',
+ 'Comments you posted' => 'Reacties die u gepubliceerd heeft',
+ 'Articles you submitted' => 'Artikels die u heeft ingediend',
+ 'Articles you liked (your votes must be public)' => 'Artikels die u heeft aangemerkt als favorieten',
+ 'Dislikes' => 'Afgekeurd',
+ 'Articles you disliked (your votes must be public)' => 'Artikels waar u een afkeer voor heeft laten blijken (stemmen moeten publiek zijn)',
+ 'Slideshows you saved as favorites' => 'Diavoorstellingen die u als favorieten heeft opgeslagen',
+ 'Slideshows' => 'Diavoorstellingen',
+ 'Slideshows you posted' => 'Diavoorstellingen die u publiceerde',
+ 'Your achievements for achievement-enabled games' => 'Uw mijlpalen in spelletjes die mijlpalen hebben',
+ 'Stuff' => 'Dinges',
+ 'Things you posted' => 'Dingen die u publiceerde',
+ 'Tweets' => 'Tweets',
+ 'Your public tweets' => 'Uw publieke tweets',
+ 'Public tweets you saved as favorites' => 'Publieke tweets die u opgeslagen heeft als favorieten',
+ 'Tweets about your search term' => 'Tweets over uw zoekterm',
+ 'Saved' => 'Opgeslagen',
+ 'Things you saved as favorites' => 'Dingen die u heeft opgeslagen als favorieten',
+ 'Events you are watching or attending' => 'Evenementen die u bekijkt of bijwoont',
+ 'Videos you posted' => 'Video\'s die u publiceerde',
+ 'Videos you liked' => 'Video\'s die u goed vond',
+ 'Public assets you saved as favorites' => 'Publieke mediabestanden die u opsloeg als favorieten',
+ 'Your public photos in your Vox library' => 'Uw publieke foto\'s in uw Vox bibliotheek',
+ 'Your public posts to your Vox' => 'Uw publieke berichten op uw Vox',
+ 'The posts available from the website\'s feed' => 'De berichten beschikbaar op de feed van de website',
+ 'Wists' => 'Wists',
+ 'Stuff you saved' => 'Dingen die u opsloeg',
+ 'Gamerscore' => 'Gamerscore',
+ 'Notes when your gamerscore passes an even number' => 'Berichtjes over wanneer uw gamerscore een even getal passeert',
+ 'Places you reviewed' => 'Plaatsen die u heeft besproken',
+ 'Videos you saved as favorites' => 'Video\'s die u heeft opgeslagen als favorieten',
+
+## plugins/ActionStreams/services.yaml
+ '1up.com' => '1up.com',
+ '43Things' => '43Things',
+ 'Screen name' => 'Nickname',
+ 'backtype' => 'backtype',
+ 'Bebo' => 'Bebo',
+ 'Catster' => 'Catster',
+ 'COLOURlovers' => 'COLOURlovers',
+ 'Cork\'\'d\'' => 'Cork\'\'d\'',
+ 'Delicious' => 'Delicious',
+ 'Destructoid' => 'Destructoid',
+ 'Digg' => 'Digg',
+ 'Dodgeball' => 'Dodgeball',
+ 'Dogster' => 'Dogster',
+ 'Dopplr' => 'Dopplr',
+ 'Facebook' => 'Facebook',
+ 'User ID' => 'Gebruikers ID',
+ 'You can find your Facebook userid within your profile URL. For example, http://www.facebook.com/profile.php?id=24400320.' => 'U kunt uw Facebook userid terugvinden in de URL van uw profiel. Bijvoorbeeld, http://www.facebook.com/profile.php?id=24400320.',
+ 'FFFFOUND!' => 'FFFFOUND',
+ 'Flickr' => 'Flickr',
+ 'Enter your Flickr userid which contains "@" in it, e.g. 36381329@N00. Flickr userid is NOT the username in the URL of your photostream.' => 'Vul uw Flickr userid in (dit bevat een "@", bijvoorbeeld 36381329@N00). Het Flickr userid is niet de gebruikersnaam in uw photostream',
+ 'FriendFeed' => 'FriendFied',
+ 'Gametap' => 'Gametap',
+ 'Google Blogs' => 'Google Blogs',
+ 'Search term' => 'Zoekterm',
+ 'Google News' => 'Google News',
+ 'Search for' => 'Zoeken naar',
+ 'Goodreads' => 'Goodreads',
+ 'You can find your Goodreads userid within your profile URL. For example, http://www.goodreads.com/user/show/123456.' => 'U kunt uw Goodreads userid vinden in de URL van uw profiel. Bijvoorbeeld http://www.goodreads.com/user/show/123456.',
+ 'Google Reader' => 'Google Reader',
+ 'Sharing ID' => 'Sharing ID',
+ 'Hi5' => 'Hi5',
+ 'IconBuffet' => 'IconBuffet',
+ 'ICQ' => 'ICQ',
+ 'UIN' => 'UIN',
+ 'Identi.ca' => 'Identi.ca',
+ 'Iminta' => 'Iminta',
+ 'iStockPhoto' => 'iStockPhoto',
+ 'You can find your istockphoto userid within your profile URL. For example, http://www.istockphoto.com/user_view.php?id=1234567.' => 'U kunt uw iStockPhoto userid vinden in de URL van uw profiel. Bijvoorbeeld, http://www.istockphoto.com/user_view.php?id=1234567.',
+ 'IUseThis' => 'iUseThis',
+ 'iwatchthis' => 'iwatchthis',
+ 'Jabber' => 'Jabber',
+ 'Jabber ID' => 'Jabber ID',
+ 'Jaiku' => 'Jaiku',
+ 'Kongregate' => 'Kongregate',
+ 'Last.fm' => 'Last.fm',
+ 'LinkedIn' => 'LinkedIn',
+ 'Profile URL' => 'URL van profiel',
+ 'Ma.gnolia' => 'Ma.gnolia',
+ 'MOG' => 'MOG',
+ 'MSN Messenger\'' => 'MSN Messenger',
+ 'Multiply' => 'Multiply',
+ 'MySpace' => 'MySpace',
+ 'Netflix' => 'Netflix',
+ 'Netflix RSS ID' => 'Netflix RSS ID',
+ 'To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.' => 'Om uw Netflix RSS ID terug te vinden, moet u op "RSS" klikken onderaan éénder welke pagina op de Netflix site en dan uw "Queue" link knippen en plakken.',
+ 'Netvibes' => 'Netvibes',
+ 'Newsvine' => 'Newsvine',
+ 'Ning' => 'Ning',
+ 'Social Network URL' => 'Sociaal netwerk URL',
+ 'Ohloh' => 'Ohloh',
+ 'Orkut' => 'Orkut',
+ 'You can find your orkut uid within your profile URL. For example, http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789' => 'U kunt uw Orkut uid terugvinden in de URL van uw profiel. Bijvoorbeeld, http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789',
+ 'Pandora' => 'Pandora',
+ 'Picasa Web Albums' => 'Picasa Web Albums',
+ 'p0pulist' => 'p0pulist',
+ 'You can find your p0pulist user id within your Hot List URL. for example, http://p0pulist.com/list/hot_list/10000' => 'U kunt uw p0pulist userid terugvinden in de URL van uw Hot List. Bijvoorbeeld, http://p0pulist.com/list/hot_list/10000',
+ 'Pownce' => 'Pownce',
+ 'Reddit' => 'Reddit',
+ 'Skype' => 'Skype',
+ 'SlideShare' => 'SlideShare',
+ 'Smugmug' => 'Smugmug',
+ 'SonicLiving' => 'SonicLiving',
+ 'You can find your SonicLiving userid within your share&subscribe URL. For example, http://sonicliving.com/user/12345/feeds' => 'U kunt uw SonicLiving userid vinden in uw share&subscribe URL. Bijvoorbeeld, http://sonicliving.com/user/12345/feeds',
+ 'Steam' => 'Steam',
+ 'StumbleUpon' => 'StumbleUpon',
+ 'Tabblo' => 'Tabblo',
+ 'Blank should be replaced by positive sign (+).' => 'Blank moet vervangen worden met een plusteken (+)',
+ 'Tribe' => 'Tribe',
+ 'You can find your tribe userid within your profile URL. For example, http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a.' => 'U kunt uw tribe userid terugvingen in de URL van uw profiel. Bijvoorbeeld, http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a.',
+ 'Tumblr' => 'Tumblr',
+ 'Twitter' => 'Twitter',
+ 'TwitterSearch' => 'TwitterSearch',
+ 'Uncrate' => 'Uncrate',
+ 'Upcoming' => 'Upcoming',
+ 'Viddler' => 'Viddler',
+ 'Vimeo' => 'Vimeo',
+ 'Virb' => 'Virb',
+ 'You can find your VIRB userid within your home URL. For example, http://www.virb.com/backend/2756504321310091/your_home.' => 'U kunt uw VIRB userid in uw home URL terugvinden. Bijvoorbeeld, http://www.virb.com/backend/2756504321310091/your_home.',
+ 'Vox name' => 'Vox-naam',
+ 'Website' => 'Website',
+ 'Xbox Live\'' => 'Xbox Live\'',
+ 'Gamertag' => 'Gamertag',
+ 'Yahoo! Messenger\'' => 'Yahoo! Messenger\'',
+ 'Yelp' => 'Yelp',
+ 'YouTube' => 'YouTube',
+ 'Zooomr' => 'Zooomr',
+
+## plugins/ActionStreams/config.yaml
+ 'Manages authors\' accounts and actions on sites elsewhere around the web' => 'Beheert account en acties van de auteurs elders op het web',
+ 'Are you sure you want to hide EVERY event in EVERY action stream?' => 'Bent u zeker dat u ELKE gebeurtenis in ELKE action stream wenst te verbergen?',
+ 'Are you sure you want to show EVERY event in EVERY action stream?' => 'Bent u zeker dat u ELKE gebeurtenis in ELKE action stream wenst te tonen?',
+ 'Deleted events that are still available from the remote service will be added back in the next scan. Only events that are no longer available from your profile will remain deleted. Are you sure you want to delete the selected event(s)?' => 'Verwijderde gebeurtenissen die nog steeds beschikbaar zijn via de externe service zullen opnieuw worden toegevoegd bij de volgende scan. Enkel gebeurtenissen die niet meer op uw profiel voorkomen zullen verwijderd blijven. Bent u zeker dat u de geselecteerde gebeurtenis(sen) wenst te verwijderen?',
+ 'Hide All' => 'Alles verbergen',
+ 'Show All' => 'Alles tonen',
+ 'Poll for new events' => 'Checken voor nieuwe gebeurtenissen',
+ 'Update Events' => 'Gebeurtenissen bijwerken',
+ 'Action Stream' => 'Action Stream',
+ 'Main Index (Recent Actions)' => 'Hoofdindex (recente acties)',
+ 'Action Archive' => 'Actie-archief',
+ 'Feed - Recent Activity' => 'Feed - Recente activiteit',
+ 'Find Authors Elsewhere' => 'Elders auteurs vinden',
+ 'Enabling default action streams for selected profiles...' => 'Standaard action streams inschakelen voor geselecteerde profielen...',
+
+## plugins/ActionStreams/lib/ActionStreams/Upgrade.pm
+ 'Updating classification of [_1] [_2] actions...' => 'Classificatie bij aan het werken voor [_1] [_2] acties...',
+ 'Renaming "[_1]" data of [_2] [_3] actions...' => '"[_1] gegevens van [_2] [_3] acties een nieuwe naam aan het geven...',
+
+## plugins/ActionStreams/lib/ActionStreams/Worker.pm
+ 'No such author with ID [_1]' => 'Geen auteur gevonden met ID [_1]',
+
+## plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+ 'Other Profiles' => 'Andere profielen',
+ 'Profiles' => 'Profielen',
+ 'Actions from the service [_1]' => 'Gebeurtenissen op service [_1]',
+ 'Actions that are shown' => 'Gebeurtenissen die worden weergegeven',
+ 'Actions that are hidden' => 'Gebeurtenissen die worden verborgen',
+ 'No such event [_1]' => 'Geen [_1] evenement gevonden',
+ '[_1] Profile' => '[_1] profiel',
+
+## plugins/ActionStreams/lib/ActionStreams/Tags.pm
+ 'No user [_1]' => 'Geen gebruiker [_1]',
+
+## plugins/ActionStreams/lib/ActionStreams/Event.pm
+ '[_1] updating [_2] events for [_3]' => '[_1] [_2] evenementen aan het bijwerken voor [_3]',
+ 'Error updating events for [_1]\'s [_2] stream (type [_3] ident [_4]): [_5]' => 'Fout bij het updaten van evenementen voor [_1]\'s [_2] stream (type [_3] ident [_4]: [5]',
+ 'Could not load class [_1] for stream [_2] [_3]: [_4]' => 'Kon klasse [_1] voor stream [_2] [_3] niet laden: [_4]',
+ 'No URL to fetch for [_1] results' => 'Geen URL binnen te halen voor [_1] resultaten', # Translate - New
+ 'Could not fetch [_1]: [_2]' => 'Kon [_1] niet binnenhalen: [_2]', # Translate - New
+ 'Aborted fetching [_1]: [_2]' => 'Ophalen [_1] geannuleerd: [_2]', # Translate - New
+
+## plugins/ActionStreams/tmpl/dialog_edit_profile.tmpl
+ 'Your user name or ID is required.' => 'Uw gebruikersnaam of ID is vereist.',
+ 'Edit a profile on a social networking or instant messaging service.' => 'Bewerk een profiel op een sociaal netwerk of instant messaging dienst.',
+ 'Service' => 'Service',
+ 'Enter your account on the selected service.' => 'Vul uw account op de geselecteerde service in.',
+ 'For example:' => 'Bijvoorbeeld:',
+ 'Action Streams' => 'Action Streams',
+ 'Select the action streams to collect from the selected service.' => 'Selecteer de action streams die opgehaald moeten worden van de geselecteerde service.',
+ 'No streams are available for this service.' => 'Geen streams beschikbaar van deze service',
+
+## plugins/ActionStreams/tmpl/other_profiles.tmpl
+ 'The selected profile was added.' => 'Het geselecteerde profiel werd toegevoegd.',
+ 'The selected profiles were removed.' => 'De geselecteerde profielen werden verwijderd.',
+ 'The selected profiles were scanned for updates.' => 'De geselecteerde profielen werden gescand op updates.',
+ 'The changes to the profile have been saved.' => 'De wijzigingen aan het profiel werden opgeslagen.',
+ 'Add Profile' => 'Prfiel toevoegen',
+ 'profile' => 'profiel',
+ 'profiles' => 'profielen',
+ 'Delete selected profiles (x)' => 'Geselecteerde profielen verwijderen (x)',
+ 'to update' => 'om bij te werken',
+ 'Scan now for new actions' => 'Nu scannen op nieuwe gebeurtenissen',
+ 'Update Now' => 'Nu bijwerken',
+ 'No profiles were found.' => 'Geen profielen gevonden',
+ 'external_link_target' => 'external_link_target',
+ 'View Profile' => 'Profiel bekijken',
+
+## plugins/ActionStreams/tmpl/dialog_add_profile.tmpl
+ 'Add a profile on a social networking or instant messaging service.' => 'Voeg een profiel toe op een sociaal netwerk of een instant messaging dienst.',
+ 'Select a service where you already have an account.' => 'Selecteer een service waar u reeds een account heeft.',
+ 'Add Profile (s)' => 'Profiel Toevoegen (s)', # Translate - New
+
+## plugins/ActionStreams/tmpl/list_profileevent.tmpl
+ 'The selected events were deleted.' => 'De geselecteerde gebeurtenissen werden verwijderd.',
+ 'The selected events were hidden.' => 'De geselecteerde gebeurtenissen werden verborgen.',
+ 'The selected events were shown.' => 'De geselecteerde gebeurtenissen werden weergegeven.',
+ 'All action stream events were hidden.' => 'Alle actions streams gebeurtenissen werden verborgen.',
+ 'All action stream events were shown.' => 'Alle action stream gebeurtenissen werden weergegeven.',
+ 'event' => 'gebeurtenis',
+ 'events' => 'gebeurtenissen',
+ 'Hide selected events (h)' => 'Geselecteerde gebeurtenissen verbergen (h)',
+ 'Hide' => 'Verbergen',
+ 'Show selected events (h)' => 'Geselecteerde gebeurtenissen tonen (h)',
+ 'Show' => 'Tonen',
+ 'All stream actions' => 'Alle gebeurtenissen van de stream',
+ 'Show only actions where' => 'Enkel gebeurtenissen tonen waar',
+ 'service' => 'service',
+ 'visibility' => 'zichtbaarheid',
+ 'hidden' => 'verborgen',
+ 'shown' => 'zichtbaar',
+ 'No events could be found.' => 'Er werden geen gebeurtenissen gevonden.',
+ 'Event' => 'Gebeurtenis',
+ 'Shown' => 'Zichtbaar',
+ 'Hidden' => 'Verborgen',
+ 'View action link' => 'Actielink bekijken',
+
+## plugins/ActionStreams/tmpl/widget_recent.mtml
+ 'Your Recent Actions' => 'Uw recente acties',
+ 'blog this' => 'blog dit',
+
+## plugins/ActionStreams/tmpl/blog_config_template.tmpl
+ 'Rebuild Indexes' => 'Indexen herpubliceren',
+ 'If selected, this blog\'s indexes will be rebuilt when new action stream events are discovered.' => 'Indien geselecteerd zullen de indexen van deze blog opnieuw worden gepubliceerd telkens nieuwe action stream gebeurtenissen worden ontdekt.',
+ 'Enable rebuilding' => 'Herpubliceren toestaan',
+);
+
+1;
|
markpasc/mt-plugin-action-streams
|
9ff7cfa4df5f76de23a23d11b22af14cd861c0f5
|
Oops, add back complicated but better code for now (misread the merge)
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
index c5d0a94..cfd3976 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
@@ -1,793 +1,792 @@
package ActionStreams::Plugin;
use strict;
use warnings;
use Carp qw( croak );
use MT::Util qw( relative_date offset_time epoch2ts ts2epoch format_ts );
sub users_content_nav {
my ($cb, $app, $param, $tmpl) = @_;
my $author_id = $app->param('id') or return;
my $author = MT->model('author')->load( $author_id )
or return $cb->error('failed to load author');
$param->{edit_author} = 1 if $author->type == MT::Author::AUTHOR();
my $menu_str = <<"EOF";
<__trans_section component="actionstreams"><mt:if var="USER_VIEW">
<li><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">"><b><__trans phrase="Other Profiles"></b></a></li>
<li><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">"><b><__trans phrase="Action Stream"></b></a></li>
<mt:else>
<li<mt:if name="other_profiles"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="id" escape="url">"><b><__trans phrase="Other Profiles"></b></a></li>
<li<mt:if name="list_profileevent"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="id" escape="url">"><b><__trans phrase="Action Stream"></b></a></li>
</mt:if></__trans_section>
EOF
require MT::Builder;
my $builder = MT::Builder->new;
my $ctx = $tmpl->context();
my $menu_tokens = $builder->compile( $ctx, $menu_str )
or return $cb->error($builder->errstr);
if ( $param->{line_items} ) {
push @{ $param->{line_items} }, bless $menu_tokens, 'MT::Template::Tokens';
}
else {
$ctx->{__stash}{vars}{line_items} = [ bless $menu_tokens, 'MT::Template::Tokens' ];
$param->{line_items} = [ bless $menu_tokens, 'MT::Template::Tokens' ];
}
if ( ( $app->mode eq 'other_profiles' ) || ( $app->mode eq 'list_profileevent' ) ) {
$param->{profile_inactive} = 1;
}
1;
}
sub param_list_member {
my ($cb, $app, $param, $tmpl) = @_;
my $loop = $param->{object_loop};
my @author_ids = map { $_->{id} } @$loop;
my $author_iter = MT->model('author')->load_iter({ id => \@author_ids });
my %profile_counts;
while ( my $author = $author_iter->() ) {
$profile_counts{$author->id} = scalar @{ $author->other_profiles };
}
for my $loop_item ( @$loop ) {
$loop_item->{profiles} = $profile_counts{ $loop_item->{id} };
}
my $header = <<'MTML';
<th><__trans_section component="actionstreams"><__trans phrase="Profiles"></__trans_section></th>
MTML
my $body = <<'MTML';
<mt:if name="has_edit_access">
<td><a href="<mt:var name="script_url">?__mode=other_profiles&id=<mt:var name="id">"><mt:var name="profiles"></a></td>
<mt:else>
<td><mt:var name="profiles"></td>
</mt:if>
MTML
require MT::Builder;
my $builder = MT::Builder->new;
my $ctx = $tmpl->context();
my $body_tokens = $builder->compile( $ctx, $body )
or return $cb->error($builder->errstr);
$param->{more_column_headers} ||= [];
$param->{more_columns} ||= [];
push @{ $param->{more_column_headers} }, $header;
push @{ $param->{more_columns} }, bless $body_tokens, 'MT::Template::Tokens';
1;
}
sub icon_url_for_service {
my $class = shift;
my ($type, $ndata) = @_;
my $plug = $ndata->{plugin} or return;
my $icon_url;
if ($ndata->{icon} && $ndata->{icon} =~ m{ \A \w:// }xms) {
$icon_url = $ndata->{icon};
}
elsif ($ndata->{icon}) {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
$ndata->{icon};
}
elsif ($plug->id eq 'actionstreams') {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
'images', 'services', $type . '.png';
}
return $icon_url;
}
+sub _edit_author {
+ my $arg = 'HASH' eq ref($_[0]) ? shift : { id => shift };
+
+ my $app = MT->instance;
+ my $trans_error = sub {
+ return $app->error($app->translate(@_)) unless $arg->{no_error};
+ };
+
+ $arg->{id} or return $trans_error->('No id');
+
+ my $class = MT->model('author');
+ my $author = $class->load( $arg->{id} )
+ or return $trans_error->("No such [_1].", lc( $class->class_label ));
+
+ return $trans_error->("Permission denied.")
+ if ! $app->user
+ or $app->user->id != $arg->{id} && !$app->user->is_superuser();
+
+ return $author;
+}
+
sub list_profileevent {
my $app = shift;
my %param = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
- my $author_id = $app->param('id')
- or return;
- return $app->error('Not permitted to view')
- if $app->user->id != $author_id && !$app->user->is_superuser();
+ my $author = _edit_author( $app->param('id') ) or return;
my %service_styles;
my @service_styles_loop;
my $code = sub {
my ($event, $row) = @_;
my @meta_col = keys %{ $event->properties->{meta_columns} || {} };
$row->{$_} = $event->{$_} for @meta_col;
$row->{as_html} = $event->as_html();
my ($service, $stream_id) = split /_/, $row->{class}, 2;
$row->{type} = $service;
my $nets = $app->registry('profile_services') || {};
my $net = $nets->{$service};
$row->{service} = $net->{name} if $net;
$row->{url} = $event->url;
if (!$service_styles{$service}) {
if (!$net->{plugin} || $net->{plugin}->id ne 'actionstreams') {
if (my $icon = __PACKAGE__->icon_url_for_service($service, $net)) {
push @service_styles_loop, {
service_type => $service,
service_icon => $icon,
};
}
}
$service_styles{$service} = 1;
}
my $ts = $row->{created_on};
$row->{created_on_relative} = relative_date($ts, time);
$row->{created_on_formatted} = format_ts(
MT::App::CMS->LISTING_DATETIME_FORMAT(),
epoch2ts(undef, offset_time(ts2epoch(undef, $ts))),
undef,
$app->user ? $app->user->preferred_language : undef,
);
};
# Make sure all classes are loaded.
require ActionStreams::Event;
for my $prevt (keys %{ $app->registry('action_streams') }) {
ActionStreams::Event->classes_for_type($prevt);
}
my $plugin = MT->component('ActionStreams');
my %params = map { $_ => $app->param($_) ? 1 : 0 }
qw( saved_deleted hidden shown );
$params{services} = [];
my $services = $app->registry('profile_services');
while (my ($prevt, $service) = each %$services) {
push @{ $params{services} }, {
service_id => $prevt,
service_name => $service->{name},
};
}
$params{services} = [ sort { lc $a->{service_name} cmp lc $b->{service_name} } @{ $params{services} } ];
my %terms = (
class => '*',
- author_id => $author_id,
+ author_id => $author->id,
);
my %args = (
sort => 'created_on',
direction => 'descend',
);
if (my $filter = $app->param('filter')) {
$params{filter_key} = $filter;
my $filter_val = $params{filter_val} = $app->param('filter_val');
if ($filter eq 'service') {
$params{filter_label} = $app->translate('Actions from the service [_1]', $app->registry('profile_services')->{$filter_val}->{name});
$terms{class} = $filter_val . '_%';
$args{like} = { class => 1 };
}
elsif ($filter eq 'visible') {
$params{filter_label} = ($filter_val eq 'show') ? $app->translate('Actions that are shown')
: $app->translate('Actions that are hidden');
$terms{visible} = $filter_val eq 'show' ? 1 : 0;
}
}
- $params{id} = $params{edit_author_id} = $author_id;
+ $params{id} = $params{edit_author_id} = $author->id;
+ $params{name} = $params{edit_author_name} = $author->name;
$params{service_styles} = \@service_styles_loop;
$app->listing({
type => 'profileevent',
terms => \%terms,
args => \%args,
listing_screen => 1,
code => $code,
template => $plugin->load_tmpl('list_profileevent.tmpl'),
params => \%params,
});
}
sub itemset_hide_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(0);
$event->save;
}
$app->add_return_arg( hidden => 1 );
$app->call_return;
}
sub itemset_show_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(1);
$event->save;
}
$app->add_return_arg( shown => 1 );
$app->call_return;
}
sub _itemset_hide_show_all_events {
my ($app, $new_visible) = @_;
$app->validate_magic or return;
my $event_class = MT->model('profileevent');
# Really we should work directly from the selected author ID, but as an
# itemset event we only got some event IDs. So use its.
my ($event_id) = $app->param('id');
my $event = $event_class->load($event_id)
or return $app->error($app->translate('No such event [_1]', $event_id));
- my $author_id = $event->author_id;
- return $app->error('Not permitted to modify')
- if $author_id != $app->user->id && !$app->user->is_superuser();
+ my $author = _edit_author( $event->author_id ) or return;
my $driver = $event_class->driver;
my $stmt = $driver->prepare_statement($event_class, {
# TODO: include filter value when we have filters
- author_id => $author_id,
+ author_id => $author->id,
visible => $new_visible ? 0 : 1,
});
my $sql = "UPDATE " . $driver->table_for($event_class) . " SET "
. $driver->dbd->db_column_name($event_class->datasource, 'visible')
. " = ? " . $stmt->as_sql_where;
# Work around error in MT::ObjectDriver::Driver::DBI::sql by doing it inline.
my $dbh = $driver->rw_handle;
$dbh->do($sql, {}, $new_visible, @{ $stmt->{bind} })
or return $app->error($dbh->errstr);
return 1;
}
sub itemset_hide_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 0) or return;
$app->add_return_arg( all_hidden => 1 );
$app->call_return;
}
sub itemset_show_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 1) or return;
$app->add_return_arg( all_shown => 1 );
$app->call_return;
}
sub _build_service_data {
my %info = @_;
my ($networks, $streams, $author) = @info{qw( networks streams author )};
my (@service_styles_loop, @networks);
my %has_profiles;
if ($author) {
my $other_profiles = $author->other_profiles();
$has_profiles{$_->{type}} = 1 for @$other_profiles;
}
my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
keys %$networks;
TYPE: for my $type (@network_keys) {
my $ndata = $networks->{$type}
or next TYPE;
next TYPE if !$info{include_deprecated} && $ndata->{deprecated};
my @streams;
if ($streams) {
my $streamdata = $streams->{$type} || {};
@streams =
sort { lc $a->{name} cmp lc $b->{name} }
grep { grep { $_ } @$_{qw( class scraper xpath rss atom )} }
map { +{ stream => $_, %{ $streamdata->{$_} } } }
grep { $_ ne 'plugin' }
keys %$streamdata;
}
## we must translate from original. or garbles on FastCGI environment.
if ( !exists $ndata->{__ident_hint_original} ) {
$ndata->{__ident_hint_original} = $ndata->{ident_hint};
}
$ndata->{ident_hint}
= MT->component('ActionStreams')->translate( $ndata->{__ident_hint_original} )
if $ndata->{__ident_hint_original};
my $ret = {
type => $type,
%$ndata,
label => $ndata->{name},
user_has_account => ($has_profiles{$type} ? 1 : 0),
};
if (@streams) {
for my $stream (@streams) {
## we must translate from original. or garbles on FastCGI environment.
if ( !exists $stream->{__name_original} ) {
$stream->{__name_original} = $stream->{name};
}
if ( !exists $stream->{__description_original} ) {
$stream->{__description_original} = $stream->{description};
}
$stream->{name}
= MT->component('ActionStreams')->translate( $stream->{__name_original} );
$stream->{description}
= MT->component('ActionStreams')->translate( $stream->{__description_original} );
}
$ret->{streams} = \@streams if @streams;
}
push @networks, $ret;
if (!$ndata->{plugin} || $ndata->{plugin}->id ne 'actionstreams') {
push @service_styles_loop, {
service_type => $type,
service_icon => __PACKAGE__->icon_url_for_service($type, $ndata),
};
}
}
return (
service_styles => \@service_styles_loop,
networks => \@networks,
);
}
sub other_profiles {
my( $app ) = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
- my $author_id = $app->param('id')
- or return $app->error('Author id is required');
- my $user = MT->model('author')->load($author_id)
- or return $app->error('Author id is invalid');
- return $app->error('Not permitted to view')
- if $app->user->id != $author_id && !$app->user->is_superuser();
+ my $author = _edit_author( $app->param('id') ) or return;
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl( 'other_profiles.tmpl' );
my @profiles = sort { lc $a->{label} cmp lc $b->{label} }
- @{ $user->other_profiles || [] };
+ @{ $author->other_profiles || [] };
+
+ my %params = map { $_ => $author->$_ } qw( id name );
+ $params{edit_author_id} = $params{id};
+ $params{edit_author_name} = $params{name};
my %messages = map { $_ => $app->param($_) ? 1 : 0 }
(qw( added removed updated edited ));
return $app->build_page( $tmpl, {
- id => $user->id,
- edit_author_id => $user->id,
+ %params,
profiles => \@profiles,
listing_screen => 1,
_build_service_data(
networks => $app->registry('profile_services'),
),
%messages,
} );
}
sub dialog_add_edit_profile {
my ($app) = @_;
- return $app->error('Not permitted to view')
- if $app->user->id != $app->param('author_id') && !$app->user->is_superuser();
- my $author = MT->model('author')->load($app->param('author_id'))
- or return $app->error('No such author [_1]', $app->param('author_id'));
+ my $author = _edit_author( $app->param('author_id') ) or return;
my %edit_profile;
my $tmpl_name = 'dialog_add_profile.tmpl';
if (my $edit_type = $app->param('profile_type')) {
my $ident = $app->param('profile_ident') || q{};
my ($profile) = grep { $_->{ident} eq $ident }
@{ $author->other_profiles($edit_type) };
%edit_profile = (
edit_type => $edit_type,
edit_type_name => $app->registry('profile_services', $edit_type, 'name'),
edit_ident => $ident,
edit_streams => $profile->{streams} || [],
);
$tmpl_name = 'dialog_edit_profile.tmpl';
}
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl($tmpl_name);
return $app->build_page($tmpl, {
- edit_author_id => $app->param('author_id'),
+ edit_author_id => $author->id,
_build_service_data(
networks => $app->registry('profile_services'),
streams => $app->registry('action_streams'),
author => $author,
),
%edit_profile,
});
}
sub edit_other_profile {
my $app = shift;
$app->validate_magic() or return;
- my $author_id = $app->param('author_id')
- or return $app->error('Author id is required');
- my $user = MT->model('author')->load($author_id)
- or return $app->error('Author id is invalid');
- return $app->error('Not permitted to edit')
- if $app->user->id != $author_id && !$app->user->is_superuser();
-
- my $type = $app->param('profile_type');
+ my $author = _edit_author( $app->param('author_id') ) or return;
+ my $type = $app->param('profile_type');
my $orig_ident = $app->param('original_ident');
- $user->remove_profile($type, $orig_ident);
+ $author->remove_profile($type, $orig_ident);
$app->forward('add_other_profile', success_msg => 'edited');
}
sub add_other_profile {
my $app = shift;
my %param = @_;
$app->validate_magic or return;
- my $author_id = $app->param('author_id')
- or return $app->error('Author id is required');
- my $user = MT->model('author')->load($author_id)
- or return $app->error('Author id is invalid');
- return $app->error('Not permitted to add')
- if $app->user->id != $author_id && !$app->user->is_superuser();
+ my $author = _edit_author( $app->param('author_id') ) or return;
my( $ident, $uri, $label, $type );
if ( $type = $app->param( 'profile_type' ) ) {
my $reg = $app->registry('profile_services');
my $network = $reg->{$type}
or croak "Unknown network $type";
$label = MT->component('ActionStreams')->translate( '[_1] Profile', $network->{name} );
$ident = $app->param( 'profile_id' );
$ident =~ s{ \A \s* }{}xms;
$ident =~ s{ \s* \z }{}xms;
# Check for full URLs.
if (!$network->{ident_exact}) {
my $url_pattern = $network->{url};
my ($pre_ident, $post_ident) = split /(?:\%s|\Q{{ident}}\E)/, $url_pattern, 2;
$pre_ident =~ s{ \A http:// }{}xms;
$post_ident =~ s{ / \z }{}xms;
if ($ident =~ m{ \A (?:http://)? \Q$pre_ident\E (.*?) \Q$post_ident\E /? \z }xms) {
$ident = $1;
}
}
$uri = $network->{url};
$uri =~ s{ (?:\%s|\Q{{ident}}\E) }{$ident}xmsg;
} else {
$ident = $uri = $app->param( 'profile_uri' );
$label = $app->param( 'profile_label' );
$type = 'website';
}
my $profile = {
type => $type,
ident => $ident,
label => $label,
uri => $uri,
};
my %streams = map { join(q{_}, $type, $_) => 1 }
grep { $_ ne 'plugin' && $app->param(join q{_}, 'stream', $type, $_) }
keys %{ $app->registry('action_streams', $type) || {} };
$profile->{streams} = \%streams if %streams;
- $app->run_callbacks('pre_add_profile.' . $type, $app, $user, $profile);
- $user->add_profile($profile);
- $app->run_callbacks('post_add_profile.' . $type, $app, $user, $profile);
+ $app->run_callbacks('pre_add_profile.' . $type, $app, $author, $profile);
+ $author->add_profile($profile);
+ $app->run_callbacks('post_add_profile.' . $type, $app, $author, $profile);
my $success_msg = $param{success_msg} || 'added';
return $app->redirect($app->uri(
mode => 'other_profiles',
- args => { id => $author_id, $success_msg => 1 },
+ args => { id => $author->id, $success_msg => 1 },
));
}
sub remove_other_profile {
my( $app ) = @_;
$app->validate_magic or return;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
- my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
- or next PROFILE;
- next PROFILE
- if $app->user->id != $author_id && !$app->user->is_superuser();
+ $users{$author_id} ||= _edit_author({ id => $author_id,
+ no_error => 1 });
+ my $author = $users{$author_id} or next PROFILE;
- $app->run_callbacks('pre_remove_profile.' . $type, $app, $user, $type, $ident);
- $user->remove_profile( $type, $ident );
- $app->run_callbacks('post_remove_profile.' . $type, $app, $user, $type, $ident);
+ $app->run_callbacks('pre_remove_profile.' . $type, $app, $author, $type, $ident);
+ $author->remove_profile( $type, $ident );
+ $app->run_callbacks('post_remove_profile.' . $type, $app, $author, $type, $ident);
$page_author_id = $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), removed => 1 },
));
}
sub profile_add_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
$app->param('author_id', $user->id);
my $type = $app->param('profile_type')
or return $app->error( $app->translate("Invalid request.") );
# The profile side interface doesn't have stream selection, so select
# them all by default.
# TODO: factor out the adding logic (and parameterize stream selection) to stop faking params
foreach my $stream ( keys %{ $app->registry('action_streams', $type) || {} } ) {
next if $stream eq 'plugin';
$app->param(join('_', 'stream', $type, $stream), 1);
}
add_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub profile_first_update_events {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub profile_delete_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
# TODO: factor out this logic instead of having to fake params
my $id = scalar $app->param('id');
$id = $user->id . ':' . $id;
$app->param('id', $id);
remove_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub itemset_update_profiles {
my $app = shift;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
- my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
- or next PROFILE;
- next PROFILE
- if $app->user->id != $author_id && !$app->user->is_superuser();
+ $users{$author_id} ||= _edit_author({ id => $author_id,
+ no_error => 1 });
+ my $author = $users{$author_id} or next PROFILE;
- my $profiles = $user->other_profiles($type);
+ my $profiles = $author->other_profiles($type);
if (!$profiles) {
next PROFILE;
}
my @profiles = grep { $_->{ident} eq $ident } @$profiles;
for my $author_profile (@profiles) {
- update_events_for_profile($user, $author_profile,
+ update_events_for_profile($author, $author_profile,
synchronous => 1);
}
$page_author_id ||= $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), updated => 1 },
));
}
sub first_profile_update {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub rebuild_action_stream_blogs {
my ($cb, $app) = @_;
my $plugin = MT->component('ActionStreams');
my $pd_iter = MT->model('plugindata')->load_iter({
plugin => $plugin->key,
key => { like => 'configuration:blog:%' }
});
my %rebuild;
while ( my $pd = $pd_iter->() ) {
next unless $pd->data('rebuild_for_action_stream_events');
my ($blog_id) = $pd->key =~ m/:blog:(\d+)$/;
$rebuild{$blog_id} = 1;
}
for my $blog_id (keys %rebuild) {
# TODO: limit this to indexes that publish action stream data, once
# we can magically infer template content before building it
my $blog = MT->model('blog')->load( $blog_id ) or next;
# Republish all the blog's known non-virtual index fileinfos that
# have real template objects.
my $finfo_class = MT->model('fileinfo');
my $finfo_template_col = $finfo_class->driver->dbd->db_column_name(
$finfo_class->datasource, 'template_id');
my @fileinfos = $finfo_class->load({
blog_id => $blog->id,
archive_type => 'index',
virtual => [ \'IS NULL', 0 ],
}, {
join => MT->model('template')->join_on(undef,
{ id => \"= $finfo_template_col" }),
});
require MT::TheSchwartz;
require TheSchwartz::Job;
FINFO: for my $fi (@fileinfos) {
# Only publish if the matching template has an output file.
my $tmpl = MT->model('template')->load($fi->template_id)
or next FINFO;
next FINFO if !$tmpl->outfile;
my $job = TheSchwartz::Job->new();
$job->funcname('MT::Worker::Publish');
$job->uniqkey($fi->id);
$job->run_after(time + 240); # 4 minutes
MT::TheSchwartz->insert($job);
}
}
}
sub widget_recent {
my ($app, $tmpl, $widget_param) = @_;
$tmpl->param('author_id', $app->user->id);
$tmpl->param('blog_id', $app->blog->id) if $app->blog;
}
sub widget_blog_dashboard_only {
my ($page, $scope) = @_;
return if $scope eq 'dashboard:system';
return 1;
}
sub update_events {
my $mt = MT->app;
$mt->run_callbacks('pre_action_streams_task', $mt);
my $au_class = MT->model('author');
my $author_iter = $au_class->search({
status => $au_class->ACTIVE(),
}, {
join => [ $au_class->meta_pkg, 'author_id', { type => 'other_profiles' } ],
});
while (my $author = $author_iter->()) {
my $profiles = $author->other_profiles();
$mt->run_callbacks('pre_update_action_streams', $mt, $author, $profiles);
PROFILE: for my $profile (@$profiles) {
update_events_for_profile($author, $profile);
}
$mt->run_callbacks('post_update_action_streams', $mt, $author, $profiles);
}
$mt->run_callbacks('post_action_streams_task', $mt);
}
sub update_events_for_profile {
my ($author, $profile, %param) = @_;
my $type = $profile->{type};
my $streams = $profile->{streams};
return if !$streams || !%$streams;
my $services = MT->registry('profile_services');
return if !exists $services->{$type} || $services->{$type}->{deprecated};
require ActionStreams::Event;
my @event_classes = ActionStreams::Event->classes_for_type($type)
or return;
my $mt = MT->app;
$mt->run_callbacks('pre_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
EVENTCLASS: for my $event_class (@event_classes) {
next EVENTCLASS if !$streams->{$event_class->class_type};
if ($param{synchronous}) {
$event_class->update_events_loggily(
author => $author,
hide_timeless => $param{hide_timeless} ? 1 : 0,
%$profile,
);
}
else {
# Defer regular updates to job workers.
require ActionStreams::Worker;
ActionStreams::Worker->make_work(
event_class => $event_class,
author => $author,
%$profile,
);
}
}
$mt->run_callbacks('post_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
}
1;
|
markpasc/mt-plugin-action-streams
|
389d38ae34112c8b8a9254dfa831dfead98fe52b
|
Apply simplified author permission checking from Motion AS (compare revision 1536)
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
index cfd3976..c5d0a94 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
@@ -1,792 +1,793 @@
package ActionStreams::Plugin;
use strict;
use warnings;
use Carp qw( croak );
use MT::Util qw( relative_date offset_time epoch2ts ts2epoch format_ts );
sub users_content_nav {
my ($cb, $app, $param, $tmpl) = @_;
my $author_id = $app->param('id') or return;
my $author = MT->model('author')->load( $author_id )
or return $cb->error('failed to load author');
$param->{edit_author} = 1 if $author->type == MT::Author::AUTHOR();
my $menu_str = <<"EOF";
<__trans_section component="actionstreams"><mt:if var="USER_VIEW">
<li><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">"><b><__trans phrase="Other Profiles"></b></a></li>
<li><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">"><b><__trans phrase="Action Stream"></b></a></li>
<mt:else>
<li<mt:if name="other_profiles"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="id" escape="url">"><b><__trans phrase="Other Profiles"></b></a></li>
<li<mt:if name="list_profileevent"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="id" escape="url">"><b><__trans phrase="Action Stream"></b></a></li>
</mt:if></__trans_section>
EOF
require MT::Builder;
my $builder = MT::Builder->new;
my $ctx = $tmpl->context();
my $menu_tokens = $builder->compile( $ctx, $menu_str )
or return $cb->error($builder->errstr);
if ( $param->{line_items} ) {
push @{ $param->{line_items} }, bless $menu_tokens, 'MT::Template::Tokens';
}
else {
$ctx->{__stash}{vars}{line_items} = [ bless $menu_tokens, 'MT::Template::Tokens' ];
$param->{line_items} = [ bless $menu_tokens, 'MT::Template::Tokens' ];
}
if ( ( $app->mode eq 'other_profiles' ) || ( $app->mode eq 'list_profileevent' ) ) {
$param->{profile_inactive} = 1;
}
1;
}
sub param_list_member {
my ($cb, $app, $param, $tmpl) = @_;
my $loop = $param->{object_loop};
my @author_ids = map { $_->{id} } @$loop;
my $author_iter = MT->model('author')->load_iter({ id => \@author_ids });
my %profile_counts;
while ( my $author = $author_iter->() ) {
$profile_counts{$author->id} = scalar @{ $author->other_profiles };
}
for my $loop_item ( @$loop ) {
$loop_item->{profiles} = $profile_counts{ $loop_item->{id} };
}
my $header = <<'MTML';
<th><__trans_section component="actionstreams"><__trans phrase="Profiles"></__trans_section></th>
MTML
my $body = <<'MTML';
<mt:if name="has_edit_access">
<td><a href="<mt:var name="script_url">?__mode=other_profiles&id=<mt:var name="id">"><mt:var name="profiles"></a></td>
<mt:else>
<td><mt:var name="profiles"></td>
</mt:if>
MTML
require MT::Builder;
my $builder = MT::Builder->new;
my $ctx = $tmpl->context();
my $body_tokens = $builder->compile( $ctx, $body )
or return $cb->error($builder->errstr);
$param->{more_column_headers} ||= [];
$param->{more_columns} ||= [];
push @{ $param->{more_column_headers} }, $header;
push @{ $param->{more_columns} }, bless $body_tokens, 'MT::Template::Tokens';
1;
}
sub icon_url_for_service {
my $class = shift;
my ($type, $ndata) = @_;
my $plug = $ndata->{plugin} or return;
my $icon_url;
if ($ndata->{icon} && $ndata->{icon} =~ m{ \A \w:// }xms) {
$icon_url = $ndata->{icon};
}
elsif ($ndata->{icon}) {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
$ndata->{icon};
}
elsif ($plug->id eq 'actionstreams') {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
'images', 'services', $type . '.png';
}
return $icon_url;
}
-sub _edit_author {
- my $arg = 'HASH' eq ref($_[0]) ? shift : { id => shift };
-
- my $app = MT->instance;
- my $trans_error = sub {
- return $app->error($app->translate(@_)) unless $arg->{no_error};
- };
-
- $arg->{id} or return $trans_error->('No id');
-
- my $class = MT->model('author');
- my $author = $class->load( $arg->{id} )
- or return $trans_error->("No such [_1].", lc( $class->class_label ));
-
- return $trans_error->("Permission denied.")
- if ! $app->user
- or $app->user->id != $arg->{id} && !$app->user->is_superuser();
-
- return $author;
-}
-
sub list_profileevent {
my $app = shift;
my %param = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
- my $author = _edit_author( $app->param('id') ) or return;
+ my $author_id = $app->param('id')
+ or return;
+ return $app->error('Not permitted to view')
+ if $app->user->id != $author_id && !$app->user->is_superuser();
my %service_styles;
my @service_styles_loop;
my $code = sub {
my ($event, $row) = @_;
my @meta_col = keys %{ $event->properties->{meta_columns} || {} };
$row->{$_} = $event->{$_} for @meta_col;
$row->{as_html} = $event->as_html();
my ($service, $stream_id) = split /_/, $row->{class}, 2;
$row->{type} = $service;
my $nets = $app->registry('profile_services') || {};
my $net = $nets->{$service};
$row->{service} = $net->{name} if $net;
$row->{url} = $event->url;
if (!$service_styles{$service}) {
if (!$net->{plugin} || $net->{plugin}->id ne 'actionstreams') {
if (my $icon = __PACKAGE__->icon_url_for_service($service, $net)) {
push @service_styles_loop, {
service_type => $service,
service_icon => $icon,
};
}
}
$service_styles{$service} = 1;
}
my $ts = $row->{created_on};
$row->{created_on_relative} = relative_date($ts, time);
$row->{created_on_formatted} = format_ts(
MT::App::CMS->LISTING_DATETIME_FORMAT(),
epoch2ts(undef, offset_time(ts2epoch(undef, $ts))),
undef,
$app->user ? $app->user->preferred_language : undef,
);
};
# Make sure all classes are loaded.
require ActionStreams::Event;
for my $prevt (keys %{ $app->registry('action_streams') }) {
ActionStreams::Event->classes_for_type($prevt);
}
my $plugin = MT->component('ActionStreams');
my %params = map { $_ => $app->param($_) ? 1 : 0 }
qw( saved_deleted hidden shown );
$params{services} = [];
my $services = $app->registry('profile_services');
while (my ($prevt, $service) = each %$services) {
push @{ $params{services} }, {
service_id => $prevt,
service_name => $service->{name},
};
}
$params{services} = [ sort { lc $a->{service_name} cmp lc $b->{service_name} } @{ $params{services} } ];
my %terms = (
class => '*',
- author_id => $author->id,
+ author_id => $author_id,
);
my %args = (
sort => 'created_on',
direction => 'descend',
);
if (my $filter = $app->param('filter')) {
$params{filter_key} = $filter;
my $filter_val = $params{filter_val} = $app->param('filter_val');
if ($filter eq 'service') {
$params{filter_label} = $app->translate('Actions from the service [_1]', $app->registry('profile_services')->{$filter_val}->{name});
$terms{class} = $filter_val . '_%';
$args{like} = { class => 1 };
}
elsif ($filter eq 'visible') {
$params{filter_label} = ($filter_val eq 'show') ? $app->translate('Actions that are shown')
: $app->translate('Actions that are hidden');
$terms{visible} = $filter_val eq 'show' ? 1 : 0;
}
}
- $params{id} = $params{edit_author_id} = $author->id;
- $params{name} = $params{edit_author_name} = $author->name;
+ $params{id} = $params{edit_author_id} = $author_id;
$params{service_styles} = \@service_styles_loop;
$app->listing({
type => 'profileevent',
terms => \%terms,
args => \%args,
listing_screen => 1,
code => $code,
template => $plugin->load_tmpl('list_profileevent.tmpl'),
params => \%params,
});
}
sub itemset_hide_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(0);
$event->save;
}
$app->add_return_arg( hidden => 1 );
$app->call_return;
}
sub itemset_show_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(1);
$event->save;
}
$app->add_return_arg( shown => 1 );
$app->call_return;
}
sub _itemset_hide_show_all_events {
my ($app, $new_visible) = @_;
$app->validate_magic or return;
my $event_class = MT->model('profileevent');
# Really we should work directly from the selected author ID, but as an
# itemset event we only got some event IDs. So use its.
my ($event_id) = $app->param('id');
my $event = $event_class->load($event_id)
or return $app->error($app->translate('No such event [_1]', $event_id));
- my $author = _edit_author( $event->author_id ) or return;
+ my $author_id = $event->author_id;
+ return $app->error('Not permitted to modify')
+ if $author_id != $app->user->id && !$app->user->is_superuser();
my $driver = $event_class->driver;
my $stmt = $driver->prepare_statement($event_class, {
# TODO: include filter value when we have filters
- author_id => $author->id,
+ author_id => $author_id,
visible => $new_visible ? 0 : 1,
});
my $sql = "UPDATE " . $driver->table_for($event_class) . " SET "
. $driver->dbd->db_column_name($event_class->datasource, 'visible')
. " = ? " . $stmt->as_sql_where;
# Work around error in MT::ObjectDriver::Driver::DBI::sql by doing it inline.
my $dbh = $driver->rw_handle;
$dbh->do($sql, {}, $new_visible, @{ $stmt->{bind} })
or return $app->error($dbh->errstr);
return 1;
}
sub itemset_hide_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 0) or return;
$app->add_return_arg( all_hidden => 1 );
$app->call_return;
}
sub itemset_show_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 1) or return;
$app->add_return_arg( all_shown => 1 );
$app->call_return;
}
sub _build_service_data {
my %info = @_;
my ($networks, $streams, $author) = @info{qw( networks streams author )};
my (@service_styles_loop, @networks);
my %has_profiles;
if ($author) {
my $other_profiles = $author->other_profiles();
$has_profiles{$_->{type}} = 1 for @$other_profiles;
}
my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
keys %$networks;
TYPE: for my $type (@network_keys) {
my $ndata = $networks->{$type}
or next TYPE;
next TYPE if !$info{include_deprecated} && $ndata->{deprecated};
my @streams;
if ($streams) {
my $streamdata = $streams->{$type} || {};
@streams =
sort { lc $a->{name} cmp lc $b->{name} }
grep { grep { $_ } @$_{qw( class scraper xpath rss atom )} }
map { +{ stream => $_, %{ $streamdata->{$_} } } }
grep { $_ ne 'plugin' }
keys %$streamdata;
}
## we must translate from original. or garbles on FastCGI environment.
if ( !exists $ndata->{__ident_hint_original} ) {
$ndata->{__ident_hint_original} = $ndata->{ident_hint};
}
$ndata->{ident_hint}
= MT->component('ActionStreams')->translate( $ndata->{__ident_hint_original} )
if $ndata->{__ident_hint_original};
my $ret = {
type => $type,
%$ndata,
label => $ndata->{name},
user_has_account => ($has_profiles{$type} ? 1 : 0),
};
if (@streams) {
for my $stream (@streams) {
## we must translate from original. or garbles on FastCGI environment.
if ( !exists $stream->{__name_original} ) {
$stream->{__name_original} = $stream->{name};
}
if ( !exists $stream->{__description_original} ) {
$stream->{__description_original} = $stream->{description};
}
$stream->{name}
= MT->component('ActionStreams')->translate( $stream->{__name_original} );
$stream->{description}
= MT->component('ActionStreams')->translate( $stream->{__description_original} );
}
$ret->{streams} = \@streams if @streams;
}
push @networks, $ret;
if (!$ndata->{plugin} || $ndata->{plugin}->id ne 'actionstreams') {
push @service_styles_loop, {
service_type => $type,
service_icon => __PACKAGE__->icon_url_for_service($type, $ndata),
};
}
}
return (
service_styles => \@service_styles_loop,
networks => \@networks,
);
}
sub other_profiles {
my( $app ) = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
- my $author = _edit_author( $app->param('id') ) or return;
+ my $author_id = $app->param('id')
+ or return $app->error('Author id is required');
+ my $user = MT->model('author')->load($author_id)
+ or return $app->error('Author id is invalid');
+ return $app->error('Not permitted to view')
+ if $app->user->id != $author_id && !$app->user->is_superuser();
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl( 'other_profiles.tmpl' );
my @profiles = sort { lc $a->{label} cmp lc $b->{label} }
- @{ $author->other_profiles || [] };
-
- my %params = map { $_ => $author->$_ } qw( id name );
- $params{edit_author_id} = $params{id};
- $params{edit_author_name} = $params{name};
+ @{ $user->other_profiles || [] };
my %messages = map { $_ => $app->param($_) ? 1 : 0 }
(qw( added removed updated edited ));
return $app->build_page( $tmpl, {
- %params,
+ id => $user->id,
+ edit_author_id => $user->id,
profiles => \@profiles,
listing_screen => 1,
_build_service_data(
networks => $app->registry('profile_services'),
),
%messages,
} );
}
sub dialog_add_edit_profile {
my ($app) = @_;
- my $author = _edit_author( $app->param('author_id') ) or return;
+ return $app->error('Not permitted to view')
+ if $app->user->id != $app->param('author_id') && !$app->user->is_superuser();
+ my $author = MT->model('author')->load($app->param('author_id'))
+ or return $app->error('No such author [_1]', $app->param('author_id'));
my %edit_profile;
my $tmpl_name = 'dialog_add_profile.tmpl';
if (my $edit_type = $app->param('profile_type')) {
my $ident = $app->param('profile_ident') || q{};
my ($profile) = grep { $_->{ident} eq $ident }
@{ $author->other_profiles($edit_type) };
%edit_profile = (
edit_type => $edit_type,
edit_type_name => $app->registry('profile_services', $edit_type, 'name'),
edit_ident => $ident,
edit_streams => $profile->{streams} || [],
);
$tmpl_name = 'dialog_edit_profile.tmpl';
}
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl($tmpl_name);
return $app->build_page($tmpl, {
- edit_author_id => $author->id,
+ edit_author_id => $app->param('author_id'),
_build_service_data(
networks => $app->registry('profile_services'),
streams => $app->registry('action_streams'),
author => $author,
),
%edit_profile,
});
}
sub edit_other_profile {
my $app = shift;
$app->validate_magic() or return;
- my $author = _edit_author( $app->param('author_id') ) or return;
- my $type = $app->param('profile_type');
+ my $author_id = $app->param('author_id')
+ or return $app->error('Author id is required');
+ my $user = MT->model('author')->load($author_id)
+ or return $app->error('Author id is invalid');
+ return $app->error('Not permitted to edit')
+ if $app->user->id != $author_id && !$app->user->is_superuser();
+
+ my $type = $app->param('profile_type');
my $orig_ident = $app->param('original_ident');
- $author->remove_profile($type, $orig_ident);
+ $user->remove_profile($type, $orig_ident);
$app->forward('add_other_profile', success_msg => 'edited');
}
sub add_other_profile {
my $app = shift;
my %param = @_;
$app->validate_magic or return;
- my $author = _edit_author( $app->param('author_id') ) or return;
+ my $author_id = $app->param('author_id')
+ or return $app->error('Author id is required');
+ my $user = MT->model('author')->load($author_id)
+ or return $app->error('Author id is invalid');
+ return $app->error('Not permitted to add')
+ if $app->user->id != $author_id && !$app->user->is_superuser();
my( $ident, $uri, $label, $type );
if ( $type = $app->param( 'profile_type' ) ) {
my $reg = $app->registry('profile_services');
my $network = $reg->{$type}
or croak "Unknown network $type";
$label = MT->component('ActionStreams')->translate( '[_1] Profile', $network->{name} );
$ident = $app->param( 'profile_id' );
$ident =~ s{ \A \s* }{}xms;
$ident =~ s{ \s* \z }{}xms;
# Check for full URLs.
if (!$network->{ident_exact}) {
my $url_pattern = $network->{url};
my ($pre_ident, $post_ident) = split /(?:\%s|\Q{{ident}}\E)/, $url_pattern, 2;
$pre_ident =~ s{ \A http:// }{}xms;
$post_ident =~ s{ / \z }{}xms;
if ($ident =~ m{ \A (?:http://)? \Q$pre_ident\E (.*?) \Q$post_ident\E /? \z }xms) {
$ident = $1;
}
}
$uri = $network->{url};
$uri =~ s{ (?:\%s|\Q{{ident}}\E) }{$ident}xmsg;
} else {
$ident = $uri = $app->param( 'profile_uri' );
$label = $app->param( 'profile_label' );
$type = 'website';
}
my $profile = {
type => $type,
ident => $ident,
label => $label,
uri => $uri,
};
my %streams = map { join(q{_}, $type, $_) => 1 }
grep { $_ ne 'plugin' && $app->param(join q{_}, 'stream', $type, $_) }
keys %{ $app->registry('action_streams', $type) || {} };
$profile->{streams} = \%streams if %streams;
- $app->run_callbacks('pre_add_profile.' . $type, $app, $author, $profile);
- $author->add_profile($profile);
- $app->run_callbacks('post_add_profile.' . $type, $app, $author, $profile);
+ $app->run_callbacks('pre_add_profile.' . $type, $app, $user, $profile);
+ $user->add_profile($profile);
+ $app->run_callbacks('post_add_profile.' . $type, $app, $user, $profile);
my $success_msg = $param{success_msg} || 'added';
return $app->redirect($app->uri(
mode => 'other_profiles',
- args => { id => $author->id, $success_msg => 1 },
+ args => { id => $author_id, $success_msg => 1 },
));
}
sub remove_other_profile {
my( $app ) = @_;
$app->validate_magic or return;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
- $users{$author_id} ||= _edit_author({ id => $author_id,
- no_error => 1 });
- my $author = $users{$author_id} or next PROFILE;
+ my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
+ or next PROFILE;
+ next PROFILE
+ if $app->user->id != $author_id && !$app->user->is_superuser();
- $app->run_callbacks('pre_remove_profile.' . $type, $app, $author, $type, $ident);
- $author->remove_profile( $type, $ident );
- $app->run_callbacks('post_remove_profile.' . $type, $app, $author, $type, $ident);
+ $app->run_callbacks('pre_remove_profile.' . $type, $app, $user, $type, $ident);
+ $user->remove_profile( $type, $ident );
+ $app->run_callbacks('post_remove_profile.' . $type, $app, $user, $type, $ident);
$page_author_id = $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), removed => 1 },
));
}
sub profile_add_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
$app->param('author_id', $user->id);
my $type = $app->param('profile_type')
or return $app->error( $app->translate("Invalid request.") );
# The profile side interface doesn't have stream selection, so select
# them all by default.
# TODO: factor out the adding logic (and parameterize stream selection) to stop faking params
foreach my $stream ( keys %{ $app->registry('action_streams', $type) || {} } ) {
next if $stream eq 'plugin';
$app->param(join('_', 'stream', $type, $stream), 1);
}
add_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub profile_first_update_events {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub profile_delete_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
# TODO: factor out this logic instead of having to fake params
my $id = scalar $app->param('id');
$id = $user->id . ':' . $id;
$app->param('id', $id);
remove_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub itemset_update_profiles {
my $app = shift;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
- $users{$author_id} ||= _edit_author({ id => $author_id,
- no_error => 1 });
- my $author = $users{$author_id} or next PROFILE;
+ my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
+ or next PROFILE;
+ next PROFILE
+ if $app->user->id != $author_id && !$app->user->is_superuser();
- my $profiles = $author->other_profiles($type);
+ my $profiles = $user->other_profiles($type);
if (!$profiles) {
next PROFILE;
}
my @profiles = grep { $_->{ident} eq $ident } @$profiles;
for my $author_profile (@profiles) {
- update_events_for_profile($author, $author_profile,
+ update_events_for_profile($user, $author_profile,
synchronous => 1);
}
$page_author_id ||= $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), updated => 1 },
));
}
sub first_profile_update {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub rebuild_action_stream_blogs {
my ($cb, $app) = @_;
my $plugin = MT->component('ActionStreams');
my $pd_iter = MT->model('plugindata')->load_iter({
plugin => $plugin->key,
key => { like => 'configuration:blog:%' }
});
my %rebuild;
while ( my $pd = $pd_iter->() ) {
next unless $pd->data('rebuild_for_action_stream_events');
my ($blog_id) = $pd->key =~ m/:blog:(\d+)$/;
$rebuild{$blog_id} = 1;
}
for my $blog_id (keys %rebuild) {
# TODO: limit this to indexes that publish action stream data, once
# we can magically infer template content before building it
my $blog = MT->model('blog')->load( $blog_id ) or next;
# Republish all the blog's known non-virtual index fileinfos that
# have real template objects.
my $finfo_class = MT->model('fileinfo');
my $finfo_template_col = $finfo_class->driver->dbd->db_column_name(
$finfo_class->datasource, 'template_id');
my @fileinfos = $finfo_class->load({
blog_id => $blog->id,
archive_type => 'index',
virtual => [ \'IS NULL', 0 ],
}, {
join => MT->model('template')->join_on(undef,
{ id => \"= $finfo_template_col" }),
});
require MT::TheSchwartz;
require TheSchwartz::Job;
FINFO: for my $fi (@fileinfos) {
# Only publish if the matching template has an output file.
my $tmpl = MT->model('template')->load($fi->template_id)
or next FINFO;
next FINFO if !$tmpl->outfile;
my $job = TheSchwartz::Job->new();
$job->funcname('MT::Worker::Publish');
$job->uniqkey($fi->id);
$job->run_after(time + 240); # 4 minutes
MT::TheSchwartz->insert($job);
}
}
}
sub widget_recent {
my ($app, $tmpl, $widget_param) = @_;
$tmpl->param('author_id', $app->user->id);
$tmpl->param('blog_id', $app->blog->id) if $app->blog;
}
sub widget_blog_dashboard_only {
my ($page, $scope) = @_;
return if $scope eq 'dashboard:system';
return 1;
}
sub update_events {
my $mt = MT->app;
$mt->run_callbacks('pre_action_streams_task', $mt);
my $au_class = MT->model('author');
my $author_iter = $au_class->search({
status => $au_class->ACTIVE(),
}, {
join => [ $au_class->meta_pkg, 'author_id', { type => 'other_profiles' } ],
});
while (my $author = $author_iter->()) {
my $profiles = $author->other_profiles();
$mt->run_callbacks('pre_update_action_streams', $mt, $author, $profiles);
PROFILE: for my $profile (@$profiles) {
update_events_for_profile($author, $profile);
}
$mt->run_callbacks('post_update_action_streams', $mt, $author, $profiles);
}
$mt->run_callbacks('post_action_streams_task', $mt);
}
sub update_events_for_profile {
my ($author, $profile, %param) = @_;
my $type = $profile->{type};
my $streams = $profile->{streams};
return if !$streams || !%$streams;
my $services = MT->registry('profile_services');
return if !exists $services->{$type} || $services->{$type}->{deprecated};
require ActionStreams::Event;
my @event_classes = ActionStreams::Event->classes_for_type($type)
or return;
my $mt = MT->app;
$mt->run_callbacks('pre_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
EVENTCLASS: for my $event_class (@event_classes) {
next EVENTCLASS if !$streams->{$event_class->class_type};
if ($param{synchronous}) {
$event_class->update_events_loggily(
author => $author,
hide_timeless => $param{hide_timeless} ? 1 : 0,
%$profile,
);
}
else {
# Defer regular updates to job workers.
require ActionStreams::Worker;
ActionStreams::Worker->make_work(
event_class => $event_class,
author => $author,
%$profile,
);
}
}
$mt->run_callbacks('post_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
}
1;
|
markpasc/mt-plugin-action-streams
|
49230c0c213096eb61bbad6f0fd42d63367cffbe
|
Finish merging template set from Motion version of AS (seems to have been partially merged; compare revision 1536)
|
diff --git a/plugins/ActionStreams/blog_tmpl/banner_footer.mtml b/plugins/ActionStreams/blog_tmpl/banner_footer.mtml
new file mode 100644
index 0000000..1b98c6b
--- /dev/null
+++ b/plugins/ActionStreams/blog_tmpl/banner_footer.mtml
@@ -0,0 +1,18 @@
+<div id="footer">
+ <div id="footer-inner">
+ <div id="footer-content">
+ <div class="widget-powered widget">
+ <div class="widget-content">
+ <__trans phrase="_POWERED_BY">
+ </div>
+ </div>
+<mt:BlogIfCCLicense>
+ <div class="widget-creative-commons widget">
+ <div class="widget-content">
+ <__trans phrase="This blog is licensed under a <a href="[_1]">Creative Commons License</a>." params="<$mt:BlogCCLicenseURL$>">
+ </div>
+ </div>
+</mt:BlogIfCCLicense>
+ </div>
+ </div>
+</div>
diff --git a/plugins/ActionStreams/blog_tmpl/banner_header.mtml b/plugins/ActionStreams/blog_tmpl/banner_header.mtml
new file mode 100644
index 0000000..80bca5e
--- /dev/null
+++ b/plugins/ActionStreams/blog_tmpl/banner_header.mtml
@@ -0,0 +1,14 @@
+<div id="header">
+ <div id="header-inner">
+ <div id="header-content">
+<mt:Ignore><!-- Use h1 and h2 html tags on the main index of the blog as the title, use divs on all other pages where there are page titles. --></mt:Ignore>
+<mt:If name="main_index">
+ <h1 id="header-name"><a href="<$mt:BlogURL$>" accesskey="1"><$mt:BlogName encode_html="1"$></a></h1>
+ <h2 id="header-description"><$mt:BlogDescription$></h2>
+<mt:Else>
+ <div id="header-name"><a href="<$mt:BlogURL$>" accesskey="1"><$mt:BlogName encode_html="1"$></a></div>
+ <div id="header-description"><$mt:BlogDescription$></div>
+</mt:If>
+ </div>
+ </div>
+</div>
diff --git a/plugins/ActionStreams/blog_tmpl/atom.mtml b/plugins/ActionStreams/blog_tmpl/feed_recent.mtml
similarity index 100%
rename from plugins/ActionStreams/blog_tmpl/atom.mtml
rename to plugins/ActionStreams/blog_tmpl/feed_recent.mtml
diff --git a/plugins/ActionStreams/blog_tmpl/footer.mtml b/plugins/ActionStreams/blog_tmpl/footer.mtml
deleted file mode 100644
index b64177f..0000000
--- a/plugins/ActionStreams/blog_tmpl/footer.mtml
+++ /dev/null
@@ -1,29 +0,0 @@
- </div>
- </div>
-<MTIf name="sidebar">
- <$MTInclude module="<__trans phrase="Sidebar">"$>
-</MTIf>
- </div>
- </div>
- <div id="footer">
- <div id="footer-inner">
- <div id="footer-content">
- <div class="widget-powered widget">
- <div class="widget-content">
- <__trans phrase="_POWERED_BY">
- </div>
- </div>
-<MTBlogIfCCLicense>
- <div class="widget-creative-commons widget">
- <div class="widget-content">
- <__trans phrase="This blog is licensed under a <a href="[_1]">Creative Commons License</a>." params="<$MTBlogCCLicenseURL$>">
- </div>
- </div>
-</MTBlogIfCCLicense>
- </div>
- </div>
- </div>
- </div>
- </div>
-</body>
-</html>
diff --git a/plugins/ActionStreams/blog_tmpl/header.mtml b/plugins/ActionStreams/blog_tmpl/header.mtml
deleted file mode 100755
index 9769fc8..0000000
--- a/plugins/ActionStreams/blog_tmpl/header.mtml
+++ /dev/null
@@ -1,39 +0,0 @@
-<mt:setvarblock name="html_head" prepend="1">
- <MTIf name="main_template">
-<link rel="alternate" type="application/atom+xml" title="Atom" href="<$MTLink template="atom"$>" />
- <MTUnless name="main_index">
-<link rel="start" href="<$MTBlogURL$>" title="Home" />
- </MTUnless>
-<$MTCCLicenseRDF$>
- </MTIf>
-</mt:setvarblock>
-<!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" id="sixapart-standard">
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=<$MTPublishCharset$>" />
- <title><$mt:var name="title"$></title>
- <meta name="generator" content="<$MTProductName version="1"$>" />
- <link rel="stylesheet" href="<$MTLink template="styles"$>" type="text/css" />
- <$mt:var name="html_head"$>
-</head>
-<body class="<MTIf name="body_class"><$MTGetVar name="body_class"$> </MTIf>layout-wt"<MTIf name="body_onload"> onload="<$MTGetVar name="body_onload"$>"</MTIf>>
- <div id="container">
- <div id="container-inner">
- <div id="header">
- <div id="header-inner">
- <div id="header-content">
-<MTIf name="main_index">
- <h1 id="header-name"><a href="<$MTBlogURL$>" accesskey="1"><$MTBlogName encode_html="1"$></a></h1>
- <h2 id="header-description"><$MTBlogDescription$></h2>
-<MTElse>
- <div id="header-name"><a href="<$MTBlogURL$>" accesskey="1"><$MTBlogName encode_html="1"$></a></div>
- <div id="header-description"><$MTBlogDescription$></div>
-</MTIf>
- </div>
- </div>
- </div>
- <div id="content">
- <div id="content-inner">
- <div id="alpha">
- <div id="alpha-inner">
diff --git a/plugins/ActionStreams/blog_tmpl/html_head.mtml b/plugins/ActionStreams/blog_tmpl/html_head.mtml
new file mode 100644
index 0000000..e3af94e
--- /dev/null
+++ b/plugins/ActionStreams/blog_tmpl/html_head.mtml
@@ -0,0 +1,6 @@
+<meta http-equiv="Content-Type" content="text/html; charset=<$mt:PublishCharset$>" />
+<meta name="generator" content="<$mt:ProductName version="1"$>" />
+<link rel="stylesheet" href="<$mt:Link template="styles"$>" type="text/css" />
+<link rel="start" href="<$mt:BlogURL$>" title="Home" />
+<link rel="alternate" type="application/atom+xml" title="Recent Entries" href="<$mt:Link template="feed_recent"$>" />
+<$mt:CCLicenseRDF$>
|
markpasc/mt-plugin-action-streams
|
889e753a92e83a9294b0d86725dea30108bbfe2a
|
Don't try to double-shift self off the parameters
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/UserAgent/Adapter.pm b/plugins/ActionStreams/lib/ActionStreams/UserAgent/Adapter.pm
index 66876b0..73fd1c4 100644
--- a/plugins/ActionStreams/lib/ActionStreams/UserAgent/Adapter.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/UserAgent/Adapter.pm
@@ -1,116 +1,116 @@
package ActionStreams::UserAgent::NotModified;
use overload q{""} => \&as_string;
sub new {
my ($class, $string) = @_;
return bless \$string, $class;
}
sub as_string {
my $self = shift;
return $$self;
}
package ActionStreams::UserAgent::Adapter;
sub new {
my $class = shift;
my %param = @_;
return bless \%param, $class;
}
sub _add_cache_headers {
my $self = shift;
my %param = @_;
my ($uri, $headers) = @param{qw( uri headers )};
my $action_type = $self->{action_type}
or return;
my $cache = MT->model('as_ua_cache')->load({
url => $uri,
action_type => $action_type,
});
return if !$cache;
if (my $etag = $cache->etag) {
$headers->{If_None_Match} = $etag;
}
if (my $last_mod = $cache->last_modified) {
$headers->{If_Last_Modified} = $last_mod;
}
}
sub _save_cache_headers {
my $self = shift;
my ($resp) = @_;
# Don't do anything if our existing cache headers were effective.
return if $resp->code == 304;
my $action_type = $self->{action_type}
or return;
my $uri = $resp->request->uri;
my $cache = MT->model('as_ua_cache')->load({
url => $uri,
action_type => $action_type,
});
my $failed = !$resp->is_success();
my $no_cache_headers = !$resp->header('Etag') && !$resp->header('Last-Modified');
if ($failed || $no_cache_headers) {
$cache->remove() if $cache;
return;
}
$cache ||= MT->model('as_ua_cache')->new();
$cache->set_values({
url => $uri,
action_type => $action_type,
etag => ($resp->header('Etag') || undef),
last_modified => ($resp->header('Last-Modified') || undef),
});
$cache->save();
}
sub get {
my $self = shift;
my ($uri, %headers) = @_;
$self->_add_cache_headers( uri => $uri, headers => \%headers );
my $resp = $self->{ua}->get($uri, %headers);
if ($self->{die_on_not_modified} && $resp->code == 304) {
die ActionStreams::UserAgent::NotModified->new(
join q{ }, "GET", $uri, "failed:", $resp->status_line,
);
}
$self->_save_cache_headers($resp);
return $resp;
}
our $AUTOLOAD;
sub AUTOLOAD {
my $funcname = $AUTOLOAD;
$funcname =~ s{ \A .* :: }{}xms;
return if $funcname eq 'DESTROY';
my $fn = sub {
my $self = shift;
- return shift->{ua}->$funcname(@_) if ref $self;
+ return $self->{ua}->$funcname(@_) if ref $self;
if (eval { require LWPx::ParanoidAgent; 1 }) {
return LWPx::ParanoidAgent->$funcname(@_);
}
return LWP::UserAgent->$funcname(@_);
};
{
no strict 'refs';
*{$AUTOLOAD} = $fn;
}
goto &$AUTOLOAD;
}
1;
|
markpasc/mt-plugin-action-streams
|
91dbd9815349d483bc626ec317daa8c1fe7af557
|
Don't queue a publish job if the finfo's template doesn't have an output file BugzID: 99181
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
index 0fe637e..cfd3976 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
@@ -189,599 +189,604 @@ sub list_profileevent {
push @{ $params{services} }, {
service_id => $prevt,
service_name => $service->{name},
};
}
$params{services} = [ sort { lc $a->{service_name} cmp lc $b->{service_name} } @{ $params{services} } ];
my %terms = (
class => '*',
author_id => $author->id,
);
my %args = (
sort => 'created_on',
direction => 'descend',
);
if (my $filter = $app->param('filter')) {
$params{filter_key} = $filter;
my $filter_val = $params{filter_val} = $app->param('filter_val');
if ($filter eq 'service') {
$params{filter_label} = $app->translate('Actions from the service [_1]', $app->registry('profile_services')->{$filter_val}->{name});
$terms{class} = $filter_val . '_%';
$args{like} = { class => 1 };
}
elsif ($filter eq 'visible') {
$params{filter_label} = ($filter_val eq 'show') ? $app->translate('Actions that are shown')
: $app->translate('Actions that are hidden');
$terms{visible} = $filter_val eq 'show' ? 1 : 0;
}
}
$params{id} = $params{edit_author_id} = $author->id;
$params{name} = $params{edit_author_name} = $author->name;
$params{service_styles} = \@service_styles_loop;
$app->listing({
type => 'profileevent',
terms => \%terms,
args => \%args,
listing_screen => 1,
code => $code,
template => $plugin->load_tmpl('list_profileevent.tmpl'),
params => \%params,
});
}
sub itemset_hide_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(0);
$event->save;
}
$app->add_return_arg( hidden => 1 );
$app->call_return;
}
sub itemset_show_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(1);
$event->save;
}
$app->add_return_arg( shown => 1 );
$app->call_return;
}
sub _itemset_hide_show_all_events {
my ($app, $new_visible) = @_;
$app->validate_magic or return;
my $event_class = MT->model('profileevent');
# Really we should work directly from the selected author ID, but as an
# itemset event we only got some event IDs. So use its.
my ($event_id) = $app->param('id');
my $event = $event_class->load($event_id)
or return $app->error($app->translate('No such event [_1]', $event_id));
my $author = _edit_author( $event->author_id ) or return;
my $driver = $event_class->driver;
my $stmt = $driver->prepare_statement($event_class, {
# TODO: include filter value when we have filters
author_id => $author->id,
visible => $new_visible ? 0 : 1,
});
my $sql = "UPDATE " . $driver->table_for($event_class) . " SET "
. $driver->dbd->db_column_name($event_class->datasource, 'visible')
. " = ? " . $stmt->as_sql_where;
# Work around error in MT::ObjectDriver::Driver::DBI::sql by doing it inline.
my $dbh = $driver->rw_handle;
$dbh->do($sql, {}, $new_visible, @{ $stmt->{bind} })
or return $app->error($dbh->errstr);
return 1;
}
sub itemset_hide_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 0) or return;
$app->add_return_arg( all_hidden => 1 );
$app->call_return;
}
sub itemset_show_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 1) or return;
$app->add_return_arg( all_shown => 1 );
$app->call_return;
}
sub _build_service_data {
my %info = @_;
my ($networks, $streams, $author) = @info{qw( networks streams author )};
my (@service_styles_loop, @networks);
my %has_profiles;
if ($author) {
my $other_profiles = $author->other_profiles();
$has_profiles{$_->{type}} = 1 for @$other_profiles;
}
my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
keys %$networks;
TYPE: for my $type (@network_keys) {
my $ndata = $networks->{$type}
or next TYPE;
next TYPE if !$info{include_deprecated} && $ndata->{deprecated};
my @streams;
if ($streams) {
my $streamdata = $streams->{$type} || {};
@streams =
sort { lc $a->{name} cmp lc $b->{name} }
grep { grep { $_ } @$_{qw( class scraper xpath rss atom )} }
map { +{ stream => $_, %{ $streamdata->{$_} } } }
grep { $_ ne 'plugin' }
keys %$streamdata;
}
## we must translate from original. or garbles on FastCGI environment.
if ( !exists $ndata->{__ident_hint_original} ) {
$ndata->{__ident_hint_original} = $ndata->{ident_hint};
}
$ndata->{ident_hint}
= MT->component('ActionStreams')->translate( $ndata->{__ident_hint_original} )
if $ndata->{__ident_hint_original};
my $ret = {
type => $type,
%$ndata,
label => $ndata->{name},
user_has_account => ($has_profiles{$type} ? 1 : 0),
};
if (@streams) {
for my $stream (@streams) {
## we must translate from original. or garbles on FastCGI environment.
if ( !exists $stream->{__name_original} ) {
$stream->{__name_original} = $stream->{name};
}
if ( !exists $stream->{__description_original} ) {
$stream->{__description_original} = $stream->{description};
}
$stream->{name}
= MT->component('ActionStreams')->translate( $stream->{__name_original} );
$stream->{description}
= MT->component('ActionStreams')->translate( $stream->{__description_original} );
}
$ret->{streams} = \@streams if @streams;
}
push @networks, $ret;
if (!$ndata->{plugin} || $ndata->{plugin}->id ne 'actionstreams') {
push @service_styles_loop, {
service_type => $type,
service_icon => __PACKAGE__->icon_url_for_service($type, $ndata),
};
}
}
return (
service_styles => \@service_styles_loop,
networks => \@networks,
);
}
sub other_profiles {
my( $app ) = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
my $author = _edit_author( $app->param('id') ) or return;
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl( 'other_profiles.tmpl' );
my @profiles = sort { lc $a->{label} cmp lc $b->{label} }
@{ $author->other_profiles || [] };
my %params = map { $_ => $author->$_ } qw( id name );
$params{edit_author_id} = $params{id};
$params{edit_author_name} = $params{name};
my %messages = map { $_ => $app->param($_) ? 1 : 0 }
(qw( added removed updated edited ));
return $app->build_page( $tmpl, {
%params,
profiles => \@profiles,
listing_screen => 1,
_build_service_data(
networks => $app->registry('profile_services'),
),
%messages,
} );
}
sub dialog_add_edit_profile {
my ($app) = @_;
my $author = _edit_author( $app->param('author_id') ) or return;
my %edit_profile;
my $tmpl_name = 'dialog_add_profile.tmpl';
if (my $edit_type = $app->param('profile_type')) {
my $ident = $app->param('profile_ident') || q{};
my ($profile) = grep { $_->{ident} eq $ident }
@{ $author->other_profiles($edit_type) };
%edit_profile = (
edit_type => $edit_type,
edit_type_name => $app->registry('profile_services', $edit_type, 'name'),
edit_ident => $ident,
edit_streams => $profile->{streams} || [],
);
$tmpl_name = 'dialog_edit_profile.tmpl';
}
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl($tmpl_name);
return $app->build_page($tmpl, {
edit_author_id => $author->id,
_build_service_data(
networks => $app->registry('profile_services'),
streams => $app->registry('action_streams'),
author => $author,
),
%edit_profile,
});
}
sub edit_other_profile {
my $app = shift;
$app->validate_magic() or return;
my $author = _edit_author( $app->param('author_id') ) or return;
my $type = $app->param('profile_type');
my $orig_ident = $app->param('original_ident');
$author->remove_profile($type, $orig_ident);
$app->forward('add_other_profile', success_msg => 'edited');
}
sub add_other_profile {
my $app = shift;
my %param = @_;
$app->validate_magic or return;
my $author = _edit_author( $app->param('author_id') ) or return;
my( $ident, $uri, $label, $type );
if ( $type = $app->param( 'profile_type' ) ) {
my $reg = $app->registry('profile_services');
my $network = $reg->{$type}
or croak "Unknown network $type";
$label = MT->component('ActionStreams')->translate( '[_1] Profile', $network->{name} );
$ident = $app->param( 'profile_id' );
$ident =~ s{ \A \s* }{}xms;
$ident =~ s{ \s* \z }{}xms;
# Check for full URLs.
if (!$network->{ident_exact}) {
my $url_pattern = $network->{url};
my ($pre_ident, $post_ident) = split /(?:\%s|\Q{{ident}}\E)/, $url_pattern, 2;
$pre_ident =~ s{ \A http:// }{}xms;
$post_ident =~ s{ / \z }{}xms;
if ($ident =~ m{ \A (?:http://)? \Q$pre_ident\E (.*?) \Q$post_ident\E /? \z }xms) {
$ident = $1;
}
}
$uri = $network->{url};
$uri =~ s{ (?:\%s|\Q{{ident}}\E) }{$ident}xmsg;
} else {
$ident = $uri = $app->param( 'profile_uri' );
$label = $app->param( 'profile_label' );
$type = 'website';
}
my $profile = {
type => $type,
ident => $ident,
label => $label,
uri => $uri,
};
my %streams = map { join(q{_}, $type, $_) => 1 }
grep { $_ ne 'plugin' && $app->param(join q{_}, 'stream', $type, $_) }
keys %{ $app->registry('action_streams', $type) || {} };
$profile->{streams} = \%streams if %streams;
$app->run_callbacks('pre_add_profile.' . $type, $app, $author, $profile);
$author->add_profile($profile);
$app->run_callbacks('post_add_profile.' . $type, $app, $author, $profile);
my $success_msg = $param{success_msg} || 'added';
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => $author->id, $success_msg => 1 },
));
}
sub remove_other_profile {
my( $app ) = @_;
$app->validate_magic or return;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
$users{$author_id} ||= _edit_author({ id => $author_id,
no_error => 1 });
my $author = $users{$author_id} or next PROFILE;
$app->run_callbacks('pre_remove_profile.' . $type, $app, $author, $type, $ident);
$author->remove_profile( $type, $ident );
$app->run_callbacks('post_remove_profile.' . $type, $app, $author, $type, $ident);
$page_author_id = $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), removed => 1 },
));
}
sub profile_add_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
$app->param('author_id', $user->id);
my $type = $app->param('profile_type')
or return $app->error( $app->translate("Invalid request.") );
# The profile side interface doesn't have stream selection, so select
# them all by default.
# TODO: factor out the adding logic (and parameterize stream selection) to stop faking params
foreach my $stream ( keys %{ $app->registry('action_streams', $type) || {} } ) {
next if $stream eq 'plugin';
$app->param(join('_', 'stream', $type, $stream), 1);
}
add_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub profile_first_update_events {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub profile_delete_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
# TODO: factor out this logic instead of having to fake params
my $id = scalar $app->param('id');
$id = $user->id . ':' . $id;
$app->param('id', $id);
remove_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub itemset_update_profiles {
my $app = shift;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
$users{$author_id} ||= _edit_author({ id => $author_id,
no_error => 1 });
my $author = $users{$author_id} or next PROFILE;
my $profiles = $author->other_profiles($type);
if (!$profiles) {
next PROFILE;
}
my @profiles = grep { $_->{ident} eq $ident } @$profiles;
for my $author_profile (@profiles) {
update_events_for_profile($author, $author_profile,
synchronous => 1);
}
$page_author_id ||= $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), updated => 1 },
));
}
sub first_profile_update {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub rebuild_action_stream_blogs {
my ($cb, $app) = @_;
my $plugin = MT->component('ActionStreams');
my $pd_iter = MT->model('plugindata')->load_iter({
plugin => $plugin->key,
key => { like => 'configuration:blog:%' }
});
my %rebuild;
while ( my $pd = $pd_iter->() ) {
next unless $pd->data('rebuild_for_action_stream_events');
my ($blog_id) = $pd->key =~ m/:blog:(\d+)$/;
$rebuild{$blog_id} = 1;
}
for my $blog_id (keys %rebuild) {
# TODO: limit this to indexes that publish action stream data, once
# we can magically infer template content before building it
my $blog = MT->model('blog')->load( $blog_id ) or next;
# Republish all the blog's known non-virtual index fileinfos that
# have real template objects.
my $finfo_class = MT->model('fileinfo');
my $finfo_template_col = $finfo_class->driver->dbd->db_column_name(
$finfo_class->datasource, 'template_id');
my @fileinfos = $finfo_class->load({
blog_id => $blog->id,
archive_type => 'index',
virtual => [ \'IS NULL', 0 ],
}, {
join => MT->model('template')->join_on(undef,
{ id => \"= $finfo_template_col" }),
});
require MT::TheSchwartz;
require TheSchwartz::Job;
- for my $fi (@fileinfos) {
+ FINFO: for my $fi (@fileinfos) {
+ # Only publish if the matching template has an output file.
+ my $tmpl = MT->model('template')->load($fi->template_id)
+ or next FINFO;
+ next FINFO if !$tmpl->outfile;
+
my $job = TheSchwartz::Job->new();
$job->funcname('MT::Worker::Publish');
$job->uniqkey($fi->id);
$job->run_after(time + 240); # 4 minutes
MT::TheSchwartz->insert($job);
}
}
}
sub widget_recent {
my ($app, $tmpl, $widget_param) = @_;
$tmpl->param('author_id', $app->user->id);
$tmpl->param('blog_id', $app->blog->id) if $app->blog;
}
sub widget_blog_dashboard_only {
my ($page, $scope) = @_;
return if $scope eq 'dashboard:system';
return 1;
}
sub update_events {
my $mt = MT->app;
$mt->run_callbacks('pre_action_streams_task', $mt);
my $au_class = MT->model('author');
my $author_iter = $au_class->search({
status => $au_class->ACTIVE(),
}, {
join => [ $au_class->meta_pkg, 'author_id', { type => 'other_profiles' } ],
});
while (my $author = $author_iter->()) {
my $profiles = $author->other_profiles();
$mt->run_callbacks('pre_update_action_streams', $mt, $author, $profiles);
PROFILE: for my $profile (@$profiles) {
update_events_for_profile($author, $profile);
}
$mt->run_callbacks('post_update_action_streams', $mt, $author, $profiles);
}
$mt->run_callbacks('post_action_streams_task', $mt);
}
sub update_events_for_profile {
my ($author, $profile, %param) = @_;
my $type = $profile->{type};
my $streams = $profile->{streams};
return if !$streams || !%$streams;
my $services = MT->registry('profile_services');
return if !exists $services->{$type} || $services->{$type}->{deprecated};
require ActionStreams::Event;
my @event_classes = ActionStreams::Event->classes_for_type($type)
or return;
my $mt = MT->app;
$mt->run_callbacks('pre_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
EVENTCLASS: for my $event_class (@event_classes) {
next EVENTCLASS if !$streams->{$event_class->class_type};
if ($param{synchronous}) {
$event_class->update_events_loggily(
author => $author,
hide_timeless => $param{hide_timeless} ? 1 : 0,
%$profile,
);
}
else {
# Defer regular updates to job workers.
require ActionStreams::Worker;
ActionStreams::Worker->make_work(
event_class => $event_class,
author => $author,
%$profile,
);
}
}
$mt->run_callbacks('post_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
}
1;
|
markpasc/mt-plugin-action-streams
|
191d58025cdd092497d94d436a0db93bf380fda8
|
Use new Delicious feed (and logo) Collect tags for Delicious links too BugzID: 100568
|
diff --git a/mt-static/plugins/ActionStreams/images/services/delicious.png b/mt-static/plugins/ActionStreams/images/services/delicious.png
index 80af1ac..a1efb93 100755
Binary files a/mt-static/plugins/ActionStreams/images/services/delicious.png and b/mt-static/plugins/ActionStreams/images/services/delicious.png differ
diff --git a/plugins/ActionStreams/streams.yaml b/plugins/ActionStreams/streams.yaml
index 8d86f26..a856683 100644
--- a/plugins/ActionStreams/streams.yaml
+++ b/plugins/ActionStreams/streams.yaml
@@ -1,649 +1,645 @@
oneup:
playing:
name: Currently Playing
description: The games in your collection you're currently playing
class: OneupPlaying
backtype:
comments:
name: Comments
description: Comments you have made on the web
fields:
- queue
html_form: '[_1] commented on <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.backtype.com/{{ident}}'
rss: 1
identifier: url
colourlovers:
colors:
name: Colors
description: Colors you saved
fields:
- queue
html_form: '[_1] saved the color <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/colors/new?lover={{ident}}'
xpath:
foreach: //color
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
palettes:
name: Palettes
description: Palettes you saved
fields:
- queue
html_form: '[_1] saved the palette <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/palettes/new?lover={{ident}}'
xpath:
foreach: //palette
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
patterns:
name: Patterns
description: Patterns you saved
fields:
- queue
html_form: '[_1] saved the pattern <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/patterns/new?lover={{ident}}'
xpath:
foreach: //pattern
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
favpalettes:
name: Favorite Palettes
description: Palettes you saved as favorites
fields:
- queue
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite palette'
html_params:
- url
- title
url: 'http://www.colourlovers.com/rss/lover/{{ident}}/palettes/favorites'
rss: 1
corkd:
reviews:
name: Reviews
description: Your wine reviews
fields:
- review
html_form: '[_1] reviewed <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/journal/{{ident}}'
rss: 1
cellar:
name: Cellar
description: Wines you own
fields:
- wine
html_form: '[_1] owns <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/cellar/{{ident}}'
rss: 1
list:
name: Shopping List
description: Wines you want to buy
fields:
- wine
html_form: '[_1] wants <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/shoppinglist/{{ident}}'
rss: 1
delicious:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
- url: 'http://feeds.delicious.com/rss/{{ident}}'
+ url: 'http://feeds.delicious.com/v2/rss/{{ident}}?plain'
identifier: url
- xpath:
- foreach: //item
- get:
- created_on: dc:date
- title: title
- url: link
- note: description
+ rss:
+ note: description
+ tags: category/child::text()
digg:
links:
name: Dugg
description: Links you dugg
html_form: '[_1] dugg the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://digg.com/users/{{ident}}/history/diggs.rss'
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
submitted:
name: Submissions
description: Links you submitted
html_form: '[_1] submitted the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://digg.com/users/{{ident}}/history/submissions.rss
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
ffffound:
favorites:
name: Found
description: Photos you found
html_form: '[_1] ffffound <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://ffffound.com/home/{{ident}}/found/feed
rss: 1
flickr:
favorites:
name: Favorites
description: Photos you marked as favorites
fields:
- by
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite photo'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_faves.gne?nsid={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
by: author/name
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_public.gne?id={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
friendfeed:
likes:
name: Likes
description: Things from your friends that you "like"
html_form: '[_1] likes <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://friendfeed.com/{{ident}}/likes?format=atom'
atom:
url: link/@href
gametap:
scores:
name: Leaderboard scores
description: Your high scores in games with leaderboards
fields:
- score
html_form: '[_1] scored <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- score
- url
- title
url: http://www.gametap.com/profile/leaderboards.do?sn={{ident}}
identifier: title,score
scraper:
foreach: 'div.buddy-leaderboards div.tr'
get:
url:
- 'div.name a'
- '@href'
title:
- 'div.name strong'
- TEXT
score:
- 'div.name div'
- TEXT
goodreads:
toread:
name: To read
description: Books on your "to-read" shelf
fields:
- by
html_form: '[_1] saved <a href="[_2]"><i>[_3]</i> by [_4]</a> to read'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=to-read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
reading:
name: Reading
description: Books on your "currently-reading" shelf
fields:
- by
html_form: '[_1] started reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=currently-reading'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
read:
name: Read
description: Books on your "read" shelf
fields:
- by
html_form: '[_1] finished reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
googlereader:
links:
name: Shared
description: Your shared items
html_form: '[_1] shared <a href="[_2]">[_3]</a> from <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- source_url
- source_title
class: GoogleReader
iconbuffet:
icons:
name: Deliveries
description: Icon sets you were delivered
html_form: '[_1] received the icon set <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.iconbuffet.com/people/{{ident}};received_packages'
identifier: url
scraper:
foreach: 'div#icons div.preview-sm'
get:
title:
- a span
- TEXT
url:
- a
- '@href'
identica:
statuses:
name: Notices
description: Notices you posted
html_form: '[_1] <a href="[_2]">said</a>, “[_3]”'
html_params:
- url
- title
url: 'http://identi.ca/{{ident}}/rss'
rss:
created_on: dc:date
class: Identica
iminta:
links:
name: Intas
description: Links you saved
html_form: '[_1] is inta <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://iminta.com/people/{{ident}}/rss.xml?inta_source_id=11'
rss: 1
istockphoto:
photos:
name: Photos
description: Photos you posted that were approved
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.istockphoto.com/webservices/feeds/?feedFormat=IStockAtom_1_0&feedName=istockfeed.image.newestUploads&feedParams=UserID={{ident}}'
identifier: url
atom:
thumbnail: content/div/a/img/@src
iusethis:
events:
name: Recent events
description: Events from your recent events feed
html_form: '[_1] <a href="[_2]">[_3]</a>'
html_params:
- url
- title
rss: 1
url: 'http://osx.iusethis.com/user/feed.rss/{{ident}}?following=0'
osxapps:
name: Apps you use
description: The applications you saved as ones you use
fields:
- favorite
html_form: '[_1] started using <a href="[_2]">[_3]</a>[quant,_4, (and loves it),,]'
html_params:
- url
- title
- favorite
url: 'http://osx.iusethis.com/user/{{ident}}'
iwatchthis:
favorites:
name: Favorites
description: Videos you saved as watched
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video'
html_params:
- url
- title
url: 'http://iwatchthis.com/rss/{{ident}}'
rss: 1
jaiku:
jaikus:
name: Jaikus
description: Jaikus you posted
html_form: '[_1] <a href="[_2]">jaiku''d</a>, "[_3]"'
html_params:
- url
- title
url: 'http://{{ident}}.jaiku.com/feed/atom'
atom: 1
kongregate:
favorites:
name: Favorites
description: Games you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite game'
html_params:
- url
- title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url
scraper:
foreach: #favorites dl
get:
url:
- dd a
- '@href'
title:
- dd a
- TEXT
thumbnail:
- dt img
- '@src'
achievements:
name: Achievements
description: Achievements you won
fields:
- game_title
html_form: '[_1] won the <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- title
- url
- game_title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url,title
scraper:
foreach: #achievements .badge_details
get:
url:
- dt.badge_img a
- '@href'
thumbnail:
- dt.badge_img img
- '@style'
title:
- dd.badge_name
- TEXT
game_title:
- a.badge_game
- TEXT
lastfm:
tracks:
name: Tracks
description: Songs you recently listened to (High spam potential!)
html_form: '[_1] heard <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/recenttracks.rss'
rss: 1
lovedtracks:
name: Loved Tracks
description: Songs you marked as "loved"
fields:
- artist
html_form: '[_1] loved <a href="[_2]">[_3]</a> by [_4]'
html_params:
- url
- title
- artist
url: 'http://pipes.yahoo.com/pipes/pipe.run?_id=4smlkvMW3RGPpBPfTqoASA&_render=rss&lastFM_UserName={{ident}}'
identifier: url
rss:
artist: description
journalentries:
name: Journal Entries
description: Your recent journal entries
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/journals.rss'
rss: 1
events:
name: Events
description: The events you said you'll be attending
html_form: '[_1] is attending <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/events.rss'
rss: 1
livejournal:
posts:
name: Posts
description: Your public posts to your journal
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://users.livejournal.com/{{ident}}/data/atom'
atom: 1
magnolia:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ma.gnolia.com/atom/full/people/{{ident}}'
identifier: url
atom:
tags: "category[@scheme='http://ma.gnolia.com/tags']/@term"
note: content
netflix:
queue:
name: Queue
description: Movies you added to your rental queue
fields:
- queue
html_form: '[_1] queued <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/QueueRSS?id={{ident}}'
rss:
thumbnail: description
recent:
name: Recent Movies
description: Recent Rental Activity
fields:
- recent
html_form: '[_1] is watching <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/TrackingRSS?id={{ident}}'
rss:
thumbnail: description
netvibes:
links:
name: Links
description: Links you saved
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www2.netvibes.com/rest/account/{{ident}}/timeline?format=atom'
atom: 1
ohloh:
kudos:
name: Kudos
description: Kudos you have received
html_form: '[_1] received kudos from <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.ohloh.net/accounts/{{ident}}/kudos'
identifier: url
scraper:
foreach: 'div.received_kudo'
get:
url:
- a
- '@href'
title:
- a
- TEXT
pandora:
favorites:
name: Favorite Songs
description: Songs you marked as favorites
fields:
- album_art
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite song'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favorites.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
album_art: pandora:albumArtUrl
favoriteartists:
name: Favorite Artists
description: Artists you marked as favorites
fields:
- artist-photo-url
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite artist'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favoriteartists.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
artist-photo-url: pandora:stationImageUrl
stations:
name: Stations
description: Radio stations you added
fields:
- guid
- station-image-url
html_form: '[_1] added a new radio station named <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/stations.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: pandora:stationLink
station-image-url: pandora:stationImageUrl
picasaweb:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://picasaweb.google.com/data/feed/api/user/{{ident}}?kind=photo&max-results=15'
atom:
|
markpasc/mt-plugin-action-streams
|
edaba2f769df1ff8397d0eb10111026c8f5e8f5f
|
Ignore DIE handlers for these checks, since they intentionally fail a lot (thanks, Jay!) BugzID: 95748
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm
index 46b430c..93a5abf 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm
@@ -1,794 +1,801 @@
package ActionStreams::Event;
use strict;
use base qw( MT::Object MT::Taggable MT::Scorable );
our @EXPORT_OK = qw( classes_for_type );
use HTTP::Date qw( str2time );
use MT::Util qw( encode_html encode_url );
use MT::I18N;
use ActionStreams::Scraper;
our $hide_timeless = 0;
__PACKAGE__->install_properties({
column_defs => {
id => 'integer not null auto_increment',
identifier => 'string(200)',
author_id => 'integer not null',
visible => 'integer not null',
},
defaults => {
visible => 1,
},
indexes => {
identifier => 1,
author_id => 1,
created_on => 1,
created_by => 1,
},
class_type => 'event',
audit => 1,
meta => 1,
datasource => 'profileevent',
primary_key => 'id',
});
__PACKAGE__->install_meta({
columns => [ qw(
title
url
thumbnail
via
via_id
) ],
});
# Oracle does not like an identifier of more than 30 characters.
sub datasource {
my $class = shift;
my $r = MT->request;
my $ds = $r->cache('as_event_ds');
return $ds if $ds;
my $dss_oracle = qr/(db[id]::)?oracle/;
if ( my $type = MT->config('ObjectDriver') ) {
if ((lc $type) =~ m/^$dss_oracle$/) {
$ds = 'as';
}
}
$ds = $class->properties->{datasource}
unless $ds;
$r->cache('as_event_ds', $ds);
return $ds;
}
sub encode_field_for_html {
my $event = shift;
my ($field) = @_;
return encode_html( $event->$field() );
}
sub as_html {
my $event = shift;
my %params = @_;
my $stream = $event->registry_entry or return '';
# How many spaces are there in the form?
my $form = $params{form} || $stream->{html_form} || q{};
my @nums = $form =~ m{ \[ _ (\d+) \] }xmsg;
my $max = shift @nums;
for my $num (@nums) {
$max = $num if $max < $num;
}
# Do we need to supply the author name?
my @content = map { $event->encode_field_for_html($_) }
@{ $stream->{html_params} };
if ($max > scalar @content) {
my $name = defined $params{name} ? $params{name}
: $event->author->nickname
;
unshift @content, encode_html($name);
}
return MT->translate($form, @content);
}
sub update_events_loggily {
my $class = shift;
my %profile = @_;
# Keep this option out of band so we don't have to count on
# implementations of update_events() passing it through.
local $hide_timeless = delete $profile{hide_timeless} ? 1 : 0;
my $warn = $SIG{__WARN__} || sub { print STDERR $_[0] };
local $SIG{__WARN__} = sub {
my ($msg) = @_;
$msg =~ s{ \n \z }{}xms;
$msg = MT->component('ActionStreams')->translate(
'[_1] updating [_2] events for [_3]',
$msg, $profile{type}, $profile{author}->name,
);
$warn->("$msg\n");
};
eval {
$class->update_events(%profile);
};
if (my $err = $@) {
my $plugin = MT->component('ActionStreams');
my $err_msg = $plugin->translate("Error updating events for [_1]'s [_2] stream (type [_3] ident [_4]): [_5]",
$profile{author}->name, $class->properties->{class_type},
$profile{type}, $profile{ident}, $err);
MT->log($err_msg);
die $err; # re-throw so we can handle from job invocation
}
}
sub update_events {
my $class = shift;
my %profile = @_;
my $author = delete $profile{author};
my $stream = $class->registry_entry or return;
my $fetch = $stream->{fetch} || {};
local $profile{url} = $stream->{url};
die "Oops, no url?" if !$profile{url};
die "Oops, no ident?" if !$profile{ident};
require MT::I18N;
my $ident = encode_url(MT::I18N::encode_text($profile{ident}, undef, 'utf-8'));
$profile{url} =~ s/ {{ident}} / $ident /xmsge;
my $items;
if (my $xpath_params = $stream->{xpath}) {
$items = $class->fetch_xpath(
%$xpath_params,
%$fetch,
%profile,
);
}
elsif (my $atom_params = $stream->{atom}) {
my $get = {
created_on => 'published',
modified_on => 'updated',
title => 'title',
url => q{link[@rel='alternate']/@href},
via => q{link[@rel='alternate']/@href},
via_id => 'id',
identifier => 'id',
};
$atom_params = {} if !ref $atom_params;
@$get{keys %$atom_params} = values %$atom_params;
$items = $class->fetch_xpath(
foreach => '//entry',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $rss_params = $stream->{rss}) {
my $get = {
title => 'title',
url => 'link',
via => 'link',
created_on => 'pubDate',
thumbnail => 'media:thumbnail/@url',
via_id => 'guid',
identifier => 'guid',
};
$rss_params = {} if !ref $rss_params;
@$get{keys %$rss_params} = values %$rss_params;
$items = $class->fetch_xpath(
foreach => '//item',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $scraper_params = $stream->{scraper}) {
my ($foreach, $get) = @$scraper_params{qw( foreach get )};
my $scraper = scraper {
process $foreach, 'res[]' => scraper {
while (my ($field, $sel) = each %$get) {
process $sel->[0], $field => $sel->[1];
}
};
result 'res';
};
$items = $class->fetch_scraper(
scraper => $scraper,
%$fetch,
%profile,
);
}
return if !$items;
$class->build_results(
items => $items,
stream => $stream,
author => $author,
profile => \%profile,
);
}
sub registry_entry {
my $event = shift;
my ($type, $stream) = split /_/, $event->properties->{class_type}, 2;
my $reg = MT->instance->registry('action_streams') or return;
my $service = $reg->{$type} or return;
$service->{$stream};
}
sub author {
my $event = shift;
my $author_id = $event->author_id
or return;
return MT->instance->model('author')->lookup($author_id);
}
sub blog_id { 0 }
sub classes_for_type {
my $class = shift;
my ($type) = @_;
my $prevts = MT->instance->registry('action_streams');
my $prevt = $prevts->{$type};
return if !$prevt;
my @classes;
PACKAGE: while (my ($stream_id, $stream) = each %$prevt) {
next if 'HASH' ne ref $stream;
next if !$stream->{class} && !$stream->{url};
+ # This check intentionally fails a lot, so ignore any DIE handler we
+ # might have.
+ my $has_props = sub {
+ my $pkg = shift;
+ return eval { local $SIG{__DIE__}; $pkg->properties };
+ };
+
my $pkg;
if ($pkg = $stream->{class}) {
$pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms;
- if (!eval { $pkg->properties }) {
+ if (!$has_props->($pkg)) {
if (!eval "require $pkg; 1") {
my $error = $@ || q{};
my $pl = MT->component('ActionStreams');
MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]',
$pkg, $type, $stream_id, $error));
next PACKAGE;
}
}
}
else {
$pkg = join q{::}, $class, 'Auto', ucfirst $type,
ucfirst $stream_id;
- if (!eval { $pkg->properties }) {
- eval "package $pkg; use base qw( $class ); 1" or next;
+ if (!$has_props->($pkg)) {
+ eval "package $pkg; use base qw( $class ); 1" or next PACKAGE;
my $class_type = join q{_}, $type, $stream_id;
$pkg->install_properties({ class_type => $class_type });
$pkg->install_meta({ columns => $stream->{fields} })
if $stream->{fields};
}
}
push @classes, $pkg;
}
return @classes;
}
my $ua;
sub ua {
my $class = shift;
my %params = @_;
$ua ||= MT->new_ua({
paranoid => 1,
timeout => 10,
});
$ua->max_size(250_000) if $ua->can('max_size');
$ua->agent($params{default_useragent} ? $ua->_agent
: "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version);
return $ua if $class->class_type eq 'event';
return $ua if $params{unconditional};
require ActionStreams::UserAgent::Adapter;
my $adapter = ActionStreams::UserAgent::Adapter->new(
ua => $ua,
action_type => $class->class_type,
die_on_not_modified => $params{die_on_not_modified} || 0,
);
return $adapter;
}
sub set_values {
my $event = shift;
my ($values) = @_;
for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) {
my $meta_val = delete $values->{$meta_col};
$event->$meta_col($meta_val) if defined $meta_val;
}
$event->SUPER::set_values($values);
}
sub fetch_xpath {
my $class = shift;
my %params = @_;
my $url = $params{url} || '';
if (!$url) {
MT->log(
MT->component('ActionStreams')->translate(
"No URL to fetch for [_1] results", $class));
return;
}
my $ua = $class->ua(%params);
my $res = $ua->get($url);
if (!$res->is_success()) {
MT->log(
MT->component('ActionStreams')->translate(
"Could not fetch [_1]: [_2]", $url, $res->status_line()))
if $res->code != 304;
return;
}
# Do not continue if contents is incomplete.
if (my $abort = $res->{_headers}{'client-aborted'}) {
MT->log(
MT->component('ActionStreams')->translate(
'Aborted fetching [_1]: [_2]', $url, $abort));
return;
}
# Strip leading whitespace, since the parser doesn't like it.
# TODO: confirm we got xml?
my $content = $res->content;
$content =~ s{ \A \s+ }{}xms;
require XML::XPath;
my $x = XML::XPath->new( xml => $content );
my @items;
ITEM: for my $item ($x->findnodes($params{foreach})) {
my %item_data;
VALUE: while (my ($key, $val) = each %{ $params{get} }) {
next VALUE if !$val;
if ($key eq 'tags') {
my @outvals = $item->findnodes($val)
or next VALUE;
$item_data{$key} = [ map { MT::I18N::utf8_off( $_->getNodeValue ) } @outvals ];
}
else {
my $outval = $item->findvalue($val)
or next VALUE;
$outval = MT::I18N::utf8_off("$outval");
if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) {
# try both RFC 822/1123 and ISO 8601 formats
$outval = MT::Util::epoch2ts(undef, str2time($outval))
|| MT::Util::iso2ts(undef, $outval);
}
$item_data{$key} = $outval if $outval;
}
}
push @items, \%item_data;
}
return \@items;
}
sub build_results {
my $class = shift;
my %params = @_;
my ($author, $items, $profile, $stream) =
@params{qw( author items profile stream )};
my $mt = MT->app;
ITEM: for my $item (@$items) {
my $event;
my $identifier = delete $item->{identifier};
if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) {
$identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} };
}
if (defined $identifier) {
$identifier = "$identifier";
($event) = $class->search({
author_id => $author->id,
identifier => $identifier,
});
}
$event ||= $class->new;
$mt->run_callbacks('pre_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
my $tags = delete $item->{tags};
$event->set_values({
author_id => $author->id,
identifier => $identifier,
%$item,
});
$event->tags(@$tags) if $tags;
if ($hide_timeless && !$event->created_on) {
$event->visible(0);
}
$mt->run_callbacks('post_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
$event->save() or MT->log($event->errstr);
}
1;
}
sub save {
my $event = shift;
# Built-in audit field setting will set a local time, so do it ourselves.
if (!$event->created_on) {
my $ts = MT::Util::epoch2ts(undef, time);
$event->created_on($ts);
$event->modified_on($ts);
}
return $event->SUPER::save(@_);
}
sub fetch_scraper {
my $class = shift;
my %params = @_;
my ($url, $scraper) = @params{qw( url scraper )};
$scraper->user_agent( $class->ua( %params, die_on_not_modified => 1 ) );
my $uri_obj = URI->new($url);
my $items = eval { $scraper->scrape($uri_obj) };
# Ignore Web::Scraper errors due to 304 Not Modified responses.
if (!$items && $@ && !UNIVERSAL::isa($@, 'ActionStreams::UserAgent::NotModified')) {
die; # rethrow
}
# we're only being used for our scraper.
return if !$items;
return $items if !ref $items;
return $items if 'ARRAY' ne ref $items;
ITEM: for my $item (@$items) {
next ITEM if !ref $item || ref $item ne 'HASH';
for my $field (keys %$item) {
if ($field eq 'tags') {
$item->{$field} = [ map { MT::I18N::utf8_off( "$_" ) } @{ $item->{$field} } ];
}
else {
$item->{$field} = MT::I18N::utf8_off( q{} . $item->{$field} );
}
}
}
return $items;
}
sub backup_terms_args {
my $class = shift;
my ($blog_ids) = @_;
return { terms => { 'class' => '*' }, args => undef };
}
1;
__END__
=head1 NAME
ActionStreams::Event - an Action Streams stream definition
=head1 SYNOPSIS
# in plugin's config.yaml
profile_services:
example:
streamid:
name: Dice Example
description: A simple die rolling Perl stream example.
html_form: [_1] rolled a [_2]!
html_params:
- title
class: My::Stream
# in plugin's lib/My/Stream.pm
package My::Stream;
use base qw( ActionStreams::Event );
__PACKAGE__->install_properties({
class_type => 'example_streamid',
});
sub update_events {
my $class = shift;
my %profile = @_;
# trivial example: save a random number
my $die_roll = int rand 20;
my %item = (
title => $die_roll,
identifier => $die_roll,
);
return $class->build_results(
author => $profile{author},
items => [ \%item ],
);
}
1;
=head1 DESCRIPTION
I<ActionStreams::Event> provides the basic implementation of an action stream.
Stream definitions are engines for turning web resources into I<actions> (also
called I<events>). This base class produces actions based on generic stream
recipes defined in the MT registry, as well as providing the internal machinery
for you to implement your own streams in Perl code.
=head1 METHODS TO IMPLEMENT
These are the methods one commonly implements (overrides) when implementing a
stream subclass.
=head2 C<$class-E<gt>update_events(%profile)>
Fetches the web resource specified by the profile parameters, collects data
from it into actions, and saves the action records for use later. Required
members of C<%profile> are:
=over 4
=item * C<author>
The C<MT::Author> instance for whom events should be collected.
=item * C<ident>
The author's identifier on the given service.
=back
Other information about the stream, such as the URL pattern into which the
C<ident> parameter can be replaced, is available through the
C<$class-E<gt>registry_entry()> method.
=head2 C<$self-E<gt>as_html(%params)>
Returns the HTML version of the action, suitable for display to readers.
The default implementation uses the stream's registry definition to construct
the action: the author's name and the action's values as named in
C<html_params> are replaced into the stream's C<html_form> setting. You need
override it only if you have more complex requirements.
Optional members of C<%params> are:
=over 4
=item * C<form>
The formatting string to use. If not given, the C<html_form> specified for
this stream in the registry is used.
=item * C<name>
The text to use as the author's name if C<as_html> needs to provide it
automatically in the result. Author names are provided if there are more
tokens in C<html_form> than there are fields specified in C<html_params>.
If not given, the event's author's nickname is provided. Note that a defined
but empty name (such as C<q{}>) I<will> be used; in this case, the name will
appear to be omitted from the result of the C<as_html> call.
=back
=head1 AVAILABLE METHODS
These are the methods provided by I<ActionStreams::Event> to perform common
tasks. Call them from your overridden methods.
=head2 C<$self-E<gt>set_values(\%values)>
Stores the data given in C<%values> as members of this event.
=head2 C<$class-E<gt>fetch_xpath(%param)>
Returns the items discovered by scanning a web resource by the given XPath
recipe. Required members of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be a
valid XML document.
=item * C<foreach>
The XPath selector with which to select the individual events from the
resource.
=item * C<get>
A hashref containing the XPath selectors with which to collect individual data
for each item, keyed on the names of the fields to contain the data.
=back
C<%param> may also contain additional arguments for the C<ua()> method.
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
=head2 C<$class-E<gt>fetch_scraper(%param)>
Returns the items discovered by scanning by the given recipe. Required members
of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be an
HTML or XML document suitable for analysis by the C<Web::Scraper> module.
=item * C<scraper>
The C<Web::Scraper> scraper with which to extract item data from the specified
web resource. See L<Web::Scraper> for information on how to construct a
scraper.
=back
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
See also the below I<NOTE ON WEB::SCRAPER>.
=head2 C<$class-E<gt>build_results(%param)>
Converts a set of collected items into saved action records of type C<$class>.
The required members of C<%param> are:
=over 4
=item * C<author>
The C<MT::Author> instance whose action the items represent.
=item * C<items>
An arrayref of items to save as actions. Each item is a hashref containing the
action data, keyed on the names of the fields containing the data.
=back
Optional parameters are:
=over 4
=item * C<profile>
An arrayref describing the data for the author's profile for the associated
stream, such as is returned by the C<MT::Author::other_profile()> method
supplied by the Action Streams plugin.
The profile member is not used directly by C<build_results()>; they are only
passed to callbacks.
=item * C<stream>
A hashref containing the settings from the registry about the stream, such as
is returned from the C<registry_entry()> method.
=back
=head2 C<$class-E<gt>ua(%param)>
Returns the common HTTP user-agent, an instance of C<LWP::UserAgent>, with
which you can fetch web resources.
The resulting user agent may provide automatic conditional HTTP support when
you call its C<get> method. A UA with conditional HTTP support enabled will
store the values of the conditional HTTP headers (C<ETag> and
C<Last-Modified>) received in responses as C<ActionStreams::UserAgent::Cache>
objects and, on subsequent requests of the same URL, automatically supply the
header values. When the remote HTTP server reports that such a resource has
not changed, the C<HTTP::Response> will be a C<304 Not Modified> response; the
user agent does not itself store and supply the resource content. Using other
C<LWP::UserAgent> methods such as C<post> or C<request> will I<not> trigger
automatic conditional HTTP support.
No arguments are required; possible optional parameters are:
=over 4
=item * C<default_useragent>
If set, the returned HTTP user-agent will use C<LWP::UserAgent>'s default
identifier in the HTTP C<User-Agent> header. If omitted, the UA will use the
Action Streams identifier of C<mt-actionstreams-lwp/I<version>>.
=item * C<unconditional>
If set, the return HTTP user-agent will I<not> automatically use conditional
HTTP to avoid requesting old content from compliant servers. That is, if
omitted, the UA I<will> automatically use conditional HTTP when you call its
C<get> method.
=item * C<die_on_not_modified>
If set, when the response of the HTTP user-agent's C<get> method is a
conditional HTTP C<304 Not Modified> response, throw an exception instead of
returning the response. (Use this option to return control to yourself when
passing UAs with conditional HTTP support to other Perl modules that don't
expect 304 responses.)
The thrown exception is an C<ActionStreams::UserAgent::NotModified> exception.
=back
=head2 C<$self-E<gt>author()>
Returns the C<MT::Author> instance associated with this event, if its
C<author_id> field has been set.
=head2 C<$class-E<gt>install_properties(\%properties)>
I<TODO>
=head2 C<$class-E<gt>install_meta(\%properties)>
I<TODO>
=head2 C<$class-E<gt>registry_entry()>
Returns the registry data for the stream represented by C<$class>.
=head2 C<$class-E<gt>classes_for_type($service_id)>
Given a profile service ID (that is, a key from the C<profile_services> section
of the registry), returns a list of stream classes for scanning that service's
streams.
=head2 C<$class-E<gt>backup_terms_args($blog_ids)>
Used in backup. Backup function calls the method to generate $terms and
$args for the class to load objects. ActionStream::Event does not have
blog_id and does use class_column, the nature the class has to tell
backup function to properly load all the target objects of the class
|
markpasc/mt-plugin-action-streams
|
d192690348ad0c22e0e2d74806a9d4fb72edff7c
|
Use 'not like' operator if service or stream attributes are specified individually with leading 'not'
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Tags.pm b/plugins/ActionStreams/lib/ActionStreams/Tags.pm
index 743a42d..da58eca 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Tags.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Tags.pm
@@ -1,548 +1,552 @@
package ActionStreams::Tags;
use strict;
use MT::Util qw( offset_time_list epoch2ts ts2epoch );
use ActionStreams::Plugin;
sub stream_action {
my ($ctx, $args, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamAction in a non-action-stream context!");
return $event->as_html(
defined $args->{name} ? (name => $args->{name}) : ()
);
}
sub stream_action_id {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionURL in a non-action-stream context!");
return $event->id || '';
}
sub stream_action_var {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionVar in a non-action-stream context!");
my $var = $arg->{var} || $arg->{name}
or return $ctx->error("Used StreamActionVar without a 'name' attribute!");
return $ctx->error("Use StreamActionVar to retrieve invalid variable $var from event of type " . ref $event)
if !$event->can($var) && !$event->has_column($var);
return $event->$var();
}
sub stream_action_date {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionDate in a non-action-stream context!");
my $c_on = $event->created_on;
local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $c_on) )
if $c_on;
return $ctx->_hdlr_date($arg);
}
sub stream_action_modified_date {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionModifiedDate in a non-action-stream context!");
my $m_on = $event->modified_on || $event->created_on;
local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $m_on) )
if $m_on;
return $ctx->_hdlr_date($arg);
}
sub stream_action_title {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionTitle in a non-action-stream context!");
return $event->title || '';
}
sub stream_action_url {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionURL in a non-action-stream context!");
return $event->url || '';
}
sub stream_action_thumbnail_url {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionThumbnailURL in a non-action-stream context!");
return $event->thumbnail || '';
}
sub stream_action_via {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionVia in a non-action-stream context!");
return $event->via || q{};
}
sub other_profile_var {
my( $ctx, $args ) = @_;
my $profile = $ctx->stash( 'other_profile' )
or return $ctx->error( 'No profile defined in ProfileVar' );
my $var = $args->{name} || 'uri';
return defined $profile->{ $var } ? $profile->{ $var } : '';
}
sub _author_ids_for_args {
my ($ctx, $args, $cond) = @_;
my @author_ids;
if (my $ids = $args->{author_ids} || $args->{author_id}) {
@author_ids = split /\s*,\s*/, $ids;
}
elsif (my $disp_names = $args->{display_names} || $args->{display_name}) {
my @names = split /\s*,\s*/, $disp_names;
my @authors = MT->model('author')->load({ nickname => \@names });
@author_ids = map { $_->id } @authors;
}
elsif (my $names = $args->{author} || $args->{authors}) {
# If arg is the special string 'all', then include all authors by returning undef instead of an empty array.
return if $names =~ m{ \A\s* all \s*\z }xmsi;
my @names = split /\s*,\s*/, $names;
my @authors = MT->model('author')->load({ name => \@names });
@author_ids = map { $_->id } @authors;
}
elsif (my $author = $ctx->stash('author')) {
@author_ids = ( $author->id );
}
elsif (my $blog = $ctx->stash('blog')) {
my @authors = MT->model('author')->load({
status => 1, # enabled
}, {
join => MT->model('permission')->join_on('author_id',
{ blog_id => $blog->id }, { unique => 1 }),
});
my $blog_id = $ctx->stash('blog_id');
my $blog = MT->model('blog')->load( $blog_id );
if ( $args->{no_commenter} ) {
@author_ids = map { $_->[0]->id }
grep { $_->[1]->can_administer_blog || $_->[1]->can_create_post }
map { [ $_, $_->permissions($blog->id) ] }
@authors;
}
elsif ( $blog->publish_authd_untrusted_commenters ) {
@author_ids = map { $_->[0]->id }
grep {
$_->[1]->can_administer_blog
|| $_->[1]->can_create_post
|| $_->[1]->has('comment')
|| ( $_->[0]->type == MT::Author::COMMENTER()
&& !$_->[0]->is_banned($blog_id) )
}
map { [ $_, $_->permissions($blog->id) ] }
@authors;
}
else {
@author_ids = map { $_->[0]->id }
grep {
$_->[1]->can_administer_blog
|| $_->[1]->can_create_post
|| $_->[1]->has('comment')
}
map { [ $_, $_->permissions($blog->id) ] }
@authors;
}
}
return \@author_ids;
}
sub action_streams {
my ($ctx, $args, $cond) = @_;
my %terms = (
class => '*',
visible => 1,
);
my $author_id = _author_ids_for_args(@_);
$terms{author_id} = $author_id if defined $author_id;
my %args = (
sort => ($args->{sort_by} || 'created_on'),
direction => ($args->{direction} || 'descend'),
);
my $app = MT->app;
undef $app unless $app->isa('MT::App');
if (my $limit = $args->{limit} || $args->{lastn}) {
$args{limit} = $limit eq 'auto' ? ( $app ? $app->param('limit') : 20 ) : $limit;
$args{limit} = 20 unless $args{limit};
}
elsif (my $days = $args->{days}) {
my @ago = offset_time_list(time - 3600 * 24 * $days,
$ctx->stash('blog'));
my $ago = sprintf "%04d%02d%02d%02d%02d%02d",
$ago[5]+1900, $ago[4]+1, @ago[3,2,1,0];
$terms{created_on} = [ $ago ];
$args{range_incl}{created_on} = 1;
}
else {
$args{limit} = 20;
}
if (my $offset = $args->{offset}) {
if ($offset eq 'auto') {
if ( $app && $app->param('offset') ) {
$offset = $app->param('offset') || 0;
}
else {
$offset = 0;
}
}
if ($offset =~ m/^\d+$/) {
$args{offset} = $offset;
}
}
my ($service, $stream) = @$args{qw( service stream )};
if ($service && $stream) {
$terms{class} = join q{_}, $service, $stream;
}
+ elsif ($service && $service =~ s{ \A not \s* }{}xmsi) {
+ $terms{class} = { op => 'not like', value => $service . '_%' };
+ }
elsif ($service) {
- $terms{class} = $service . '_%';
- $args{like} = { class => 1 };
+ $terms{class} = { op => 'like', value => $service . '_%' };
+ }
+ elsif ($stream && $stream =~ s{ \A not \s* }{}xmsi) {
+ $terms{class} = { op => 'not like', value => '%_' . $stream };
}
elsif ($stream) {
- $terms{class} = '%_' . $stream;
- $args{like} = { class => 1 };
+ $terms{class} = { op => 'like', value => '%_' . $stream };
}
# Make sure all classes are loaded.
require ActionStreams::Event;
for my $service (keys %{ MT->instance->registry('action_streams') || {} }) {
ActionStreams::Event->classes_for_type($service);
}
my @events = ActionStreams::Event->search(\%terms, \%args);
my $number_of_events = $ctx->stash('count');
$number_of_events = ActionStreams::Event->count(\%terms, \%args)
unless defined $number_of_events;
return $ctx->_hdlr_pass_tokens_else($args, $cond)
if !@events;
if ($args{sort} eq 'created_on') {
@events = sort { $b->created_on cmp $a->created_on || $b->id <=> $a->id } @events;
@events = reverse @events
if $args{direction} ne 'descend';
}
local $ctx->{__stash}{remaining_stream_actions} = \@events;
my $res = '';
my ($count, $total) = (0, scalar @events);
my $day_date = '';
# For pagination tags
my ( $l, $o, $c );
if ( exists $ctx->{__stash}{limit} ) {
$l = $ctx->{__stash}{limit};
}
elsif ( exists $args{limit} ){
$l = $args{limit};
}
local $ctx->{__stash}{limit} = $l if defined $l;
if ( exists $ctx->{__stash}{offset} ) {
$o = $ctx->{__stash}{offset};
}
elsif ( exists $args{offset} ){
$o = $args{offset};
}
local $ctx->{__stash}{offset} = $o if defined $o;
if ( exists $ctx->{__stash}{count} ) {
$c = $ctx->{__stash}{count};
}
else {
$c = $number_of_events;
}
local $ctx->{__stash}{count} = $c if defined $c;
$ctx->{__stash}{number_of_events} = $number_of_events;
EVENT: while (my $event = shift @events) {
my $new_day_date = _event_day($ctx, $event);
local $cond->{DateHeader} = $day_date ne $new_day_date ? 1 : 0;
local $cond->{DateFooter} = !@events ? 1
: $new_day_date ne _event_day($ctx, $events[0]) ? 1
: 0
;
$day_date = $new_day_date;
$count++;
defined (my $out = _build_about_event(
$ctx, $args, $cond,
event => $event,
count => $count,
total => $total,
)) or return;
$res .= $out;
}
return $res;
}
sub _build_about_event {
my ($ctx, $arg, $cond, %param) = @_;
my ($event, $count, $total) = @param{qw( event count total )};
local $ctx->{__stash}{stream_action} = $event;
my $author = $event->author;
local $ctx->{__stash}{author} = $event->author;
my $type = $event->class_type;
my ($service, $stream_id) = split /_/, $type, 2;
# TODO: find from the event which other_profile is really associated
# instead of guessing it's the first one.
my $profiles = $author->other_profiles($service) || [];
local ($ctx->{__stash}{other_profile}) = @$profiles;
my $vars = $ctx->{__stash}{vars} ||= {};
local $vars->{action_type} = $type;
local $vars->{service_type} = $service;
local $vars->{stream_type} = $stream_id;
local $vars->{__first__} = $count == 1;
local $vars->{__last__} = $count == $total;
local $vars->{__odd__} = ($count % 2) == 1;
local $vars->{__even__} = ($count % 2) == 0;
local $vars->{__counter__} = $count;
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
defined(my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error($builder->errstr);
return $out;
}
sub stream_action_rollup {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionRollup in a non-action-stream context!");
my $nexts = $ctx->stash('remaining_stream_actions');
return $ctx->else($arg, $cond)
if !$nexts || !@$nexts;
my $by_spec = $arg->{by} || 'date,action';
my %by = map { $_ => 1 } split /\s*,\s*/, $by_spec;
my $event_date = _event_day($ctx, $event);
my $event_class = $event->class;
my ($event_service, $event_stream) = split /_/, $event_class, 2;
my @rollup_events = ($event);
EVENT: while (@$nexts) {
my $next = $nexts->[0];
last EVENT if $by{date} && $event_date ne _event_day($ctx, $next);
last EVENT if $by{action} && $event_class ne $next->class;
last EVENT if $by{stream} && $next->class !~ m{ _ \Q$event_stream\E \z }xms;
last EVENT if $by{service} && $next->class !~ m{ \A \Q$event_service\E _ }xms;
# Eligible to roll up! Remove it from the remaining actions.
push @rollup_events, shift @$nexts;
}
return $ctx->else($arg, $cond)
if 1 >= scalar @rollup_events;
my $res;
my $count = 0;
for my $rup_event (@rollup_events) {
$count++;
defined (my $out = _build_about_event(
$ctx, $arg, $cond,
event => $rup_event,
count => $count,
total => scalar @rollup_events,
)) or return;
$res .= $arg->{glue} if $arg->{glue} && $count > 1;
$res .= $out;
}
return $res;
}
sub _event_day {
my ($ctx, $event) = @_;
return substr(epoch2ts($ctx->stash('blog'), ts2epoch(undef, $event->created_on)), 0, 8);
}
sub stream_action_tags {
my ($ctx, $args, $cond) = @_;
require MT::Entry;
my $event = $ctx->stash('stream_action');
return '' unless $event;
my $glue = $args->{glue} || '';
local $ctx->{__stash}{tag_max_count} = undef;
local $ctx->{__stash}{tag_min_count} = undef;
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
my $res = '';
my $tags = $event->get_tag_objects;
for my $tag (@$tags) {
next if $tag->is_private && !$args->{include_private};
local $ctx->{__stash}{Tag} = $tag;
local $ctx->{__stash}{tag_count} = undef;
local $ctx->{__stash}{tag_event_count} = undef; # ?
defined(my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error( $builder->errstr );
$res .= $glue if $res ne '';
$res .= $out;
}
$res;
}
sub other_profiles {
my( $ctx, $args, $cond ) = @_;
my $author_ids = _author_ids_for_args(@_);
my $author_id = shift @$author_ids
or return $ctx->error('No author specified for OtherProfiles');
my $user = MT->model('author')->load($author_id)
or return $ctx->error(MT->translate('No user [_1]', $author_id));
my @profiles = @{ $user->other_profiles() };
my $services = MT->app->registry('profile_services');
if (my $filter_type = $args->{type}) {
my $filter_except = $filter_type =~ s{ \A NOT \s+ }{}xmsi ? 1 : 0;
@profiles = grep {
my $profile = $_;
my $profile_type = $profile->{type};
my $service_type = ($services->{$profile_type} || {})->{service_type} || q{};
$filter_except ? $service_type ne $filter_type : $service_type eq $filter_type;
} @profiles;
}
@profiles = map { $_->[1] }
sort { $a->[0] cmp $b->[0] }
map { [ lc (($services->{ $_->{type} } || {})->{name} || q{}), $_ ] }
@profiles;
my $populate_icon = sub {
my ($item, $row) = @_;
my $type = $item->{type};
$row->{vars}{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $services->{$type});
};
return list(
context => $ctx,
arguments => $args,
conditions => $cond,
items => \@profiles,
stash_key => 'other_profile',
code => $populate_icon,
);
}
sub list {
my %param = @_;
my ($ctx, $args, $cond) = @param{qw( context arguments conditions )};
my ($items, $stash_key, $code) = @param{qw( items stash_key code )};
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
my $res = q{};
my $glue = $args->{glue};
$glue = '' unless defined $glue;
my $vars = ($ctx->{__stash}{vars} ||= {});
my ($count, $total) = (0, scalar @$items);
for my $item (@$items) {
local $ctx->{__stash}->{$stash_key} = $item;
my $row = {};
$code->($item, $row) if $code;
my $lvars = delete $row->{vars} if exists $row->{vars};
local @$vars{keys %$lvars} = values %$lvars
if $lvars;
local @{ $ctx->{__stash} }{keys %$row} = values %$row;
$count++;
my %loop_vars = (
__first__ => $count == 1,
__last__ => $count == $total,
__odd__ => $count % 2,
__even__ => !($count % 2),
__counter__ => $count,
);
local @$vars{keys %loop_vars} = values %loop_vars;
defined (my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error($builder->errstr);
$res .= $glue if ($res ne '') && ($out ne '') && ($glue ne '');
$res .= $out;
}
return $res;
}
sub profile_services {
my( $ctx, $args, $cond ) = @_;
my $app = MT->app;
my $networks = $app->registry('profile_services');
my @network_keys = keys %$networks;
if ( $args->{eligible_to_add} ) {
@network_keys = grep { !$networks->{$_}->{deprecated} } @network_keys;
my $author = $ctx->stash('author');
if ( $author ) {
my $other_profiles = $author->other_profiles();
my %has_unique_profile;
for my $profile ( @$other_profiles ) {
if ( !$networks->{$profile->{type}}->{can_many} ) {
$has_unique_profile{$profile->{type}} = 1;
}
}
@network_keys = grep { !$has_unique_profile{$_} } @network_keys;
}
}
@network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
@network_keys;
my $out = "";
my $builder = $ctx->stash( 'builder' );
my $tokens = $ctx->stash( 'tokens' );
my $vars = ($ctx->{__stash}{vars} ||= {});
if ($args->{extra}) {
# Skip output completely if it's a "core" service but we want
# extras only.
@network_keys = grep { ! $networks->{$_}->{plugin} || ($networks->{$_}->{plugin}->id ne 'actionstreams') } @network_keys;
}
my ($count, $total) = (0, scalar @network_keys);
for my $type (@network_keys) {
$count++;
my %loop_vars = (
__first__ => $count == 1,
__last__ => $count == $total,
__odd__ => $count % 2,
__even__ => !($count % 2),
__counter__ => $count,
);
local @$vars{keys %loop_vars} = values %loop_vars;
my $ndata = $networks->{$type};
local @$vars{ keys %$ndata } = values %$ndata;
local $vars->{ident_hint} =
MT->component('ActionStreams')->translate( $ndata->{ident_hint} )
if $ndata->{ident_hint};
local $vars->{label} = $ndata->{name};
local $vars->{type} = $type;
local $vars->{icon_url} =
ActionStreams::Plugin->icon_url_for_service( $type,
$networks->{$type} );
local $ctx->{__stash}{profile_service} = $ndata;
$out .= $builder->build( $ctx, $tokens, $cond );
}
return $out;
}
1;
|
markpasc/mt-plugin-action-streams
|
1fdb44b999baecc41029461cd019a9d977a5bcb0
|
Fixed bugzid:100284. * Stoped to remove html tags when get value from field.
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm
index 0f27e09..46b430c 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm
@@ -1,582 +1,582 @@
package ActionStreams::Event;
use strict;
use base qw( MT::Object MT::Taggable MT::Scorable );
our @EXPORT_OK = qw( classes_for_type );
use HTTP::Date qw( str2time );
-use MT::Util qw( encode_html remove_html encode_url );
+use MT::Util qw( encode_html encode_url );
use MT::I18N;
use ActionStreams::Scraper;
our $hide_timeless = 0;
__PACKAGE__->install_properties({
column_defs => {
id => 'integer not null auto_increment',
identifier => 'string(200)',
author_id => 'integer not null',
visible => 'integer not null',
},
defaults => {
visible => 1,
},
indexes => {
identifier => 1,
author_id => 1,
created_on => 1,
created_by => 1,
},
class_type => 'event',
audit => 1,
meta => 1,
datasource => 'profileevent',
primary_key => 'id',
});
__PACKAGE__->install_meta({
columns => [ qw(
title
url
thumbnail
via
via_id
) ],
});
# Oracle does not like an identifier of more than 30 characters.
sub datasource {
my $class = shift;
my $r = MT->request;
my $ds = $r->cache('as_event_ds');
return $ds if $ds;
my $dss_oracle = qr/(db[id]::)?oracle/;
if ( my $type = MT->config('ObjectDriver') ) {
if ((lc $type) =~ m/^$dss_oracle$/) {
$ds = 'as';
}
}
$ds = $class->properties->{datasource}
unless $ds;
$r->cache('as_event_ds', $ds);
return $ds;
}
sub encode_field_for_html {
my $event = shift;
my ($field) = @_;
- return encode_html( remove_html( $event->$field() ) );
+ return encode_html( $event->$field() );
}
sub as_html {
my $event = shift;
my %params = @_;
my $stream = $event->registry_entry or return '';
# How many spaces are there in the form?
my $form = $params{form} || $stream->{html_form} || q{};
my @nums = $form =~ m{ \[ _ (\d+) \] }xmsg;
my $max = shift @nums;
for my $num (@nums) {
$max = $num if $max < $num;
}
# Do we need to supply the author name?
my @content = map { $event->encode_field_for_html($_) }
@{ $stream->{html_params} };
if ($max > scalar @content) {
my $name = defined $params{name} ? $params{name}
: $event->author->nickname
;
unshift @content, encode_html($name);
}
return MT->translate($form, @content);
}
sub update_events_loggily {
my $class = shift;
my %profile = @_;
# Keep this option out of band so we don't have to count on
# implementations of update_events() passing it through.
local $hide_timeless = delete $profile{hide_timeless} ? 1 : 0;
my $warn = $SIG{__WARN__} || sub { print STDERR $_[0] };
local $SIG{__WARN__} = sub {
my ($msg) = @_;
$msg =~ s{ \n \z }{}xms;
$msg = MT->component('ActionStreams')->translate(
'[_1] updating [_2] events for [_3]',
$msg, $profile{type}, $profile{author}->name,
);
$warn->("$msg\n");
};
eval {
$class->update_events(%profile);
};
if (my $err = $@) {
my $plugin = MT->component('ActionStreams');
my $err_msg = $plugin->translate("Error updating events for [_1]'s [_2] stream (type [_3] ident [_4]): [_5]",
$profile{author}->name, $class->properties->{class_type},
$profile{type}, $profile{ident}, $err);
MT->log($err_msg);
die $err; # re-throw so we can handle from job invocation
}
}
sub update_events {
my $class = shift;
my %profile = @_;
my $author = delete $profile{author};
my $stream = $class->registry_entry or return;
my $fetch = $stream->{fetch} || {};
local $profile{url} = $stream->{url};
die "Oops, no url?" if !$profile{url};
die "Oops, no ident?" if !$profile{ident};
require MT::I18N;
my $ident = encode_url(MT::I18N::encode_text($profile{ident}, undef, 'utf-8'));
$profile{url} =~ s/ {{ident}} / $ident /xmsge;
my $items;
if (my $xpath_params = $stream->{xpath}) {
$items = $class->fetch_xpath(
%$xpath_params,
%$fetch,
%profile,
);
}
elsif (my $atom_params = $stream->{atom}) {
my $get = {
created_on => 'published',
modified_on => 'updated',
title => 'title',
url => q{link[@rel='alternate']/@href},
via => q{link[@rel='alternate']/@href},
via_id => 'id',
identifier => 'id',
};
$atom_params = {} if !ref $atom_params;
@$get{keys %$atom_params} = values %$atom_params;
$items = $class->fetch_xpath(
foreach => '//entry',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $rss_params = $stream->{rss}) {
my $get = {
title => 'title',
url => 'link',
via => 'link',
created_on => 'pubDate',
thumbnail => 'media:thumbnail/@url',
via_id => 'guid',
identifier => 'guid',
};
$rss_params = {} if !ref $rss_params;
@$get{keys %$rss_params} = values %$rss_params;
$items = $class->fetch_xpath(
foreach => '//item',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $scraper_params = $stream->{scraper}) {
my ($foreach, $get) = @$scraper_params{qw( foreach get )};
my $scraper = scraper {
process $foreach, 'res[]' => scraper {
while (my ($field, $sel) = each %$get) {
process $sel->[0], $field => $sel->[1];
}
};
result 'res';
};
$items = $class->fetch_scraper(
scraper => $scraper,
%$fetch,
%profile,
);
}
return if !$items;
$class->build_results(
items => $items,
stream => $stream,
author => $author,
profile => \%profile,
);
}
sub registry_entry {
my $event = shift;
my ($type, $stream) = split /_/, $event->properties->{class_type}, 2;
my $reg = MT->instance->registry('action_streams') or return;
my $service = $reg->{$type} or return;
$service->{$stream};
}
sub author {
my $event = shift;
my $author_id = $event->author_id
or return;
return MT->instance->model('author')->lookup($author_id);
}
sub blog_id { 0 }
sub classes_for_type {
my $class = shift;
my ($type) = @_;
my $prevts = MT->instance->registry('action_streams');
my $prevt = $prevts->{$type};
return if !$prevt;
my @classes;
PACKAGE: while (my ($stream_id, $stream) = each %$prevt) {
next if 'HASH' ne ref $stream;
next if !$stream->{class} && !$stream->{url};
my $pkg;
if ($pkg = $stream->{class}) {
$pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms;
if (!eval { $pkg->properties }) {
if (!eval "require $pkg; 1") {
my $error = $@ || q{};
my $pl = MT->component('ActionStreams');
MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]',
$pkg, $type, $stream_id, $error));
next PACKAGE;
}
}
}
else {
$pkg = join q{::}, $class, 'Auto', ucfirst $type,
ucfirst $stream_id;
if (!eval { $pkg->properties }) {
eval "package $pkg; use base qw( $class ); 1" or next;
my $class_type = join q{_}, $type, $stream_id;
$pkg->install_properties({ class_type => $class_type });
$pkg->install_meta({ columns => $stream->{fields} })
if $stream->{fields};
}
}
push @classes, $pkg;
}
return @classes;
}
my $ua;
sub ua {
my $class = shift;
my %params = @_;
$ua ||= MT->new_ua({
paranoid => 1,
timeout => 10,
});
$ua->max_size(250_000) if $ua->can('max_size');
$ua->agent($params{default_useragent} ? $ua->_agent
: "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version);
return $ua if $class->class_type eq 'event';
return $ua if $params{unconditional};
require ActionStreams::UserAgent::Adapter;
my $adapter = ActionStreams::UserAgent::Adapter->new(
ua => $ua,
action_type => $class->class_type,
die_on_not_modified => $params{die_on_not_modified} || 0,
);
return $adapter;
}
sub set_values {
my $event = shift;
my ($values) = @_;
for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) {
my $meta_val = delete $values->{$meta_col};
$event->$meta_col($meta_val) if defined $meta_val;
}
$event->SUPER::set_values($values);
}
sub fetch_xpath {
my $class = shift;
my %params = @_;
my $url = $params{url} || '';
if (!$url) {
MT->log(
MT->component('ActionStreams')->translate(
"No URL to fetch for [_1] results", $class));
return;
}
my $ua = $class->ua(%params);
my $res = $ua->get($url);
if (!$res->is_success()) {
MT->log(
MT->component('ActionStreams')->translate(
"Could not fetch [_1]: [_2]", $url, $res->status_line()))
if $res->code != 304;
return;
}
# Do not continue if contents is incomplete.
if (my $abort = $res->{_headers}{'client-aborted'}) {
MT->log(
MT->component('ActionStreams')->translate(
'Aborted fetching [_1]: [_2]', $url, $abort));
return;
}
# Strip leading whitespace, since the parser doesn't like it.
# TODO: confirm we got xml?
my $content = $res->content;
$content =~ s{ \A \s+ }{}xms;
require XML::XPath;
my $x = XML::XPath->new( xml => $content );
my @items;
ITEM: for my $item ($x->findnodes($params{foreach})) {
my %item_data;
VALUE: while (my ($key, $val) = each %{ $params{get} }) {
next VALUE if !$val;
if ($key eq 'tags') {
my @outvals = $item->findnodes($val)
or next VALUE;
$item_data{$key} = [ map { MT::I18N::utf8_off( $_->getNodeValue ) } @outvals ];
}
else {
my $outval = $item->findvalue($val)
or next VALUE;
$outval = MT::I18N::utf8_off("$outval");
if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) {
# try both RFC 822/1123 and ISO 8601 formats
$outval = MT::Util::epoch2ts(undef, str2time($outval))
|| MT::Util::iso2ts(undef, $outval);
}
$item_data{$key} = $outval if $outval;
}
}
push @items, \%item_data;
}
return \@items;
}
sub build_results {
my $class = shift;
my %params = @_;
my ($author, $items, $profile, $stream) =
@params{qw( author items profile stream )};
my $mt = MT->app;
ITEM: for my $item (@$items) {
my $event;
my $identifier = delete $item->{identifier};
if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) {
$identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} };
}
if (defined $identifier) {
$identifier = "$identifier";
($event) = $class->search({
author_id => $author->id,
identifier => $identifier,
});
}
$event ||= $class->new;
$mt->run_callbacks('pre_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
my $tags = delete $item->{tags};
$event->set_values({
author_id => $author->id,
identifier => $identifier,
%$item,
});
$event->tags(@$tags) if $tags;
if ($hide_timeless && !$event->created_on) {
$event->visible(0);
}
$mt->run_callbacks('post_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
$event->save() or MT->log($event->errstr);
}
1;
}
sub save {
my $event = shift;
# Built-in audit field setting will set a local time, so do it ourselves.
if (!$event->created_on) {
my $ts = MT::Util::epoch2ts(undef, time);
$event->created_on($ts);
$event->modified_on($ts);
}
return $event->SUPER::save(@_);
}
sub fetch_scraper {
my $class = shift;
my %params = @_;
my ($url, $scraper) = @params{qw( url scraper )};
$scraper->user_agent( $class->ua( %params, die_on_not_modified => 1 ) );
my $uri_obj = URI->new($url);
my $items = eval { $scraper->scrape($uri_obj) };
# Ignore Web::Scraper errors due to 304 Not Modified responses.
if (!$items && $@ && !UNIVERSAL::isa($@, 'ActionStreams::UserAgent::NotModified')) {
die; # rethrow
}
# we're only being used for our scraper.
return if !$items;
return $items if !ref $items;
return $items if 'ARRAY' ne ref $items;
ITEM: for my $item (@$items) {
next ITEM if !ref $item || ref $item ne 'HASH';
for my $field (keys %$item) {
if ($field eq 'tags') {
$item->{$field} = [ map { MT::I18N::utf8_off( "$_" ) } @{ $item->{$field} } ];
}
else {
$item->{$field} = MT::I18N::utf8_off( q{} . $item->{$field} );
}
}
}
return $items;
}
sub backup_terms_args {
my $class = shift;
my ($blog_ids) = @_;
return { terms => { 'class' => '*' }, args => undef };
}
1;
__END__
=head1 NAME
ActionStreams::Event - an Action Streams stream definition
=head1 SYNOPSIS
# in plugin's config.yaml
profile_services:
example:
streamid:
name: Dice Example
description: A simple die rolling Perl stream example.
html_form: [_1] rolled a [_2]!
html_params:
- title
class: My::Stream
# in plugin's lib/My/Stream.pm
package My::Stream;
use base qw( ActionStreams::Event );
__PACKAGE__->install_properties({
class_type => 'example_streamid',
});
sub update_events {
my $class = shift;
my %profile = @_;
# trivial example: save a random number
my $die_roll = int rand 20;
my %item = (
title => $die_roll,
identifier => $die_roll,
);
return $class->build_results(
author => $profile{author},
items => [ \%item ],
);
}
1;
=head1 DESCRIPTION
I<ActionStreams::Event> provides the basic implementation of an action stream.
Stream definitions are engines for turning web resources into I<actions> (also
called I<events>). This base class produces actions based on generic stream
recipes defined in the MT registry, as well as providing the internal machinery
for you to implement your own streams in Perl code.
=head1 METHODS TO IMPLEMENT
These are the methods one commonly implements (overrides) when implementing a
stream subclass.
=head2 C<$class-E<gt>update_events(%profile)>
Fetches the web resource specified by the profile parameters, collects data
from it into actions, and saves the action records for use later. Required
members of C<%profile> are:
=over 4
=item * C<author>
The C<MT::Author> instance for whom events should be collected.
=item * C<ident>
The author's identifier on the given service.
=back
|
markpasc/mt-plugin-action-streams
|
6bc747e9a91eaeee7ac25bf2e8e9c0a1841548a0
|
removed search services merged from motion. bugzid:100283.
|
diff --git a/mt-static/plugins/ActionStreams/css/action-streams.css b/mt-static/plugins/ActionStreams/css/action-streams.css
index 116081b..9e1e4e5 100644
--- a/mt-static/plugins/ActionStreams/css/action-streams.css
+++ b/mt-static/plugins/ActionStreams/css/action-streams.css
@@ -1,118 +1,113 @@
#header,
#content,
#alpha,
#beta,
#gamma,
#footer {
position: static;
}
.action-stream-header {
margin: 1em 0 .25em;
}
.action-stream-list {
margin-left: 0px;
padding-left: 5px;
list-style-type: none;
}
.action-stream-list li {
margin: 0 0 0.5em;
padding-bottom: 1px;
}
.service-icon {
display: block;
overflow: hidden;
background: transparent url(../images/services/other.png) no-repeat;
padding-left: 20px;
min-height: 18px;
min-width: 16px;
}
.service-website { background-image: url(../images/services/website.png); }
.service-oneup { background-image: url(../images/services/oneup.png); }
.service-backtype { background-image: url(../images/services/backtype.png); }
.service-fortythreethings { background-image: url(../images/services/fortythreethings.png); }
.service-aim { background-image: url(../images/services/aim.png); }
.service-bebo { background-image: url(../images/services/bebo.png); }
.service-catster { background-image: url(../images/services/catster.png); }
.service-colourlovers { background-image: url(../images/services/colourlovers.png); }
.service-corkd { background-image: url(../images/services/corkd.png); }
/*.service-deadjournal { background-image: url(../images/services/deadjournal.png); }*/
.service-delicious { background-image: url(../images/services/delicious.png); }
.service-digg { background-image: url(../images/services/digg.png); }
.service-dodgeball { background-image: url(../images/services/dodgeball.png); }
.service-dogster { background-image: url(../images/services/dogster.png); }
.service-dopplr { background-image: url(../images/services/dopplr.png); }
.service-facebook { background-image: url(../images/services/facebook.png); }
.service-ffffound { background-image: url(../images/services/ffffound.png); }
.service-flickr { background-image: url(../images/services/flickr.png); }
.service-friendfeed { background-image: url(../images/services/friendfeed.png); }
.service-gametap { background-image: url(../images/services/gametap.png); }
-.service-gblogs { background-image: url(../images/services/gblogs.png); }
-.service-gnews { background-image: url(../images/services/gnews.png); }
.service-goodreads { background-image: url(../images/services/goodreads.png); }
.service-googlereader { background-image: url(../images/services/googlereader.png); }
.service-gtalk { background-image: url(../images/services/gtalk.png); }
.service-hi5 { background-image: url(../images/services/hi5.png); }
.service-iconbuffet { background-image: url(../images/services/iconbuffet.png); }
.service-icq { background-image: url(../images/services/icq.png); }
.service-identica { background-image: url(../images/services/identica.png); }
.service-iminta { background-image: url(../images/services/iminta.png); }
.service-istockphoto { background-image: url(../images/services/istockphoto.png); }
.service-iusethis { background-image: url(../images/services/iusethis.png); }
.service-iwatchthis { background-image: url(../images/services/iwatchthis.png); }
.service-jabber { background-image: url(../images/services/jabber.png); }
.service-jaiku { background-image: url(../images/services/jaiku.png); }
.service-kongregate { background-image: url(../images/services/kongregate.png); }
.service-lastfm { background-image: url(../images/services/lastfm.png); }
.service-linkedin { background-image: url(../images/services/linkedin.png); }
/*.service-livedoor { background-image: url(../images/services/livedoor.png); }*/
.service-livejournal { background-image: url(../images/services/livejournal.png); }
.service-magnolia { background-image: url(../images/services/magnolia.png); }
.service-mog { background-image: url(../images/services/mog.png); }
.service-msn { background-image: url(../images/services/msn.png); }
.service-multiply { background-image: url(../images/services/multiply.png); }
.service-myspace { background-image: url(../images/services/myspace.png); }
.service-netflix { background-image: url(../images/services/netflix.png); }
.service-netvibes { background-image: url(../images/services/netvibes.png); }
.service-newsvine { background-image: url(../images/services/newsvine.png); }
.service-ning { background-image: url(../images/services/ning.png); }
.service-ohloh { background-image: url(../images/services/ohloh.png); }
.service-orkut { background-image: url(../images/services/orkut.png); }
.service-pandora { background-image: url(../images/services/pandora.png); }
.service-picasaweb { background-image: url(../images/services/picasaweb.png); }
.service-p0pulist { background-image: url(../images/services/p0pulist.png); }
.service-pownce { background-image: url(../images/services/pownce.png); }
.service-reddit { background-image: url(../images/services/reddit.png); }
.service-skype { background-image: url(../images/services/skype.png); }
.service-slideshare { background-image: url(../images/services/slideshare.png); }
.service-smugmug { background-image: url(../images/services/smugmug.png); }
.service-sonicliving { background-image: url(../images/services/sonicliving.png); }
.service-steam { background-image: url(../images/services/steam.png); }
.service-stumbleupon { background-image: url(../images/services/stumbleupon.png); }
.service-tabblo { background-image: url(../images/services/tabblo.png); }
.service-technorati { background-image: url(../images/services/technorati.png); }
-.service-technoratisearch { background-image: url(../images/services/technorati.png); }
.service-tribe { background-image: url(../images/services/tribe.png); }
.service-twitter { background-image: url(../images/services/twitter.png); }
-.service-twittersearch { background-image: url(../images/services/twitter.png); }
.service-tumblr { background-image: url(../images/services/tumblr.gif); }
.service-typepad { background-image: url(../images/services/typepad.png); }
.service-uncrate { background-image: url(../images/services/uncrate.png); }
.service-upcoming { background-image: url(../images/services/upcoming.png); }
.service-viddler { background-image: url(../images/services/viddler.png); }
.service-vimeo { background-image: url(../images/services/vimeo.png); }
.service-virb { background-image: url(../images/services/virb.png); }
.service-vox { background-image: url(../images/services/vox.png); }
.service-wists { background-image: url(../images/services/wists.png); }
.service-xboxlive { background-image: url(../images/services/xboxlive.png); }
.service-yahoo { background-image: url(../images/services/yahoo.png); }
.service-yelp { background-image: url(../images/services/yelp.png); }
.service-youtube { background-image: url(../images/services/youtube.png); }
.service-zooomr { background-image: url(../images/services/zooomr.png); }
-.service-twittersearch { background-image: url(../images/services/twitter.png); }
diff --git a/mt-static/plugins/ActionStreams/images/services/gblogs.png b/mt-static/plugins/ActionStreams/images/services/gblogs.png
deleted file mode 100644
index 1709d08..0000000
Binary files a/mt-static/plugins/ActionStreams/images/services/gblogs.png and /dev/null differ
diff --git a/mt-static/plugins/ActionStreams/images/services/gnews.png b/mt-static/plugins/ActionStreams/images/services/gnews.png
deleted file mode 100644
index 1709d08..0000000
Binary files a/mt-static/plugins/ActionStreams/images/services/gnews.png and /dev/null differ
diff --git a/plugins/ActionStreams/services.yaml b/plugins/ActionStreams/services.yaml
index 7cc238d..55395f0 100644
--- a/plugins/ActionStreams/services.yaml
+++ b/plugins/ActionStreams/services.yaml
@@ -1,356 +1,331 @@
oneup:
name: 1up.com
url: http://{{ident}}.1up.com/
fortythreethings:
name: 43Things
url: http://www.43things.com/person/{{ident}}/
aim:
name: AIM
url: aim:goim?screenname={{ident}}
ident_label: Screen name
service_type: contact
backtype:
name: backtype
url: http://www.backtype.com/{{ident}}
service_type: comments
bebo:
name: Bebo
url: http://www.bebo.com/Profile.jsp?MemberId={{ident}}
service_type: network
catster:
name: Catster
url: http://www.catster.com/cats/{{ident}}
colourlovers:
name: COLOURlovers
url: http://www.colourlovers.com/lover/{{ident}}
corkd:
name: 'Cork''d'
url: http://www.corkd.com/people/{{ident}}
delicious:
name: Delicious
url: http://delicious.com/{{ident}}/
service_type: links
destructoid:
name: Destructoid
url: http://www.destructoid.com/elephant/profile.phtml?un={{ident}}
digg:
name: Digg
url: http://digg.com/users/{{ident}}/
service_type: links
dodgeball:
name: Dodgeball
url: http://www.dodgeball.com/user?uid={{ident}}
dogster:
name: Dogster
url: http://www.dogster.com/dogs/{{ident}}
dopplr:
name: Dopplr
url: http://www.dopplr.com/traveller/{{ident}}/
facebook:
name: Facebook
url: http://www.facebook.com/profile.php?id={{ident}}
ident_label: User ID
ident_example: 12345
service_type: network
ident_hint: You can find your Facebook userid within your profile URL. For example, http://www.facebook.com/profile.php?id=24400320.
ffffound:
name: FFFFOUND!
url: http://ffffound.com/home/{{ident}}/found/
service_type: photos
flickr:
name: Flickr
url: http://flickr.com/photos/{{ident}}/
ident_example: 36381329@N00
service_type: photos
ident_hint: Enter your Flickr userid which contains "@" in it, e.g. 36381329@N00. Flickr userid is NOT the username in the URL of your photostream.
friendfeed:
name: FriendFeed
url: http://friendfeed.com/{{ident}}
ident_example: JoeUsername
gametap:
name: Gametap
url: http://www.gametap.com/profile/show/profile.do?sn={{ident}}
-gblogs:
- name: Google Blogs
- url: http://blogsearch.google.com/blogsearch?q=%s
-# icon: http://www.google.com/mobile/images/news-24x24.gif
- ident_label: Search term
- can_many: 1
-gnews:
- name: Google News
- url: http://news.google.com/news?q=%s
-# icon: http://www.google.com/mobile/images/news-24x24.gif
- ident_label: Search for
- can_many: 1
goodreads:
name: Goodreads
url: http://www.goodreads.com/user/show/{{ident}}
ident_label: User ID
ident_example: 12345
ident_hint: You can find your Goodreads userid within your profile URL. For example, http://www.goodreads.com/user/show/123456.
googlereader:
name: Google Reader
url: http://www.google.com/reader/shared/{{ident}}
ident_label: Sharing ID
ident_example: http://www.google.com/reader/shared/16793324975410272738
service_type: links
hi5:
name: Hi5
url: http://hi5.com/friend/profile/displayProfile.do?userid={{ident}}
service_type: network
iconbuffet:
name: IconBuffet
url: http://www.iconbuffet.com/people/{{ident}}
icq:
name: ICQ
url: http://www.icq.com/people/about_me.php?uin={{ident}}
ident_label: UIN
ident_example: 12345
service_type: contact
identica:
name: Identi.ca
url: http://identi.ca/{{ident}}
service_type: status
iminta:
name: Iminta
url: http://iminta.com/people/{{ident}}
istockphoto:
name: iStockPhoto
url: http://www.istockphoto.com/user_view.php?id={{ident}}
ident_label: User ID
ident_example: 123456
ident_hint: You can find your istockphoto userid within your profile URL. For example, http://www.istockphoto.com/user_view.php?id=1234567.
iusethis:
name: IUseThis
url: http://osx.iusethis.com/user/{{ident}}
iwatchthis:
name: iwatchthis
url: http://iwatchthis.com/{{ident}}
jabber:
name: Jabber
url: jabber://{{ident}}
ident_label: Jabber ID
ident_example: [email protected]
service_type: contact
jaiku:
name: Jaiku
url: http://{{ident}}.jaiku.com/
ident_suffix: .jaiku.com
service_type: status
kongregate:
name: Kongregate
url: http://www.kongregate.com/accounts/{{ident}}
lastfm:
name: Last.fm
url: http://www.last.fm/user/{{ident}}/
ident_example: JoeUsername
linkedin:
name: LinkedIn
url: http://www.linkedin.com/in/{{ident}}
ident_example: MelodyNelson
ident_prefix: http://www.linkedin.com/in/
ident_label: Profile URL
service_type: network
livejournal:
name: LiveJournal
url: http://{{ident}}.livejournal.com/
ident_suffix: .livejournal.com
service_type: blog
magnolia:
name: Ma.gnolia
url: http://ma.gnolia.com/people/{{ident}}
service_type: links
mog:
name: MOG
url: http://mog.com/{{ident}}
msn:
name: 'MSN Messenger'
url: msnim:chat?contact={{ident}}
service_type: contact
multiply:
name: Multiply
url: http://{{ident}}.multiply.com/
myspace:
name: MySpace
url: http://www.myspace.com/{{ident}}
ident_label: User ID
ident_prefix: http://www.myspace.com/
service_type: network
netflix:
name: Netflix
url: http://rss.netflix.com/QueueRSS?id={{ident}}
ident_label: Netflix RSS ID
ident_example: P0000006746939516625352861892808956
ident_hint: To find your Netflix RSS ID, click "RSS" at the bottom of any page on the Netflix site, then copy and paste in your "Queue" link.
netvibes:
name: Netvibes
url: http://www.netvibes.com/{{ident}}
service_type: links
newsvine:
name: Newsvine
url: http://{{ident}}.newsvine.com/
ning:
name: Ning
url: http://{{ident}}.ning.com/
service_type: network
ident_suffix: .ning.com/
ident_prefix: http://
ident_label: Social Network URL
ohloh:
name: Ohloh
url: http://ohloh.net/accounts/{{ident}}
orkut:
name: Orkut
url: http://www.orkut.com/Profile.aspx?uid={{ident}}
ident_label: User ID
ident_example: 1234567890123456789
service_type: network
ident_hint: You can find your orkut uid within your profile URL. For example, http://www.orkut.com/Main#Profile.aspx?rl=ls&uid=1234567890123456789
pandora:
name: Pandora
url: http://pandora.com/people/{{ident}}
ident_example: JoeUsername
picasaweb:
name: Picasa Web Albums
url: http://picasaweb.google.com/{{ident}}
service_type: photos
p0pulist:
name: p0pulist
url: http://p0pulist.com/list/hot_list/{{ident}}
ident_label: User ID
ident_example: 12345
ident_hint: You can find your p0pulist user id within your Hot List URL. for example, http://p0pulist.com/list/hot_list/10000
pownce:
name: Pownce
url: http://pownce.com/{{ident}}/
service_type: status
deprecated: 1
reddit:
name: Reddit
url: http://reddit.com/user/{{ident}}/
service_type: links
skype:
name: Skype
url: callto://{{ident}}
slideshare:
name: SlideShare
url: http://www.slideshare.net/{{ident}}
smugmug:
name: Smugmug
url: http://{{ident}}.smugmug.com/
service_type: photos
sonicliving:
name: SonicLiving
url: http://www.sonicliving.com/user/{{ident}}/
ident_label: User ID
ident_example: 12345
ident_hint: You can find your SonicLiving userid within your share&subscribe URL. For example, http://sonicliving.com/user/12345/feeds
steam:
name: Steam
url: http://steamcommunity.com/id/{{ident}}
stumbleupon:
name: StumbleUpon
url: http://{{ident}}.stumbleupon.com/
tabblo:
name: Tabblo
url: http://www.tabblo.com/studio/person/{{ident}}/
technorati:
name: Technorati
url: http://technorati.com/people/technorati/{{ident}}
-technoratisearch:
- name: Technorati Search
- url: http://technorati.com/search/{{ident}}
- icon: images/services/technorati.png
- ident_label: Search term
- ident_example: Movable+Type
- ident_hint: Blank should be replaced by positive sign (+).
- can_many: 1
tribe:
name: Tribe
url: http://people.tribe.net/{{ident}}
service_type: network
ident_label: User ID
ident_hint: You can find your tribe userid within your profile URL. For example, http://people.tribe.net/dcdc61ed-696a-40b5-80c1-e9a9809a726a.
tumblr:
name: Tumblr
url: http://{{ident}}.tumblr.com
icon: images/services/tumblr.gif
ident_label: URL
ident_suffix: .tumblr.com
service_type: blog
twitter:
name: Twitter
url: http://twitter.com/{{ident}}
service_type: status
-twittersearch:
- name: TwitterSearch
- url: http://search.twitter.com/search?q={{ident}}
- ident_label: Search term
- can_many: 1
typepad:
name: TypePad
ident_prefix: http://profile.typepad.com/
ident_label: Profile URL
url: http://profile.typepad.com/{{ident}}
uncrate:
name: Uncrate
url: http://uncrate.com/stuff/{{ident}}
upcoming:
name: Upcoming
url: http://upcoming.yahoo.com/user/{{ident}}
ident_label: User ID
ident_example: 12345
viddler:
name: Viddler
url: http://www.viddler.com/explore/{{ident}}
service_type: video
vimeo:
name: Vimeo
url: http://www.vimeo.com/{{ident}}
service_type: video
virb:
name: Virb
url: http://www.virb.com/{{ident}}
service_type: network
ident_label: User ID
ident_hint: You can find your VIRB userid within your home URL. For example, http://www.virb.com/backend/2756504321310091/your_home.
vox:
name: Vox
url: http://{{ident}}.vox.com/
ident_label: Vox name
ident_suffix: .vox.com
service_type: blog
website:
name: Website
url: '{{ident}}'
ident_label: URL
ident_example: http://www.example.com/
ident_exact: 1
can_many: 1
service_type: blog
wists:
name: Wists
url: http://www.wists.com/{{ident}}
xboxlive:
name: 'Xbox Live'
url: http://live.xbox.com/member/{{ident}}
ident_label: Gamertag
yahoo:
name: 'Yahoo! Messenger'
url: http://edit.yahoo.com/config/send_webmesg?.target={{ident}}
service_type: contact
yelp:
name: Yelp
url: http://www.yelp.com/user_details?userid={{ident}}
ident_label: User ID
ident_example: 4BXqlLKW8oP0RBCW1FvaIg
youtube:
name: YouTube
url: http://www.youtube.com/user/{{ident}}
service_type: video
zooomr:
name: Zooomr
url: http://www.zooomr.com/photos/{{ident}}
ident_example: 1234567@Z01
service_type: photos
diff --git a/plugins/ActionStreams/streams.yaml b/plugins/ActionStreams/streams.yaml
index 9e95053..8d86f26 100644
--- a/plugins/ActionStreams/streams.yaml
+++ b/plugins/ActionStreams/streams.yaml
@@ -1,1071 +1,1027 @@
oneup:
playing:
name: Currently Playing
description: The games in your collection you're currently playing
class: OneupPlaying
backtype:
comments:
name: Comments
description: Comments you have made on the web
fields:
- queue
html_form: '[_1] commented on <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.backtype.com/{{ident}}'
rss: 1
identifier: url
colourlovers:
colors:
name: Colors
description: Colors you saved
fields:
- queue
html_form: '[_1] saved the color <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/colors/new?lover={{ident}}'
xpath:
foreach: //color
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
palettes:
name: Palettes
description: Palettes you saved
fields:
- queue
html_form: '[_1] saved the palette <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/palettes/new?lover={{ident}}'
xpath:
foreach: //palette
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
patterns:
name: Patterns
description: Patterns you saved
fields:
- queue
html_form: '[_1] saved the pattern <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.colourlovers.com/api/patterns/new?lover={{ident}}'
xpath:
foreach: //pattern
get:
title: title
url: url
identifier: url
created_on: dateCreated
thumbnail: imageUrl
favpalettes:
name: Favorite Palettes
description: Palettes you saved as favorites
fields:
- queue
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite palette'
html_params:
- url
- title
url: 'http://www.colourlovers.com/rss/lover/{{ident}}/palettes/favorites'
rss: 1
corkd:
reviews:
name: Reviews
description: Your wine reviews
fields:
- review
html_form: '[_1] reviewed <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/journal/{{ident}}'
rss: 1
cellar:
name: Cellar
description: Wines you own
fields:
- wine
html_form: '[_1] owns <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/cellar/{{ident}}'
rss: 1
list:
name: Shopping List
description: Wines you want to buy
fields:
- wine
html_form: '[_1] wants <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.corkd.com/feed/shoppinglist/{{ident}}'
rss: 1
delicious:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.delicious.com/rss/{{ident}}'
identifier: url
xpath:
foreach: //item
get:
created_on: dc:date
title: title
url: link
note: description
digg:
links:
name: Dugg
description: Links you dugg
html_form: '[_1] dugg the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://digg.com/users/{{ident}}/history/diggs.rss'
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
submitted:
name: Submissions
description: Links you submitted
html_form: '[_1] submitted the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://digg.com/users/{{ident}}/history/submissions.rss
identifier: url
fetch:
default_useragent: 1
xpath:
foreach: //item
get:
created_on: pubDate
title: title
url: link
ffffound:
favorites:
name: Found
description: Photos you found
html_form: '[_1] ffffound <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://ffffound.com/home/{{ident}}/found/feed
rss: 1
flickr:
favorites:
name: Favorites
description: Photos you marked as favorites
fields:
- by
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite photo'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_faves.gne?nsid={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
by: author/name
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://api.flickr.com/services/feeds/photos_public.gne?id={{ident}}&lang=en-us&format=atom_10'
atom:
thumbnail: content
friendfeed:
likes:
name: Likes
description: Things from your friends that you "like"
html_form: '[_1] likes <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://friendfeed.com/{{ident}}/likes?format=atom'
atom:
url: link/@href
gametap:
scores:
name: Leaderboard scores
description: Your high scores in games with leaderboards
fields:
- score
html_form: '[_1] scored <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- score
- url
- title
url: http://www.gametap.com/profile/leaderboards.do?sn={{ident}}
identifier: title,score
scraper:
foreach: 'div.buddy-leaderboards div.tr'
get:
url:
- 'div.name a'
- '@href'
title:
- 'div.name strong'
- TEXT
score:
- 'div.name div'
- TEXT
-gblogs:
- posts:
- name: Posts
- description: Blog posts about your search term
- html_form: 'Google Blog Search result: <a href="[_2]">[_3]</a>'
- html_params:
- - url
- - title
- url: 'http://blogsearch.google.com/blogsearch_feeds?q=%22{{ident}}%22&ie=utf-8&num=10&output=atom&scoring=d'
- identifier: url
- atom: 1
-gnews:
- stories:
- name: Stories
- description: News Stories matching your search
- html_form: 'Google News search result: <a href="[_2]">[_3]</a>'
- html_params:
- - url
- - title
- url: 'http://news.google.com/news?num=30&q=%22{{ident}}%22&output=atom'
- identifier: url
- atom: 1
goodreads:
toread:
name: To read
description: Books on your "to-read" shelf
fields:
- by
html_form: '[_1] saved <a href="[_2]"><i>[_3]</i> by [_4]</a> to read'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=to-read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
reading:
name: Reading
description: Books on your "currently-reading" shelf
fields:
- by
html_form: '[_1] started reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=currently-reading'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
read:
name: Read
description: Books on your "read" shelf
fields:
- by
html_form: '[_1] finished reading <a href="[_2]"><i>[_3]</i> by [_4]</a>'
html_params:
- url
- title
- by
url: 'http://www.goodreads.com/review/list_rss/{{ident}}?shelf=read'
identifier: url
xpath:
foreach: //item
get:
title: title
url: link
created_on: pubDate
modified_on: pubDate
by: author_name
googlereader:
links:
name: Shared
description: Your shared items
html_form: '[_1] shared <a href="[_2]">[_3]</a> from <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- source_url
- source_title
class: GoogleReader
iconbuffet:
icons:
name: Deliveries
description: Icon sets you were delivered
html_form: '[_1] received the icon set <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.iconbuffet.com/people/{{ident}};received_packages'
identifier: url
scraper:
foreach: 'div#icons div.preview-sm'
get:
title:
- a span
- TEXT
url:
- a
- '@href'
identica:
statuses:
name: Notices
description: Notices you posted
html_form: '[_1] <a href="[_2]">said</a>, “[_3]”'
html_params:
- url
- title
url: 'http://identi.ca/{{ident}}/rss'
rss:
created_on: dc:date
class: Identica
iminta:
links:
name: Intas
description: Links you saved
html_form: '[_1] is inta <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://iminta.com/people/{{ident}}/rss.xml?inta_source_id=11'
rss: 1
istockphoto:
photos:
name: Photos
description: Photos you posted that were approved
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.istockphoto.com/webservices/feeds/?feedFormat=IStockAtom_1_0&feedName=istockfeed.image.newestUploads&feedParams=UserID={{ident}}'
identifier: url
atom:
thumbnail: content/div/a/img/@src
iusethis:
events:
name: Recent events
description: Events from your recent events feed
html_form: '[_1] <a href="[_2]">[_3]</a>'
html_params:
- url
- title
rss: 1
url: 'http://osx.iusethis.com/user/feed.rss/{{ident}}?following=0'
osxapps:
name: Apps you use
description: The applications you saved as ones you use
fields:
- favorite
html_form: '[_1] started using <a href="[_2]">[_3]</a>[quant,_4, (and loves it),,]'
html_params:
- url
- title
- favorite
url: 'http://osx.iusethis.com/user/{{ident}}'
iwatchthis:
favorites:
name: Favorites
description: Videos you saved as watched
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video'
html_params:
- url
- title
url: 'http://iwatchthis.com/rss/{{ident}}'
rss: 1
jaiku:
jaikus:
name: Jaikus
description: Jaikus you posted
html_form: '[_1] <a href="[_2]">jaiku''d</a>, "[_3]"'
html_params:
- url
- title
url: 'http://{{ident}}.jaiku.com/feed/atom'
atom: 1
kongregate:
favorites:
name: Favorites
description: Games you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite game'
html_params:
- url
- title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url
scraper:
foreach: #favorites dl
get:
url:
- dd a
- '@href'
title:
- dd a
- TEXT
thumbnail:
- dt img
- '@src'
achievements:
name: Achievements
description: Achievements you won
fields:
- game_title
html_form: '[_1] won the <strong>[_2]</strong> in <a href="[_3]">[_4]</a>'
html_params:
- title
- url
- game_title
url: 'http://www.kongregate.com/accounts/{{ident}}'
identifier: url,title
scraper:
foreach: #achievements .badge_details
get:
url:
- dt.badge_img a
- '@href'
thumbnail:
- dt.badge_img img
- '@style'
title:
- dd.badge_name
- TEXT
game_title:
- a.badge_game
- TEXT
lastfm:
tracks:
name: Tracks
description: Songs you recently listened to (High spam potential!)
html_form: '[_1] heard <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/recenttracks.rss'
rss: 1
lovedtracks:
name: Loved Tracks
description: Songs you marked as "loved"
fields:
- artist
html_form: '[_1] loved <a href="[_2]">[_3]</a> by [_4]'
html_params:
- url
- title
- artist
url: 'http://pipes.yahoo.com/pipes/pipe.run?_id=4smlkvMW3RGPpBPfTqoASA&_render=rss&lastFM_UserName={{ident}}'
identifier: url
rss:
artist: description
journalentries:
name: Journal Entries
description: Your recent journal entries
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/journals.rss'
rss: 1
events:
name: Events
description: The events you said you'll be attending
html_form: '[_1] is attending <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ws.audioscrobbler.com/1.0/user/{{ident}}/events.rss'
rss: 1
livejournal:
posts:
name: Posts
description: Your public posts to your journal
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://users.livejournal.com/{{ident}}/data/atom'
atom: 1
magnolia:
links:
name: Links
description: Your public links
fields:
- note
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://ma.gnolia.com/atom/full/people/{{ident}}'
identifier: url
atom:
tags: "category[@scheme='http://ma.gnolia.com/tags']/@term"
note: content
netflix:
queue:
name: Queue
description: Movies you added to your rental queue
fields:
- queue
html_form: '[_1] queued <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/QueueRSS?id={{ident}}'
rss:
thumbnail: description
recent:
name: Recent Movies
description: Recent Rental Activity
fields:
- recent
html_form: '[_1] is watching <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://rss.netflix.com/TrackingRSS?id={{ident}}'
rss:
thumbnail: description
netvibes:
links:
name: Links
description: Links you saved
html_form: '[_1] saved the link <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www2.netvibes.com/rest/account/{{ident}}/timeline?format=atom'
atom: 1
ohloh:
kudos:
name: Kudos
description: Kudos you have received
html_form: '[_1] received kudos from <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.ohloh.net/accounts/{{ident}}/kudos'
identifier: url
scraper:
foreach: 'div.received_kudo'
get:
url:
- a
- '@href'
title:
- a
- TEXT
pandora:
favorites:
name: Favorite Songs
description: Songs you marked as favorites
fields:
- album_art
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite song'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favorites.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
album_art: pandora:albumArtUrl
favoriteartists:
name: Favorite Artists
description: Artists you marked as favorites
fields:
- artist-photo-url
- guid
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite artist'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/favoriteartists.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: link
artist-photo-url: pandora:stationImageUrl
stations:
name: Stations
description: Radio stations you added
fields:
- guid
- station-image-url
html_form: '[_1] added a new radio station named <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://feeds.pandora.com/feeds/people/{{ident}}/stations.xml'
identifier: guid
xpath:
foreach: //item
get:
created_on: pubDate
title: title
guid: guid
url: pandora:stationLink
station-image-url: pandora:stationImageUrl
picasaweb:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://picasaweb.google.com/data/feed/api/user/{{ident}}?kind=photo&max-results=15'
atom:
thumbnail: media:group/media:thumbnail[position()=2]/@url
p0pulist:
stuff:
name: List
description: Things you put in your list
html_form: '[_1] is enjoying <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://p0pulist.com/list/hot_list/{{ident}}.rss'
rss:
thumbnail: image/url
pownce:
statuses:
name: Notes
description: Your public notes
fields:
- note
html_form: '[_1] <a href="[_2]">posted</a>, "[_3]"'
html_params:
- url
- note
url: 'http://pownce.com/feeds/public/{{ident}}/'
atom:
note: summary
reddit:
comments:
name: Comments
description: Comments you posted
html_form: '[_1] commented on <a href="[_2]">[_3]</a> at Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/comments/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
submitted:
name: Submissions
description: Articles you submitted
html_form: '[_1] submitted <a href="[_2]">[_3]</a> to Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/submitted/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
favorites:
name: Likes
description: Articles you liked (your votes must be public)
html_form: '[_1] liked <a href="[_2]">[_3]</a> from Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/liked/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
dislikes:
name: Dislikes
description: Articles you disliked (your votes must be public)
html_form: '[_1] disliked <a href="[_2]">[_3]</a> on Reddit'
html_params:
- url
- title
url: 'http://www.reddit.com/user/{{ident}}/disliked/'
identifier: title
scraper:
foreach: 'a.title'
get:
title:
- a
- TEXT
url:
- a
- '@href'
slideshare:
favorites:
name: Favorites
description: Slideshows you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite slideshow'
html_params:
- url
- title
url: 'http://www.slideshare.net/rss/user/{{ident}}/favorites'
rss:
thumbnail: media:content/media:thumbnail/@url
created_on: ''
slideshows:
name: Slideshows
description: Slideshows you posted
html_form: '[_1] posted the slideshow <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.slideshare.net/rss/user/{{ident}}'
rss:
thumbnail: media:content/media:thumbnail/@url
smugmug:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">a photo</a>'
html_params:
- url
url: 'http://www.smugmug.com/hack/feed.mg?Type=nicknameRecentPhotos&Data={{ident}}&format=atom10&ImageCount=15'
atom:
thumbnail: id
steam:
achievements:
name: Achievements
description: Your achievements for achievement-enabled games
html_form: '[_1] won the <strong>[_2]</strong> achievement in <a href="http://steamcommunity.com/id/[_3]/stats/[_4]?tab=achievements">[_5]</a>'
html_params:
- title
- ident
- gamecode
- game
class: Steam
-technoratisearch:
- posts:
- name: Posts
- description: Blog posts about your search term
- html_form: 'Technorati blog search result: <a href="[_2]">[_3]</a>'
- html_params:
- - url
- - title
- url: http://feeds.technorati.com/search/{{ident}}
- identifier: url
- rss: 1
tumblr:
events:
name: Stuff
description: Things you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://{{ident}}.tumblr.com/rss'
rss: 1
twitter:
statuses:
name: Tweets
description: Your public tweets
class: TwitterTweet
html_form: '[_1] <a href="[_2]">tweeted</a>, "[_3]"'
html_params:
- url
- title
url: 'http://twitter.com/statuses/user_timeline/{{ident}}.atom'
atom: 1
favorites:
name: Favorites
description: Public tweets you saved as favorites
class: TwitterFavorite
fields:
- tweet_author
html_form: '[_1] saved <a href="[_2]">[_3]''s tweet</a>, "[_4]" as a favorite'
html_params:
- url
- tweet_author
- title
url: 'http://twitter.com/favorites/{{ident}}.atom'
atom:
created_on: ''
modified_on: ''
-twittersearch:
- posts:
- name: Tweets
- description: Tweets about your search term
- html_form: 'Twitter Search result: <a href="[_2]">[_3]</a>'
- html_params:
- - url
- - title
- url: 'http://search.twitter.com/search.atom?q={{ident}}'
- identifier: url
- atom: 1
typepad:
comments:
name: Comments
description: Comments you posted
html_form: '[_1] left a comment on <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://profile.typepad.com/{{ident}}/comments/atom.xml'
atom: 1
uncrate:
saved:
name: Saved
description: Things you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> on Uncrate'
html_params:
- url
- title
url: 'http://uncrate.com/stuff/{{ident}}'
identifier: url
scraper:
foreach: '#widget h2'
get:
title:
- a
- TEXT
url:
- a
- '@href'
upcoming:
events:
name: Events
description: Events you are watching or attending
fields:
- venue
html_form: '[_1] is attending <a href="[_2]">[_3]</a> at [_4]'
html_params:
- url
- title
- venue
url: 'http://upcoming.yahoo.com/syndicate/v2/my_events/{{ident}}'
xpath:
foreach: //item
get:
title: xCal:summary
url: link
created_on: dc:date
modified_on: dc:date
venue: 'xCal:x-calconnect-venue/xCal:adr/xCal:x-calconnect-venue-name'
identifier: guid
viddler:
videos:
name: Videos
description: Videos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.viddler.com/explore/{{ident}}/videos/feed/'
rss:
thumbnail: media:content/media:thumbnail/@url
vimeo:
videos:
name: Videos
description: Videos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://vimeo.com/{{ident}}/videos/rss
rss:
thumbnail: media:thumbnail/@url
like:
name: Likes
description: Videos you liked
html_form: '[_1] liked <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: http://vimeo.com/{{ident}}/likes/rss
rss:
thumbnail: media:thumbnail/@url
created_on: ''
modified_on: ''
vox:
favorites:
name: Favorites
description: Public assets you saved as favorites
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite'
html_params:
- url
- title
class: Vox
photos:
name: Photos
description: Your public photos in your Vox library
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://{{ident}}.vox.com/library/photos/rss.xml'
rss:
thumbnail: media:thumbnail/@url
tags: category
posts:
name: Posts
description: Your public posts to your Vox
html_form: '[_1] posted <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://{{ident}}.vox.com/library/posts/atom.xml'
atom:
tags: category/@label
website:
posted:
name: Posts
description: The posts available from the website's feed
html_form: '[_1] posted <a href="[_2]">[_3]</a> on <a href="[_4]">[_5]</a>'
html_params:
- url
- title
- source_url
- source_title
class: Website
wists:
wists:
name: Wists
description: Stuff you saved
html_form: '[_1] wants <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.wists.com/{{ident}}?out=rdf'
identifier: url
rss:
created_on: dc:date
tags: dc:tag
thumbnail: content:encoded
xboxlive:
gamerscore:
name: Gamerscore
description: Notes when your gamerscore passes an even number
html_form: '[_1] passed <strong>[_2]</strong> gamerscore <a href="[_3]">on Xbox Live</a>'
html_params:
- score
- url
class: XboxGamerscore
yelp:
reviews:
name: Reviews
description: Places you reviewed
html_form: '[_1] reviewed <a href="[_2]">[_3]</a>'
html_params:
- url
- title
url: 'http://www.yelp.com/syndicate/user/{{ident}}/atom.xml'
atom:
url: link/@href
youtube:
favorites:
name: Favorites
description: Videos you saved as favorites
fields:
- by
html_form: '[_1] saved <a href="[_2]">[_3]</a> as a favorite video'
html_params:
- url
- title
url: 'http://gdata.youtube.com/feeds/users/{{ident}}/favorites'
atom:
by: author/name
url: "link[@rel='alternate' and @type='text/html']/@href"
thumbnail: "media:group/media:thumbnail[position()=1]/@url"
created_on: ''
modified_on: ''
videos:
name: Videos
description: Videos you posted
html_form: '[_1] posted <a href="[_2]">[_3]</a> to YouTube'
html_params:
- url
- title
url: 'http://gdata.youtube.com/feeds/users/{{ident}}/uploads'
atom:
url: "link[@rel='alternate' and @type='text/html']/@href"
thumbnail: "media:group/media:thumbnail[position()=1]/@url"
zooomr:
photos:
name: Photos
description: Photos you posted
html_form: '[_1] posted <a href="[_2]">a photo</a>'
html_params:
- url
url: 'http://www.zooomr.com/services/feeds/public_photos/?id={{ident}}&format=rss_200'
xpath:
foreach: //item
get:
identifier: link
thumbnail: media:content/@url
|
markpasc/mt-plugin-action-streams
|
cc8e91a1c8b87e1eebd9021891f9f2d65f2d236d
|
Don't next out of a function, and let there be no associated profile (thanks, Jay) BugzID: 91839
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Tags.pm b/plugins/ActionStreams/lib/ActionStreams/Tags.pm
index 9737d9f..7dba44c 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Tags.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Tags.pm
@@ -1,533 +1,532 @@
package ActionStreams::Tags;
use strict;
use MT::Util qw( offset_time_list epoch2ts ts2epoch );
use ActionStreams::Plugin;
sub stream_action {
my ($ctx, $args, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamAction in a non-action-stream context!");
return $event->as_html(
defined $args->{name} ? (name => $args->{name}) : ()
);
}
sub stream_action_id {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionURL in a non-action-stream context!");
return $event->id || '';
}
sub stream_action_var {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionVar in a non-action-stream context!");
my $var = $arg->{var} || $arg->{name}
or return $ctx->error("Used StreamActionVar without a 'name' attribute!");
return $ctx->error("Use StreamActionVar to retrieve invalid variable $var from event of type " . ref $event)
if !$event->can($var) && !$event->has_column($var);
return $event->$var();
}
sub stream_action_date {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionDate in a non-action-stream context!");
my $c_on = $event->created_on;
local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $c_on) )
if $c_on;
return $ctx->_hdlr_date($arg);
}
sub stream_action_modified_date {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionModifiedDate in a non-action-stream context!");
my $m_on = $event->modified_on || $event->created_on;
local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $m_on) )
if $m_on;
return $ctx->_hdlr_date($arg);
}
sub stream_action_title {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionTitle in a non-action-stream context!");
return $event->title || '';
}
sub stream_action_url {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionURL in a non-action-stream context!");
return $event->url || '';
}
sub stream_action_thumbnail_url {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionThumbnailURL in a non-action-stream context!");
return $event->thumbnail || '';
}
sub stream_action_via {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionVia in a non-action-stream context!");
return $event->via || q{};
}
sub other_profile_var {
my( $ctx, $args ) = @_;
my $profile = $ctx->stash( 'other_profile' )
or return $ctx->error( 'No profile defined in ProfileVar' );
my $var = $args->{name} || 'uri';
return defined $profile->{ $var } ? $profile->{ $var } : '';
}
sub _author_ids_for_args {
my ($ctx, $args, $cond) = @_;
my @author_ids;
if (my $ids = $args->{author_ids} || $args->{author_id}) {
@author_ids = split /\s*,\s*/, $ids;
}
elsif (my $disp_names = $args->{display_names} || $args->{display_name}) {
my @names = split /\s*,\s*/, $disp_names;
my @authors = MT->model('author')->load({ nickname => \@names });
@author_ids = map { $_->id } @authors;
}
elsif (my $names = $args->{author} || $args->{authors}) {
# If arg is the special string 'all', then include all authors by returning undef instead of an empty array.
return if $names =~ m{ \A\s* all \s*\z }xmsi;
my @names = split /\s*,\s*/, $names;
my @authors = MT->model('author')->load({ name => \@names });
@author_ids = map { $_->id } @authors;
}
elsif (my $author = $ctx->stash('author')) {
@author_ids = ( $author->id );
}
elsif (my $blog = $ctx->stash('blog')) {
my @authors = MT->model('author')->load({
status => 1, # enabled
}, {
join => MT->model('permission')->join_on('author_id',
{ blog_id => $blog->id }, { unique => 1 }),
});
my $blog_id = $ctx->stash('blog_id');
my $blog = MT->model('blog')->load( $blog_id );
if ( $args->{no_commenter} ) {
@author_ids = map { $_->[0]->id }
grep { $_->[1]->can_administer_blog || $_->[1]->can_create_post }
map { [ $_, $_->permissions($blog->id) ] }
@authors;
}
elsif ( $blog->publish_authd_untrusted_commenters ) {
@author_ids = map { $_->[0]->id }
grep {
$_->[1]->can_administer_blog
|| $_->[1]->can_create_post
|| $_->[1]->has('comment')
|| ( $_->[0]->type == MT::Author::COMMENTER()
&& !$_->[0]->is_banned($blog_id) )
}
map { [ $_, $_->permissions($blog->id) ] }
@authors;
}
else {
@author_ids = map { $_->[0]->id }
grep {
$_->[1]->can_administer_blog
|| $_->[1]->can_create_post
|| $_->[1]->has('comment')
}
map { [ $_, $_->permissions($blog->id) ] }
@authors;
}
}
return \@author_ids;
}
sub action_streams {
my ($ctx, $args, $cond) = @_;
my %terms = (
class => '*',
visible => 1,
);
my $author_id = _author_ids_for_args(@_);
$terms{author_id} = $author_id if defined $author_id;
my %args = (
sort => ($args->{sort_by} || 'created_on'),
direction => ($args->{direction} || 'descend'),
);
my $app = MT->app;
undef $app unless $app->isa('MT::App');
if (my $limit = $args->{limit} || $args->{lastn}) {
$args{limit} = $limit eq 'auto' ? ( $app ? $app->param('limit') : 20 ) : $limit;
$args{limit} = 20 unless $args{limit};
}
elsif (my $days = $args->{days}) {
my @ago = offset_time_list(time - 3600 * 24 * $days,
$ctx->stash('blog'));
my $ago = sprintf "%04d%02d%02d%02d%02d%02d",
$ago[5]+1900, $ago[4]+1, @ago[3,2,1,0];
$terms{created_on} = [ $ago ];
$args{range_incl}{created_on} = 1;
}
else {
$args{limit} = 20;
}
if (my $offset = $args->{offset}) {
if ($offset eq 'auto') {
if ( $app && $app->param('offset') ) {
$offset = $app->param('offset') || 0;
}
else {
$offset = 0;
}
}
if ($offset =~ m/^\d+$/) {
$args{offset} = $offset;
}
}
my ($service, $stream) = @$args{qw( service stream )};
if ($service && $stream) {
$terms{class} = join q{_}, $service, $stream;
}
elsif ($service) {
$terms{class} = $service . '_%';
$args{like} = { class => 1 };
}
elsif ($stream) {
$terms{class} = '%_' . $stream;
$args{like} = { class => 1 };
}
# Make sure all classes are loaded.
require ActionStreams::Event;
for my $service (keys %{ MT->instance->registry('action_streams') || {} }) {
ActionStreams::Event->classes_for_type($service);
}
my @events = ActionStreams::Event->search(\%terms, \%args);
my $number_of_events = $ctx->stash('count');
$number_of_events = ActionStreams::Event->count(\%terms, \%args)
unless defined $number_of_events;
return $ctx->_hdlr_pass_tokens_else($args, $cond)
if !@events;
if ($args{sort} eq 'created_on') {
@events = sort { $b->created_on cmp $a->created_on || $b->id <=> $a->id } @events;
@events = reverse @events
if $args{direction} ne 'descend';
}
local $ctx->{__stash}{remaining_stream_actions} = \@events;
my $res = '';
my ($count, $total) = (0, scalar @events);
my $day_date = '';
# For pagination tags
local $ctx->{__stash}{limit} = $args{limit}
if exists($args{limit}) && !exists($ctx->{__stash}{limit});
local $ctx->{__stash}{offset} = $args{offset}
if exists($args{offset}) && !exists($ctx->{__stash}{offset});
local $ctx->{__stash}{count} = $number_of_events
unless exists $ctx->{__stash}{count};
$ctx->{__stash}{number_of_events} = $number_of_events;
EVENT: while (my $event = shift @events) {
my $new_day_date = _event_day($ctx, $event);
local $cond->{DateHeader} = $day_date ne $new_day_date ? 1 : 0;
local $cond->{DateFooter} = !@events ? 1
: $new_day_date ne _event_day($ctx, $events[0]) ? 1
: 0
;
$day_date = $new_day_date;
$count++;
defined (my $out = _build_about_event(
$ctx, $args, $cond,
event => $event,
count => $count,
total => $total,
)) or return;
$res .= $out;
}
return $res;
}
sub _build_about_event {
my ($ctx, $arg, $cond, %param) = @_;
my ($event, $count, $total) = @param{qw( event count total )};
local $ctx->{__stash}{stream_action} = $event;
my $author = $event->author;
local $ctx->{__stash}{author} = $event->author;
my $type = $event->class_type;
my ($service, $stream_id) = split /_/, $type, 2;
# TODO: find from the event which other_profile is really associated
# instead of guessing it's the first one.
- my $profiles = $author->other_profiles($service);
- next EVENT if !$profiles || !@$profiles;
+ my $profiles = $author->other_profiles($service) || [];
local ($ctx->{__stash}{other_profile}) = @$profiles;
my $vars = $ctx->{__stash}{vars} ||= {};
local $vars->{action_type} = $type;
local $vars->{service_type} = $service;
local $vars->{stream_type} = $stream_id;
local $vars->{__first__} = $count == 1;
local $vars->{__last__} = $count == $total;
local $vars->{__odd__} = ($count % 2) == 1;
local $vars->{__even__} = ($count % 2) == 0;
local $vars->{__counter__} = $count;
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
defined(my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error($builder->errstr);
return $out;
}
sub stream_action_rollup {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionRollup in a non-action-stream context!");
my $nexts = $ctx->stash('remaining_stream_actions');
return $ctx->else($arg, $cond)
if !$nexts || !@$nexts;
my $by_spec = $arg->{by} || 'date,action';
my %by = map { $_ => 1 } split /\s*,\s*/, $by_spec;
my $event_date = _event_day($ctx, $event);
my $event_class = $event->class;
my ($event_service, $event_stream) = split /_/, $event_class, 2;
my @rollup_events = ($event);
EVENT: while (@$nexts) {
my $next = $nexts->[0];
last EVENT if $by{date} && $event_date ne _event_day($ctx, $next);
last EVENT if $by{action} && $event_class ne $next->class;
last EVENT if $by{stream} && $next->class !~ m{ _ \Q$event_stream\E \z }xms;
last EVENT if $by{service} && $next->class !~ m{ \A \Q$event_service\E _ }xms;
# Eligible to roll up! Remove it from the remaining actions.
push @rollup_events, shift @$nexts;
}
return $ctx->else($arg, $cond)
if 1 >= scalar @rollup_events;
my $res;
my $count = 0;
for my $rup_event (@rollup_events) {
$count++;
defined (my $out = _build_about_event(
$ctx, $arg, $cond,
event => $rup_event,
count => $count,
total => scalar @rollup_events,
)) or return;
$res .= $arg->{glue} if $arg->{glue} && $count > 1;
$res .= $out;
}
return $res;
}
sub _event_day {
my ($ctx, $event) = @_;
return substr(epoch2ts($ctx->stash('blog'), ts2epoch(undef, $event->created_on)), 0, 8);
}
sub stream_action_tags {
my ($ctx, $args, $cond) = @_;
require MT::Entry;
my $event = $ctx->stash('stream_action');
return '' unless $event;
my $glue = $args->{glue} || '';
local $ctx->{__stash}{tag_max_count} = undef;
local $ctx->{__stash}{tag_min_count} = undef;
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
my $res = '';
my $tags = $event->get_tag_objects;
for my $tag (@$tags) {
next if $tag->is_private && !$args->{include_private};
local $ctx->{__stash}{Tag} = $tag;
local $ctx->{__stash}{tag_count} = undef;
local $ctx->{__stash}{tag_event_count} = undef; # ?
defined(my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error( $builder->errstr );
$res .= $glue if $res ne '';
$res .= $out;
}
$res;
}
sub other_profiles {
my( $ctx, $args, $cond ) = @_;
my $author_ids = _author_ids_for_args(@_);
my $author_id = shift @$author_ids
or return $ctx->error('No author specified for OtherProfiles');
my $user = MT->model('author')->load($author_id)
or return $ctx->error(MT->translate('No user [_1]', $author_id));
my @profiles = @{ $user->other_profiles() };
my $services = MT->app->registry('profile_services');
if (my $filter_type = $args->{type}) {
my $filter_except = $filter_type =~ s{ \A NOT \s+ }{}xmsi ? 1 : 0;
@profiles = grep {
my $profile = $_;
my $profile_type = $profile->{type};
my $service_type = ($services->{$profile_type} || {})->{service_type} || q{};
$filter_except ? $service_type ne $filter_type : $service_type eq $filter_type;
} @profiles;
}
@profiles = map { $_->[1] }
sort { $a->[0] cmp $b->[0] }
map { [ lc (($services->{ $_->{type} } || {})->{name} || q{}), $_ ] }
@profiles;
my $populate_icon = sub {
my ($item, $row) = @_;
my $type = $item->{type};
$row->{vars}{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $services->{$type});
};
return list(
context => $ctx,
arguments => $args,
conditions => $cond,
items => \@profiles,
stash_key => 'other_profile',
code => $populate_icon,
);
}
sub list {
my %param = @_;
my ($ctx, $args, $cond) = @param{qw( context arguments conditions )};
my ($items, $stash_key, $code) = @param{qw( items stash_key code )};
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
my $res = q{};
my $glue = $args->{glue};
$glue = '' unless defined $glue;
my $vars = ($ctx->{__stash}{vars} ||= {});
my ($count, $total) = (0, scalar @$items);
for my $item (@$items) {
local $ctx->{__stash}->{$stash_key} = $item;
my $row = {};
$code->($item, $row) if $code;
my $lvars = delete $row->{vars} if exists $row->{vars};
local @$vars{keys %$lvars} = values %$lvars
if $lvars;
local @{ $ctx->{__stash} }{keys %$row} = values %$row;
$count++;
my %loop_vars = (
__first__ => $count == 1,
__last__ => $count == $total,
__odd__ => $count % 2,
__even__ => !($count % 2),
__counter__ => $count,
);
local @$vars{keys %loop_vars} = values %loop_vars;
defined (my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error($builder->errstr);
$res .= $glue if ($res ne '') && ($out ne '') && ($glue ne '');
$res .= $out;
}
return $res;
}
sub profile_services {
my( $ctx, $args, $cond ) = @_;
my $app = MT->app;
my $networks = $app->registry('profile_services');
my @network_keys = keys %$networks;
if ( $args->{eligible_to_add} ) {
@network_keys = grep { !$networks->{$_}->{deprecated} } @network_keys;
my $author = $ctx->stash('author');
if ( $author ) {
my $other_profiles = $author->other_profiles();
my %has_unique_profile;
for my $profile ( @$other_profiles ) {
if ( !$networks->{$profile->{type}}->{can_many} ) {
$has_unique_profile{$profile->{type}} = 1;
}
}
@network_keys = grep { !$has_unique_profile{$_} } @network_keys;
}
}
@network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
@network_keys;
my $out = "";
my $builder = $ctx->stash( 'builder' );
my $tokens = $ctx->stash( 'tokens' );
my $vars = ($ctx->{__stash}{vars} ||= {});
if ($args->{extra}) {
# Skip output completely if it's a "core" service but we want
# extras only.
@network_keys = grep { ! $networks->{$_}->{plugin} || ($networks->{$_}->{plugin}->id ne 'actionstreams') } @network_keys;
}
my ($count, $total) = (0, scalar @network_keys);
for my $type (@network_keys) {
$count++;
my %loop_vars = (
__first__ => $count == 1,
__last__ => $count == $total,
__odd__ => $count % 2,
__even__ => !($count % 2),
__counter__ => $count,
);
local @$vars{keys %loop_vars} = values %loop_vars;
my $ndata = $networks->{$type};
local @$vars{ keys %$ndata } = values %$ndata;
local $vars->{ident_hint} =
MT->component('ActionStreams')->translate( $ndata->{ident_hint} )
if $ndata->{ident_hint};
local $vars->{label} = $ndata->{name};
local $vars->{type} = $type;
local $vars->{icon_url} =
ActionStreams::Plugin->icon_url_for_service( $type,
$networks->{$type} );
local $ctx->{__stash}{profile_service} = $ndata;
$out .= $builder->build( $ctx, $tokens, $cond );
}
return $out;
}
1;
|
markpasc/mt-plugin-action-streams
|
60fe1d91cefa17cee5dbee0760788afdb5092c4e
|
fixed typo.
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Tags.pm b/plugins/ActionStreams/lib/ActionStreams/Tags.pm
index 8e48589..9737d9f 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Tags.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Tags.pm
@@ -1,533 +1,533 @@
package ActionStreams::Tags;
use strict;
use MT::Util qw( offset_time_list epoch2ts ts2epoch );
use ActionStreams::Plugin;
sub stream_action {
my ($ctx, $args, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamAction in a non-action-stream context!");
return $event->as_html(
defined $args->{name} ? (name => $args->{name}) : ()
);
}
sub stream_action_id {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionURL in a non-action-stream context!");
return $event->id || '';
}
sub stream_action_var {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionVar in a non-action-stream context!");
my $var = $arg->{var} || $arg->{name}
or return $ctx->error("Used StreamActionVar without a 'name' attribute!");
return $ctx->error("Use StreamActionVar to retrieve invalid variable $var from event of type " . ref $event)
if !$event->can($var) && !$event->has_column($var);
return $event->$var();
}
sub stream_action_date {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionDate in a non-action-stream context!");
my $c_on = $event->created_on;
local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $c_on) )
if $c_on;
return $ctx->_hdlr_date($arg);
}
sub stream_action_modified_date {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionModifiedDate in a non-action-stream context!");
my $m_on = $event->modified_on || $event->created_on;
local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $m_on) )
if $m_on;
return $ctx->_hdlr_date($arg);
}
sub stream_action_title {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionTitle in a non-action-stream context!");
return $event->title || '';
}
sub stream_action_url {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionURL in a non-action-stream context!");
return $event->url || '';
}
sub stream_action_thumbnail_url {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionThumbnailURL in a non-action-stream context!");
return $event->thumbnail || '';
}
sub stream_action_via {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionVia in a non-action-stream context!");
return $event->via || q{};
}
sub other_profile_var {
my( $ctx, $args ) = @_;
my $profile = $ctx->stash( 'other_profile' )
or return $ctx->error( 'No profile defined in ProfileVar' );
my $var = $args->{name} || 'uri';
return defined $profile->{ $var } ? $profile->{ $var } : '';
}
sub _author_ids_for_args {
my ($ctx, $args, $cond) = @_;
my @author_ids;
if (my $ids = $args->{author_ids} || $args->{author_id}) {
@author_ids = split /\s*,\s*/, $ids;
}
elsif (my $disp_names = $args->{display_names} || $args->{display_name}) {
my @names = split /\s*,\s*/, $disp_names;
my @authors = MT->model('author')->load({ nickname => \@names });
@author_ids = map { $_->id } @authors;
}
elsif (my $names = $args->{author} || $args->{authors}) {
# If arg is the special string 'all', then include all authors by returning undef instead of an empty array.
return if $names =~ m{ \A\s* all \s*\z }xmsi;
my @names = split /\s*,\s*/, $names;
my @authors = MT->model('author')->load({ name => \@names });
@author_ids = map { $_->id } @authors;
}
elsif (my $author = $ctx->stash('author')) {
@author_ids = ( $author->id );
}
elsif (my $blog = $ctx->stash('blog')) {
my @authors = MT->model('author')->load({
status => 1, # enabled
}, {
join => MT->model('permission')->join_on('author_id',
{ blog_id => $blog->id }, { unique => 1 }),
});
my $blog_id = $ctx->stash('blog_id');
my $blog = MT->model('blog')->load( $blog_id );
if ( $args->{no_commenter} ) {
@author_ids = map { $_->[0]->id }
grep { $_->[1]->can_administer_blog || $_->[1]->can_create_post }
map { [ $_, $_->permissions($blog->id) ] }
@authors;
}
elsif ( $blog->publish_authd_untrusted_commenters ) {
@author_ids = map { $_->[0]->id }
grep {
$_->[1]->can_administer_blog
|| $_->[1]->can_create_post
|| $_->[1]->has('comment')
|| ( $_->[0]->type == MT::Author::COMMENTER()
&& !$_->[0]->is_banned($blog_id) )
}
map { [ $_, $_->permissions($blog->id) ] }
@authors;
}
else {
@author_ids = map { $_->[0]->id }
grep {
$_->[1]->can_administer_blog
|| $_->[1]->can_create_post
|| $_->[1]->has('comment')
}
map { [ $_, $_->permissions($blog->id) ] }
@authors;
}
}
return \@author_ids;
}
sub action_streams {
my ($ctx, $args, $cond) = @_;
my %terms = (
class => '*',
visible => 1,
);
my $author_id = _author_ids_for_args(@_);
$terms{author_id} = $author_id if defined $author_id;
my %args = (
sort => ($args->{sort_by} || 'created_on'),
direction => ($args->{direction} || 'descend'),
);
my $app = MT->app;
undef $app unless $app->isa('MT::App');
if (my $limit = $args->{limit} || $args->{lastn}) {
$args{limit} = $limit eq 'auto' ? ( $app ? $app->param('limit') : 20 ) : $limit;
$args{limit} = 20 unless $args{limit};
}
elsif (my $days = $args->{days}) {
my @ago = offset_time_list(time - 3600 * 24 * $days,
$ctx->stash('blog'));
my $ago = sprintf "%04d%02d%02d%02d%02d%02d",
$ago[5]+1900, $ago[4]+1, @ago[3,2,1,0];
$terms{created_on} = [ $ago ];
$args{range_incl}{created_on} = 1;
}
else {
$args{limit} = 20;
}
if (my $offset = $args->{offset}) {
if ($offset eq 'auto') {
if ( $app && $app->param('offset') ) {
$offset = $app->param('offset') || 0;
}
else {
$offset = 0;
}
}
if ($offset =~ m/^\d+$/) {
$args{offset} = $offset;
}
}
my ($service, $stream) = @$args{qw( service stream )};
if ($service && $stream) {
$terms{class} = join q{_}, $service, $stream;
}
elsif ($service) {
$terms{class} = $service . '_%';
$args{like} = { class => 1 };
}
elsif ($stream) {
$terms{class} = '%_' . $stream;
$args{like} = { class => 1 };
}
# Make sure all classes are loaded.
require ActionStreams::Event;
for my $service (keys %{ MT->instance->registry('action_streams') || {} }) {
ActionStreams::Event->classes_for_type($service);
}
my @events = ActionStreams::Event->search(\%terms, \%args);
my $number_of_events = $ctx->stash('count');
$number_of_events = ActionStreams::Event->count(\%terms, \%args)
unless defined $number_of_events;
return $ctx->_hdlr_pass_tokens_else($args, $cond)
if !@events;
if ($args{sort} eq 'created_on') {
@events = sort { $b->created_on cmp $a->created_on || $b->id <=> $a->id } @events;
@events = reverse @events
if $args{direction} ne 'descend';
}
local $ctx->{__stash}{remaining_stream_actions} = \@events;
my $res = '';
my ($count, $total) = (0, scalar @events);
my $day_date = '';
# For pagination tags
local $ctx->{__stash}{limit} = $args{limit}
if exists($args{limit}) && !exists($ctx->{__stash}{limit});
local $ctx->{__stash}{offset} = $args{offset}
if exists($args{offset}) && !exists($ctx->{__stash}{offset});
local $ctx->{__stash}{count} = $number_of_events
unless exists $ctx->{__stash}{count};
$ctx->{__stash}{number_of_events} = $number_of_events;
EVENT: while (my $event = shift @events) {
my $new_day_date = _event_day($ctx, $event);
local $cond->{DateHeader} = $day_date ne $new_day_date ? 1 : 0;
local $cond->{DateFooter} = !@events ? 1
: $new_day_date ne _event_day($ctx, $events[0]) ? 1
: 0
;
$day_date = $new_day_date;
$count++;
defined (my $out = _build_about_event(
$ctx, $args, $cond,
event => $event,
count => $count,
total => $total,
)) or return;
$res .= $out;
}
return $res;
}
sub _build_about_event {
my ($ctx, $arg, $cond, %param) = @_;
my ($event, $count, $total) = @param{qw( event count total )};
local $ctx->{__stash}{stream_action} = $event;
my $author = $event->author;
local $ctx->{__stash}{author} = $event->author;
my $type = $event->class_type;
my ($service, $stream_id) = split /_/, $type, 2;
# TODO: find from the event which other_profile is really associated
# instead of guessing it's the first one.
my $profiles = $author->other_profiles($service);
next EVENT if !$profiles || !@$profiles;
local ($ctx->{__stash}{other_profile}) = @$profiles;
my $vars = $ctx->{__stash}{vars} ||= {};
local $vars->{action_type} = $type;
local $vars->{service_type} = $service;
local $vars->{stream_type} = $stream_id;
local $vars->{__first__} = $count == 1;
local $vars->{__last__} = $count == $total;
local $vars->{__odd__} = ($count % 2) == 1;
local $vars->{__even__} = ($count % 2) == 0;
local $vars->{__counter__} = $count;
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
defined(my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error($builder->errstr);
return $out;
}
sub stream_action_rollup {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionRollup in a non-action-stream context!");
my $nexts = $ctx->stash('remaining_stream_actions');
return $ctx->else($arg, $cond)
if !$nexts || !@$nexts;
my $by_spec = $arg->{by} || 'date,action';
my %by = map { $_ => 1 } split /\s*,\s*/, $by_spec;
my $event_date = _event_day($ctx, $event);
my $event_class = $event->class;
my ($event_service, $event_stream) = split /_/, $event_class, 2;
my @rollup_events = ($event);
EVENT: while (@$nexts) {
my $next = $nexts->[0];
last EVENT if $by{date} && $event_date ne _event_day($ctx, $next);
last EVENT if $by{action} && $event_class ne $next->class;
last EVENT if $by{stream} && $next->class !~ m{ _ \Q$event_stream\E \z }xms;
last EVENT if $by{service} && $next->class !~ m{ \A \Q$event_service\E _ }xms;
# Eligible to roll up! Remove it from the remaining actions.
push @rollup_events, shift @$nexts;
}
return $ctx->else($arg, $cond)
if 1 >= scalar @rollup_events;
my $res;
my $count = 0;
for my $rup_event (@rollup_events) {
$count++;
defined (my $out = _build_about_event(
$ctx, $arg, $cond,
event => $rup_event,
count => $count,
total => scalar @rollup_events,
)) or return;
$res .= $arg->{glue} if $arg->{glue} && $count > 1;
$res .= $out;
}
return $res;
}
sub _event_day {
my ($ctx, $event) = @_;
return substr(epoch2ts($ctx->stash('blog'), ts2epoch(undef, $event->created_on)), 0, 8);
}
sub stream_action_tags {
my ($ctx, $args, $cond) = @_;
require MT::Entry;
my $event = $ctx->stash('stream_action');
return '' unless $event;
my $glue = $args->{glue} || '';
local $ctx->{__stash}{tag_max_count} = undef;
local $ctx->{__stash}{tag_min_count} = undef;
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
my $res = '';
my $tags = $event->get_tag_objects;
for my $tag (@$tags) {
next if $tag->is_private && !$args->{include_private};
local $ctx->{__stash}{Tag} = $tag;
local $ctx->{__stash}{tag_count} = undef;
local $ctx->{__stash}{tag_event_count} = undef; # ?
defined(my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error( $builder->errstr );
$res .= $glue if $res ne '';
$res .= $out;
}
$res;
}
sub other_profiles {
my( $ctx, $args, $cond ) = @_;
my $author_ids = _author_ids_for_args(@_);
my $author_id = shift @$author_ids
or return $ctx->error('No author specified for OtherProfiles');
my $user = MT->model('author')->load($author_id)
or return $ctx->error(MT->translate('No user [_1]', $author_id));
my @profiles = @{ $user->other_profiles() };
my $services = MT->app->registry('profile_services');
if (my $filter_type = $args->{type}) {
my $filter_except = $filter_type =~ s{ \A NOT \s+ }{}xmsi ? 1 : 0;
@profiles = grep {
my $profile = $_;
my $profile_type = $profile->{type};
my $service_type = ($services->{$profile_type} || {})->{service_type} || q{};
$filter_except ? $service_type ne $filter_type : $service_type eq $filter_type;
} @profiles;
}
@profiles = map { $_->[1] }
sort { $a->[0] cmp $b->[0] }
map { [ lc (($services->{ $_->{type} } || {})->{name} || q{}), $_ ] }
@profiles;
my $populate_icon = sub {
my ($item, $row) = @_;
my $type = $item->{type};
$row->{vars}{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $services->{$type});
};
return list(
context => $ctx,
arguments => $args,
conditions => $cond,
items => \@profiles,
stash_key => 'other_profile',
code => $populate_icon,
);
}
sub list {
my %param = @_;
my ($ctx, $args, $cond) = @param{qw( context arguments conditions )};
my ($items, $stash_key, $code) = @param{qw( items stash_key code )};
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
my $res = q{};
my $glue = $args->{glue};
$glue = '' unless defined $glue;
my $vars = ($ctx->{__stash}{vars} ||= {});
my ($count, $total) = (0, scalar @$items);
for my $item (@$items) {
local $ctx->{__stash}->{$stash_key} = $item;
my $row = {};
$code->($item, $row) if $code;
my $lvars = delete $row->{vars} if exists $row->{vars};
local @$vars{keys %$lvars} = values %$lvars
if $lvars;
local @{ $ctx->{__stash} }{keys %$row} = values %$row;
$count++;
my %loop_vars = (
__first__ => $count == 1,
__last__ => $count == $total,
__odd__ => $count % 2,
__even__ => !($count % 2),
__counter__ => $count,
);
local @$vars{keys %loop_vars} = values %loop_vars;
defined (my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error($builder->errstr);
$res .= $glue if ($res ne '') && ($out ne '') && ($glue ne '');
$res .= $out;
}
return $res;
}
sub profile_services {
my( $ctx, $args, $cond ) = @_;
my $app = MT->app;
my $networks = $app->registry('profile_services');
my @network_keys = keys %$networks;
- if ( $args->{eligble_to_add} ) {
+ if ( $args->{eligible_to_add} ) {
@network_keys = grep { !$networks->{$_}->{deprecated} } @network_keys;
my $author = $ctx->stash('author');
if ( $author ) {
my $other_profiles = $author->other_profiles();
my %has_unique_profile;
for my $profile ( @$other_profiles ) {
if ( !$networks->{$profile->{type}}->{can_many} ) {
$has_unique_profile{$profile->{type}} = 1;
}
}
@network_keys = grep { !$has_unique_profile{$_} } @network_keys;
}
}
@network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
@network_keys;
my $out = "";
my $builder = $ctx->stash( 'builder' );
my $tokens = $ctx->stash( 'tokens' );
my $vars = ($ctx->{__stash}{vars} ||= {});
if ($args->{extra}) {
# Skip output completely if it's a "core" service but we want
# extras only.
@network_keys = grep { ! $networks->{$_}->{plugin} || ($networks->{$_}->{plugin}->id ne 'actionstreams') } @network_keys;
}
my ($count, $total) = (0, scalar @network_keys);
for my $type (@network_keys) {
$count++;
my %loop_vars = (
__first__ => $count == 1,
__last__ => $count == $total,
__odd__ => $count % 2,
__even__ => !($count % 2),
__counter__ => $count,
);
local @$vars{keys %loop_vars} = values %loop_vars;
my $ndata = $networks->{$type};
local @$vars{ keys %$ndata } = values %$ndata;
local $vars->{ident_hint} =
MT->component('ActionStreams')->translate( $ndata->{ident_hint} )
if $ndata->{ident_hint};
local $vars->{label} = $ndata->{name};
local $vars->{type} = $type;
local $vars->{icon_url} =
ActionStreams::Plugin->icon_url_for_service( $type,
$networks->{$type} );
local $ctx->{__stash}{profile_service} = $ndata;
$out .= $builder->build( $ctx, $tokens, $cond );
}
return $out;
}
1;
|
markpasc/mt-plugin-action-streams
|
c506cfe4b7b62a02a1821f807ec482fcb437307c
|
Removed "no_deplecated" option from _build_service_data because it's backward logical. bugzid:100250. * not show deplecated services if no option. * to show deplecated services, use "include_deplecated" option.
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
index 57df8e1..d3c396d 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
@@ -1,775 +1,774 @@
package ActionStreams::Plugin;
use strict;
use warnings;
use Carp qw( croak );
use MT::Util qw( relative_date offset_time epoch2ts ts2epoch format_ts );
sub users_content_nav {
my ($cb, $app, $param, $tmpl) = @_;
my $author_id = $app->param('id') or return;
my $author = MT->model('author')->load( $author_id )
or return $cb->error('failed to load author');
$param->{edit_author} = 1 if $author->type == MT::Author::AUTHOR();
my $menu_str = <<"EOF";
<__trans_section component="actionstreams"><mt:if var="USER_VIEW">
<li><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">"><b><__trans phrase="Other Profiles"></b></a></li>
<li><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">"><b><__trans phrase="Action Stream"></b></a></li>
<mt:else>
<li<mt:if name="other_profiles"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="id" escape="url">"><b><__trans phrase="Other Profiles"></b></a></li>
<li<mt:if name="list_profileevent"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="id" escape="url">"><b><__trans phrase="Action Stream"></b></a></li>
</mt:if></__trans_section>
EOF
require MT::Builder;
my $builder = MT::Builder->new;
my $ctx = $tmpl->context();
my $menu_tokens = $builder->compile( $ctx, $menu_str )
or return $cb->error($builder->errstr);
if ( $param->{line_items} ) {
push @{ $param->{line_items} }, bless $menu_tokens, 'MT::Template::Tokens';
}
else {
$ctx->{__stash}{vars}{line_items} = [ bless $menu_tokens, 'MT::Template::Tokens' ];
$param->{line_items} = [ bless $menu_tokens, 'MT::Template::Tokens' ];
}
if ( ( $app->mode eq 'other_profiles' ) || ( $app->mode eq 'list_profileevent' ) ) {
$param->{profile_inactive} = 1;
}
1;
}
sub param_list_member {
my ($cb, $app, $param, $tmpl) = @_;
my $loop = $param->{object_loop};
my @author_ids = map { $_->{id} } @$loop;
my $author_iter = MT->model('author')->load_iter({ id => \@author_ids });
my %profile_counts;
while ( my $author = $author_iter->() ) {
$profile_counts{$author->id} = scalar @{ $author->other_profiles };
}
for my $loop_item ( @$loop ) {
$loop_item->{profiles} = $profile_counts{ $loop_item->{id} };
}
my $header = <<'MTML';
<th><__trans_section component="actionstreams"><__trans phrase="Profiles"></__trans_section></th>
MTML
my $body = <<'MTML';
<mt:if name="has_edit_access">
<td><a href="<mt:var name="script_url">?__mode=other_profiles&id=<mt:var name="id">"><mt:var name="profiles"></a></td>
<mt:else>
<td><mt:var name="profiles"></td>
</mt:if>
MTML
require MT::Builder;
my $builder = MT::Builder->new;
my $ctx = $tmpl->context();
my $body_tokens = $builder->compile( $ctx, $body )
or return $cb->error($builder->errstr);
$param->{more_column_headers} ||= [];
$param->{more_columns} ||= [];
push @{ $param->{more_column_headers} }, $header;
push @{ $param->{more_columns} }, bless $body_tokens, 'MT::Template::Tokens';
1;
}
sub icon_url_for_service {
my $class = shift;
my ($type, $ndata) = @_;
my $plug = $ndata->{plugin} or return;
my $icon_url;
if ($ndata->{icon} && $ndata->{icon} =~ m{ \A \w:// }xms) {
$icon_url = $ndata->{icon};
}
elsif ($ndata->{icon}) {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
$ndata->{icon};
}
elsif ($plug->id eq 'actionstreams') {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
'images', 'services', $type . '.png';
}
return $icon_url;
}
sub _edit_author {
my $arg = 'HASH' eq ref($_[0]) ? shift : { id => shift };
my $app = MT->instance;
my $trans_error = sub {
return $app->error($app->translate(@_)) unless $arg->{no_error};
};
$arg->{id} or return $trans_error->('No id');
my $class = MT->model('author');
my $author = $class->load( $arg->{id} )
or return $trans_error->("No such [_1].", lc( $class->class_label ));
return $trans_error->("Permission denied.")
if ! $app->user
or $app->user->id != $arg->{id} && !$app->user->is_superuser();
return $author;
}
sub list_profileevent {
my $app = shift;
my %param = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
my $author = _edit_author( $app->param('id') ) or return;
my %service_styles;
my @service_styles_loop;
my $code = sub {
my ($event, $row) = @_;
my @meta_col = keys %{ $event->properties->{meta_columns} || {} };
$row->{$_} = $event->{$_} for @meta_col;
$row->{as_html} = $event->as_html();
my ($service, $stream_id) = split /_/, $row->{class}, 2;
$row->{type} = $service;
my $nets = $app->registry('profile_services') || {};
my $net = $nets->{$service};
$row->{service} = $net->{name} if $net;
$row->{url} = $event->url;
if (!$service_styles{$service}) {
if (!$net->{plugin} || $net->{plugin}->id ne 'actionstreams') {
if (my $icon = __PACKAGE__->icon_url_for_service($service, $net)) {
push @service_styles_loop, {
service_type => $service,
service_icon => $icon,
};
}
}
$service_styles{$service} = 1;
}
my $ts = $row->{created_on};
$row->{created_on_relative} = relative_date($ts, time);
$row->{created_on_formatted} = format_ts(
MT::App::CMS->LISTING_DATETIME_FORMAT(),
epoch2ts(undef, offset_time(ts2epoch(undef, $ts))),
undef,
$app->user ? $app->user->preferred_language : undef,
);
};
# Make sure all classes are loaded.
require ActionStreams::Event;
for my $prevt (keys %{ $app->registry('action_streams') }) {
ActionStreams::Event->classes_for_type($prevt);
}
my $plugin = MT->component('ActionStreams');
my %params = map { $_ => $app->param($_) ? 1 : 0 }
qw( saved_deleted hidden shown );
$params{services} = [];
my $services = $app->registry('profile_services');
while (my ($prevt, $service) = each %$services) {
push @{ $params{services} }, {
service_id => $prevt,
service_name => $service->{name},
};
}
$params{services} = [ sort { lc $a->{service_name} cmp lc $b->{service_name} } @{ $params{services} } ];
my %terms = (
class => '*',
author_id => $author->id,
);
my %args = (
sort => 'created_on',
direction => 'descend',
);
if (my $filter = $app->param('filter')) {
$params{filter_key} = $filter;
my $filter_val = $params{filter_val} = $app->param('filter_val');
if ($filter eq 'service') {
$params{filter_label} = $app->translate('Actions from the service [_1]', $app->registry('profile_services')->{$filter_val}->{name});
$terms{class} = $filter_val . '_%';
$args{like} = { class => 1 };
}
elsif ($filter eq 'visible') {
$params{filter_label} = ($filter_val eq 'show') ? $app->translate('Actions that are shown')
: $app->translate('Actions that are hidden');
$terms{visible} = $filter_val eq 'show' ? 1 : 0;
}
}
$params{id} = $params{edit_author_id} = $author->id;
$params{name} = $params{edit_author_name} = $author->name;
$params{service_styles} = \@service_styles_loop;
$app->listing({
type => 'profileevent',
terms => \%terms,
args => \%args,
listing_screen => 1,
code => $code,
template => $plugin->load_tmpl('list_profileevent.tmpl'),
params => \%params,
});
}
sub itemset_hide_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(0);
$event->save;
}
$app->add_return_arg( hidden => 1 );
$app->call_return;
}
sub itemset_show_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(1);
$event->save;
}
$app->add_return_arg( shown => 1 );
$app->call_return;
}
sub _itemset_hide_show_all_events {
my ($app, $new_visible) = @_;
$app->validate_magic or return;
my $event_class = MT->model('profileevent');
# Really we should work directly from the selected author ID, but as an
# itemset event we only got some event IDs. So use its.
my ($event_id) = $app->param('id');
my $event = $event_class->load($event_id)
or return $app->error($app->translate('No such event [_1]', $event_id));
my $author = _edit_author( $event->author_id ) or return;
my $driver = $event_class->driver;
my $stmt = $driver->prepare_statement($event_class, {
# TODO: include filter value when we have filters
author_id => $author->id,
visible => $new_visible ? 0 : 1,
});
my $sql = "UPDATE " . $driver->table_for($event_class) . " SET "
. $driver->dbd->db_column_name($event_class->datasource, 'visible')
. " = ? " . $stmt->as_sql_where;
# Work around error in MT::ObjectDriver::Driver::DBI::sql by doing it inline.
my $dbh = $driver->rw_handle;
$dbh->do($sql, {}, $new_visible, @{ $stmt->{bind} })
or return $app->error($dbh->errstr);
return 1;
}
sub itemset_hide_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 0) or return;
$app->add_return_arg( all_hidden => 1 );
$app->call_return;
}
sub itemset_show_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 1) or return;
$app->add_return_arg( all_shown => 1 );
$app->call_return;
}
sub _build_service_data {
my %info = @_;
my ($networks, $streams, $author) = @info{qw( networks streams author )};
my (@service_styles_loop, @networks);
my %has_profiles;
if ($author) {
my $other_profiles = $author->other_profiles();
$has_profiles{$_->{type}} = 1 for @$other_profiles;
}
my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
keys %$networks;
TYPE: for my $type (@network_keys) {
my $ndata = $networks->{$type}
or next TYPE;
- next TYPE if $info{no_deprecated} && $ndata->{deprecated};
+ next TYPE if !$info{include_deprecated} && $ndata->{deprecated};
my @streams;
if ($streams) {
my $streamdata = $streams->{$type} || {};
@streams =
sort { lc $a->{name} cmp lc $b->{name} }
grep { grep { $_ } @$_{qw( class scraper xpath rss atom )} }
map { +{ stream => $_, %{ $streamdata->{$_} } } }
grep { $_ ne 'plugin' }
keys %$streamdata;
}
$ndata->{ident_hint}
= MT->component('ActionStreams')->translate( $ndata->{ident_hint} )
if $ndata->{ident_hint};
my $ret = {
type => $type,
%$ndata,
label => $ndata->{name},
user_has_account => ($has_profiles{$type} ? 1 : 0),
};
if (@streams) {
for my $stream (@streams) {
$stream->{name}
= MT->component('ActionStreams')->translate( $stream->{name} );
$stream->{description}
= MT->component('ActionStreams')->translate( $stream->{description} );
}
$ret->{streams} = \@streams if @streams;
}
push @networks, $ret;
if (!$ndata->{plugin} || $ndata->{plugin}->id ne 'actionstreams') {
push @service_styles_loop, {
service_type => $type,
service_icon => __PACKAGE__->icon_url_for_service($type, $ndata),
};
}
}
return (
service_styles => \@service_styles_loop,
networks => \@networks,
);
}
sub other_profiles {
my( $app ) = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
my $author = _edit_author( $app->param('id') ) or return;
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl( 'other_profiles.tmpl' );
my @profiles = sort { lc $a->{label} cmp lc $b->{label} }
@{ $author->other_profiles || [] };
my %params = map { $_ => $author->$_ } qw( id name );
$params{edit_author_id} = $params{id};
$params{edit_author_name} = $params{name};
my %messages = map { $_ => $app->param($_) ? 1 : 0 }
(qw( added removed updated edited ));
return $app->build_page( $tmpl, {
%params,
profiles => \@profiles,
listing_screen => 1,
_build_service_data(
networks => $app->registry('profile_services'),
),
%messages,
} );
}
sub dialog_add_edit_profile {
my ($app) = @_;
my $author = _edit_author( $app->param('author_id') ) or return;
my %edit_profile;
my $tmpl_name = 'dialog_add_profile.tmpl';
if (my $edit_type = $app->param('profile_type')) {
my $ident = $app->param('profile_ident') || q{};
my ($profile) = grep { $_->{ident} eq $ident }
@{ $author->other_profiles($edit_type) };
%edit_profile = (
edit_type => $edit_type,
edit_type_name => $app->registry('profile_services', $edit_type, 'name'),
edit_ident => $ident,
edit_streams => $profile->{streams} || [],
);
$tmpl_name = 'dialog_edit_profile.tmpl';
}
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl($tmpl_name);
return $app->build_page($tmpl, {
edit_author_id => $author->id,
_build_service_data(
networks => $app->registry('profile_services'),
streams => $app->registry('action_streams'),
author => $author,
- no_deprecated => 1,
),
%edit_profile,
});
}
sub edit_other_profile {
my $app = shift;
$app->validate_magic() or return;
my $author = _edit_author( $app->param('author_id') ) or return;
my $type = $app->param('profile_type');
my $orig_ident = $app->param('original_ident');
$author->remove_profile($type, $orig_ident);
$app->forward('add_other_profile', success_msg => 'edited');
}
sub add_other_profile {
my $app = shift;
my %param = @_;
$app->validate_magic or return;
my $author = _edit_author( $app->param('author_id') ) or return;
my( $ident, $uri, $label, $type );
if ( $type = $app->param( 'profile_type' ) ) {
my $reg = $app->registry('profile_services');
my $network = $reg->{$type}
or croak "Unknown network $type";
$label = MT->component('ActionStreams')->translate( '[_1] Profile', $network->{name} );
$ident = $app->param( 'profile_id' );
$ident =~ s{ \A \s* }{}xms;
$ident =~ s{ \s* \z }{}xms;
# Check for full URLs.
if (!$network->{ident_exact}) {
my $url_pattern = $network->{url};
my ($pre_ident, $post_ident) = split /(?:\%s|\Q{{ident}}\E)/, $url_pattern, 2;
$pre_ident =~ s{ \A http:// }{}xms;
$post_ident =~ s{ / \z }{}xms;
if ($ident =~ m{ \A (?:http://)? \Q$pre_ident\E (.*?) \Q$post_ident\E /? \z }xms) {
$ident = $1;
}
}
$uri = $network->{url};
$uri =~ s{ (?:\%s|\Q{{ident}}\E) }{$ident}xmsg;
} else {
$ident = $uri = $app->param( 'profile_uri' );
$label = $app->param( 'profile_label' );
$type = 'website';
}
my $profile = {
type => $type,
ident => $ident,
label => $label,
uri => $uri,
};
my %streams = map { join(q{_}, $type, $_) => 1 }
grep { $_ ne 'plugin' && $app->param(join q{_}, 'stream', $type, $_) }
keys %{ $app->registry('action_streams', $type) || {} };
$profile->{streams} = \%streams if %streams;
$app->run_callbacks('pre_add_profile.' . $type, $app, $author, $profile);
$author->add_profile($profile);
$app->run_callbacks('post_add_profile.' . $type, $app, $author, $profile);
my $success_msg = $param{success_msg} || 'added';
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => $author->id, $success_msg => 1 },
));
}
sub remove_other_profile {
my( $app ) = @_;
$app->validate_magic or return;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
$users{$author_id} ||= _edit_author({ id => $author_id,
no_error => 1 });
my $author = $users{$author_id} or next PROFILE;
$app->run_callbacks('pre_remove_profile.' . $type, $app, $author, $type, $ident);
$author->remove_profile( $type, $ident );
$app->run_callbacks('post_remove_profile.' . $type, $app, $author, $type, $ident);
$page_author_id = $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), removed => 1 },
));
}
sub profile_add_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
$app->param('author_id', $user->id);
my $type = $app->param('profile_type')
or return $app->error( $app->translate("Invalid request.") );
# The profile side interface doesn't have stream selection, so select
# them all by default.
# TODO: factor out the adding logic (and parameterize stream selection) to stop faking params
foreach my $stream ( keys %{ $app->registry('action_streams', $type) || {} } ) {
next if $stream eq 'plugin';
$app->param(join('_', 'stream', $type, $stream), 1);
}
add_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub profile_first_update_events {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub profile_delete_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
# TODO: factor out this logic instead of having to fake params
my $id = scalar $app->param('id');
$id = $user->id . ':' . $id;
$app->param('id', $id);
remove_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub itemset_update_profiles {
my $app = shift;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
$users{$author_id} ||= _edit_author({ id => $author_id,
no_error => 1 });
my $author = $users{$author_id} or next PROFILE;
my $profiles = $author->other_profiles($type);
if (!$profiles) {
next PROFILE;
}
my @profiles = grep { $_->{ident} eq $ident } @$profiles;
for my $author_profile (@profiles) {
update_events_for_profile($author, $author_profile,
synchronous => 1);
}
$page_author_id ||= $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), updated => 1 },
));
}
sub first_profile_update {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub rebuild_action_stream_blogs {
my ($cb, $app) = @_;
my $plugin = MT->component('ActionStreams');
my $pd_iter = MT->model('plugindata')->load_iter({
plugin => $plugin->key,
key => { like => 'configuration:blog:%' }
});
my %rebuild;
while ( my $pd = $pd_iter->() ) {
next unless $pd->data('rebuild_for_action_stream_events');
my ($blog_id) = $pd->key =~ m/:blog:(\d+)$/;
$rebuild{$blog_id} = 1;
}
for my $blog_id (keys %rebuild) {
# TODO: limit this to indexes that publish action stream data, once
# we can magically infer template content before building it
my $blog = MT->model('blog')->load( $blog_id ) or next;
# Republish all the blog's known non-virtual index fileinfos that
# have real template objects.
my $finfo_class = MT->model('fileinfo');
my $finfo_template_col = $finfo_class->driver->dbd->db_column_name(
$finfo_class->datasource, 'template_id');
my @fileinfos = $finfo_class->load({
blog_id => $blog->id,
archive_type => 'index',
virtual => [ \'IS NULL', 0 ],
}, {
join => MT->model('template')->join_on(undef,
{ id => \"= $finfo_template_col" }),
});
require MT::TheSchwartz;
require TheSchwartz::Job;
for my $fi (@fileinfos) {
my $job = TheSchwartz::Job->new();
$job->funcname('MT::Worker::Publish');
$job->uniqkey($fi->id);
$job->run_after(time + 240); # 4 minutes
MT::TheSchwartz->insert($job);
}
}
}
sub widget_recent {
my ($app, $tmpl, $widget_param) = @_;
$tmpl->param('author_id', $app->user->id);
$tmpl->param('blog_id', $app->blog->id) if $app->blog;
}
sub widget_blog_dashboard_only {
my ($page, $scope) = @_;
return if $scope eq 'dashboard:system';
return 1;
}
sub update_events {
my $mt = MT->app;
$mt->run_callbacks('pre_action_streams_task', $mt);
my $au_class = MT->model('author');
my $author_iter = $au_class->search({
status => $au_class->ACTIVE(),
}, {
join => [ $au_class->meta_pkg, 'author_id', { type => 'other_profiles' } ],
});
while (my $author = $author_iter->()) {
my $profiles = $author->other_profiles();
$mt->run_callbacks('pre_update_action_streams', $mt, $author, $profiles);
PROFILE: for my $profile (@$profiles) {
update_events_for_profile($author, $profile);
}
$mt->run_callbacks('post_update_action_streams', $mt, $author, $profiles);
}
$mt->run_callbacks('post_action_streams_task', $mt);
}
sub update_events_for_profile {
my ($author, $profile, %param) = @_;
my $type = $profile->{type};
my $streams = $profile->{streams};
return if !$streams || !%$streams;
my $services = MT->registry('profile_services');
return if !exists $services->{$type} || $services->{$type}->{deprecated};
require ActionStreams::Event;
my @event_classes = ActionStreams::Event->classes_for_type($type)
or return;
my $mt = MT->app;
$mt->run_callbacks('pre_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
EVENTCLASS: for my $event_class (@event_classes) {
next EVENTCLASS if !$streams->{$event_class->class_type};
if ($param{synchronous}) {
$event_class->update_events_loggily(
author => $author,
hide_timeless => $param{hide_timeless} ? 1 : 0,
%$profile,
);
}
else {
# Defer regular updates to job workers.
require ActionStreams::Worker;
ActionStreams::Worker->make_work(
event_class => $event_class,
author => $author,
%$profile,
);
}
}
$mt->run_callbacks('post_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
}
1;
|
markpasc/mt-plugin-action-streams
|
776f74a3769d35a28c2f26ede36b7c9d05bc6b3f
|
Removed today_date hack from archive template. additionaly fixed typo in index. bugzid:100249.
|
diff --git a/plugins/ActionStreams/blog_tmpl/archive.mtml b/plugins/ActionStreams/blog_tmpl/archive.mtml
index 5a03d5a..8cba1b7 100644
--- a/plugins/ActionStreams/blog_tmpl/archive.mtml
+++ b/plugins/ActionStreams/blog_tmpl/archive.mtml
@@ -1,67 +1,62 @@
<!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" id="sixapart-standard">
<head>
<$mt:Include module="<__trans phrase="HTML Head">"$>
<title><$mt:BlogName encode_html="1"$></title>
</head>
<body id="<$mt:BlogTemplateSetID$>" class="mt-main-index <$mt:Var name="page_layout"$>">
<div id="container">
<div id="container-inner">
<$mt:Include module="<__trans phrase="Banner Header">"$>
<div id="content">
<div id="content-inner">
<div id="alpha">
<div id="alpha-inner">
<div class="action-stream hfeed">
<mt:ActionStreams days="30">
<mt:DateHeader>
<h2 class="action-stream-header asset-name">
- <mt:setvarblock name="this_date"><mt:StreamActionDate format="%B %e"></mt:setvarblock>
- <mt:if name="$today_date" eq="$this_date">
- Today
- <mt:else>
- <mt:var name="this_date">
- </mt:if>
+ <mt:StreamActionDate format="%B %e">
</h2>
<ul class="action-stream-list">
</mt:DateHeader>
<li class="hentry service-icon service-<mt:var name="service_type">">
<span class="entry-title"><mt:StreamAction remove_html="1"></span>
<span class="entry-content"><mt:StreamAction smarty_pants="1"></span>
<span class="updated"><mt:StreamActionModifiedDate utc="1" format="%Y-%m-%dT%H:%M:%SZ"></span>
<span class="published"><mt:StreamActionDate utc="1" format="%Y-%m-%dT%H:%M:%SZ"></span>
</li>
<mt:DateFooter>
</ul>
</mt:DateFooter>
</mt:ActionStreams>
</div>
</div>
</div>
<$mt:Include module="<__trans phrase="Sidebar">"$>
</div>
</div>
<$mt:Include module="<__trans phrase="Banner Footer">"$>
</div>
</div>
</body>
</html>
diff --git a/plugins/ActionStreams/blog_tmpl/main_index.mtml b/plugins/ActionStreams/blog_tmpl/main_index.mtml
index aeda914..cd22355 100644
--- a/plugins/ActionStreams/blog_tmpl/main_index.mtml
+++ b/plugins/ActionStreams/blog_tmpl/main_index.mtml
@@ -1,68 +1,68 @@
<!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" id="sixapart-standard">
<head>
<$mt:Include module="<__trans phrase="HTML Head">"$>
<title><$mt:BlogName encode_html="1"$></title>
</head>
<body id="<$mt:BlogTemplateSetID$>" class="mt-main-index <$mt:Var name="page_layout"$>">
<div id="container">
<div id="container-inner">
<$mt:Include module="<__trans phrase="Banner Header">"$>
<div id="content">
<div id="content-inner">
<div id="alpha">
<div id="alpha-inner">
<mt:setvarblock name="today_date"><mt:Date format="%B %e"></mt:setvarblock>
<div class="action-stream hfeed">
<mt:ActionStreams days="5">
<mt:DateHeader>
<h2 class="action-stream-header asset-name">
<mt:setvarblock name="this_date"><mt:StreamActionDate format="%B %e"></mt:setvarblock>
- <mt:if name="$today_date" eq="$this_date">
+ <mt:if name="today_date" eq="$this_date">
Today
<mt:else>
<mt:var name="this_date">
</mt:if>
</h2>
<ul class="action-stream-list">
</mt:DateHeader>
<li class="hentry service-icon service-<mt:var name="service_type">">
<span class="entry-title"><mt:StreamAction remove_html="1"></span>
<span class="entry-content"><mt:StreamAction smarty_pants="1"></span>
<span class="updated"><mt:StreamActionModifiedDate utc="1" format="%Y-%m-%dT%H:%M:%SZ"></span>
<span class="published"><mt:StreamActionDate utc="1" format="%Y-%m-%dT%H:%M:%SZ"></span>
</li>
<mt:DateFooter>
</ul>
</mt:DateFooter>
</mt:ActionStreams>
</div>
</div>
</div>
<$mt:Include module="<__trans phrase="Sidebar">"$>
</div>
</div>
<$mt:Include module="<__trans phrase="Banner Footer">"$>
</div>
</div>
</body>
</html>
|
markpasc/mt-plugin-action-streams
|
19288a908ac42dd8ab7de663d7fd586934480074
|
Added "for USERNAME" to page_title for list_profileevents and other_profiles modes to provide better context and consistency with the permissions and followers/following screens of the Community app. bugzid:92089
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
index 313fa57..8e00998 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
@@ -1,706 +1,710 @@
package ActionStreams::Plugin;
use strict;
use warnings;
use Carp qw( croak );
use MT::Util qw( relative_date offset_time epoch2ts ts2epoch format_ts );
sub users_content_nav {
my ($cb, $app, $html_ref) = @_;
return unless $app->param('id');
$$html_ref =~ s{class=["']active["']}{}xmsg
if $app->mode eq 'list_profileevent' || $app->mode eq 'other_profiles';
$$html_ref =~ m{ "> ((?:<b>)?) <__trans \s phrase="Permissions"> ((?:</b>)?) </a> }xms;
my ($open_bold, $close_bold) = ($1, $2);
my $html = <<"EOF";
<mt:if var="USER_VIEW">
<li><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">">$open_bold<__trans phrase="Other Profiles">$close_bold</a></li>
<li><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">">$open_bold<__trans phrase="Action Stream">$close_bold</a></li>
</mt:if>
<mt:if var="edit_author">
<li<mt:if name="other_profiles"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="id" escape="url">">$open_bold<__trans phrase="Other Profiles">$close_bold</a></li>
<li<mt:if name="list_profileevent"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="id" escape="url">">$open_bold<__trans phrase="Action Stream">$close_bold</a></li>
</mt:if>
EOF
$$html_ref =~ s{(?=</ul>)}{$html}xmsg;
}
sub icon_url_for_service {
my $class = shift;
my ($type, $ndata) = @_;
my $plug = $ndata->{plugin} or return;
my $icon_url;
if ($ndata->{icon} && $ndata->{icon} =~ m{ \A \w:// }xms) {
$icon_url = $ndata->{icon};
}
elsif ($ndata->{icon}) {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
$ndata->{icon};
}
elsif ($plug->id eq 'actionstreams') {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
'images', 'services', $type . '.png';
}
return $icon_url;
}
sub _edit_author {
my $arg = 'HASH' eq ref($_[0]) ? shift : { id => shift };
my $app = MT->instance;
my $trans_error = sub {
return $app->error($app->translate(@_)) unless $arg->{no_error};
};
$arg->{id} or return $trans_error->('No id');
my $class = MT->model('author');
my $author = $class->load( $arg->{id} )
or return $trans_error->("No such [_1].", lc( $class->class_label ));
return $trans_error->("Permission denied.")
if ! $app->user
or $app->user->id != $arg->{id} && !$app->user->is_superuser();
return $author;
}
sub list_profileevent {
my $app = shift;
my %param = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
my $author = _edit_author( $app->param('id') ) or return;
my %service_styles;
my @service_styles_loop;
my $code = sub {
my ($event, $row) = @_;
my @meta_col = keys %{ $event->properties->{meta_columns} || {} };
$row->{$_} = $event->{$_} for @meta_col;
$row->{as_html} = $event->as_html();
my ($service, $stream_id) = split /_/, $row->{class}, 2;
$row->{type} = $service;
my $nets = $app->registry('profile_services') || {};
my $net = $nets->{$service};
$row->{service} = $net->{name} if $net;
$row->{url} = $event->url;
if (!$service_styles{$service}) {
if (!$net->{plugin} || $net->{plugin}->id ne 'actionstreams') {
if (my $icon = __PACKAGE__->icon_url_for_service($service, $net)) {
push @service_styles_loop, {
service_type => $service,
service_icon => $icon,
};
}
}
$service_styles{$service} = 1;
}
my $ts = $row->{created_on};
$row->{created_on_relative} = relative_date($ts, time);
$row->{created_on_formatted} = format_ts(
MT::App::CMS->LISTING_DATETIME_FORMAT(),
epoch2ts(undef, offset_time(ts2epoch(undef, $ts))),
undef,
$app->user ? $app->user->preferred_language : undef,
);
};
# Make sure all classes are loaded.
require ActionStreams::Event;
for my $prevt (keys %{ $app->registry('action_streams') }) {
ActionStreams::Event->classes_for_type($prevt);
}
my $plugin = MT->component('ActionStreams');
my %params = map { $_ => $app->param($_) ? 1 : 0 }
qw( saved_deleted hidden shown );
$params{services} = [];
my $services = $app->registry('profile_services');
while (my ($prevt, $service) = each %$services) {
push @{ $params{services} }, {
service_id => $prevt,
service_name => $service->{name},
};
}
$params{services} = [ sort { lc $a->{service_name} cmp lc $b->{service_name} } @{ $params{services} } ];
my %terms = (
class => '*',
author_id => $author->id,
);
my %args = (
sort => 'created_on',
direction => 'descend',
);
if (my $filter = $app->param('filter')) {
$params{filter_key} = $filter;
my $filter_val = $params{filter_val} = $app->param('filter_val');
if ($filter eq 'service') {
$params{filter_label} = $app->translate('Actions from the service [_1]', $app->registry('profile_services')->{$filter_val}->{name});
$terms{class} = $filter_val . '_%';
$args{like} = { class => 1 };
}
elsif ($filter eq 'visible') {
$params{filter_label} = ($filter_val eq 'show') ? 'Actions that are shown'
: 'Actions that are hidden';
$terms{visible} = $filter_val eq 'show' ? 1 : 0;
}
}
- $params{id} = $params{edit_author_id} = $author->id;
+ $params{id} = $params{edit_author_id} = $author->id;
+ $params{name} = $params{edit_author_name} = $author->name;
$params{service_styles} = \@service_styles_loop;
$app->listing({
type => 'profileevent',
terms => \%terms,
args => \%args,
listing_screen => 1,
code => $code,
template => $plugin->load_tmpl('list_profileevent.tmpl'),
params => \%params,
});
}
sub itemset_hide_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(0);
$event->save;
}
$app->add_return_arg( hidden => 1 );
$app->call_return;
}
sub itemset_show_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(1);
$event->save;
}
$app->add_return_arg( shown => 1 );
$app->call_return;
}
sub _itemset_hide_show_all_events {
my ($app, $new_visible) = @_;
$app->validate_magic or return;
my $event_class = MT->model('profileevent');
# Really we should work directly from the selected author ID, but as an
# itemset event we only got some event IDs. So use its.
my ($event_id) = $app->param('id');
my $event = $event_class->load($event_id)
or return $app->error($app->translate('No such event [_1]', $event_id));
my $author = _edit_author( $event->author_id ) or return;
my $driver = $event_class->driver;
my $stmt = $driver->prepare_statement($event_class, {
# TODO: include filter value when we have filters
author_id => $author->id,
visible => $new_visible ? 0 : 1,
});
my $sql = "UPDATE " . $driver->table_for($event_class) . " SET "
. $driver->dbd->db_column_name($event_class->datasource, 'visible')
. " = ? " . $stmt->as_sql_where;
# Work around error in MT::ObjectDriver::Driver::DBI::sql by doing it inline.
my $dbh = $driver->rw_handle;
$dbh->do($sql, {}, $new_visible, @{ $stmt->{bind} })
or return $app->error($dbh->errstr);
return 1;
}
sub itemset_hide_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 0) or return;
$app->add_return_arg( all_hidden => 1 );
$app->call_return;
}
sub itemset_show_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 1) or return;
$app->add_return_arg( all_shown => 1 );
$app->call_return;
}
sub _build_service_data {
my %info = @_;
my ($networks, $streams, $author) = @info{qw( networks streams author )};
my (@service_styles_loop, @networks);
my %has_profiles;
if ($author) {
my $other_profiles = $author->other_profiles();
$has_profiles{$_->{type}} = 1 for @$other_profiles;
}
my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
keys %$networks;
TYPE: for my $type (@network_keys) {
my $ndata = $networks->{$type}
or next TYPE;
my @streams;
if ($streams) {
my $streamdata = $streams->{$type} || {};
@streams =
sort { lc $a->{name} cmp lc $b->{name} }
grep { grep { $_ } @$_{qw( class scraper xpath rss atom )} }
map { +{ stream => $_, %{ $streamdata->{$_} } } }
grep { $_ ne 'plugin' }
keys %$streamdata;
}
my $ret = {
type => $type,
%$ndata,
label => $ndata->{name},
user_has_account => ($has_profiles{$type} ? 1 : 0),
};
$ret->{streams} = \@streams if @streams;
push @networks, $ret;
if (!$ndata->{plugin} || $ndata->{plugin}->id ne 'actionstreams') {
push @service_styles_loop, {
service_type => $type,
service_icon => __PACKAGE__->icon_url_for_service($type, $ndata),
};
}
}
return (
service_styles => \@service_styles_loop,
networks => \@networks,
);
}
sub other_profiles {
my( $app ) = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
my $author = _edit_author( $app->param('id') ) or return;
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl( 'other_profiles.tmpl' );
my @profiles = sort { lc $a->{label} cmp lc $b->{label} }
@{ $author->other_profiles || [] };
+ my %params = map { $_ => $author->$_ } qw( id name );
+ $params{edit_author_id} = $params{id};
+ $params{edit_author_name} = $params{name};
+
my %messages = map { $_ => $app->param($_) ? 1 : 0 }
(qw( added removed updated edited ));
return $app->build_page( $tmpl, {
- id => $author->id,
- edit_author_id => $author->id,
+ %params,
profiles => \@profiles,
listing_screen => 1,
_build_service_data(
networks => $app->registry('profile_services'),
),
%messages,
} );
}
sub dialog_add_edit_profile {
my ($app) = @_;
my $author = _edit_author( $app->param('author_id') ) or return;
my %edit_profile;
my $tmpl_name = 'dialog_add_profile.tmpl';
if (my $edit_type = $app->param('profile_type')) {
my $ident = $app->param('profile_ident') || q{};
my ($profile) = grep { $_->{ident} eq $ident }
@{ $author->other_profiles($edit_type) };
%edit_profile = (
edit_type => $edit_type,
edit_type_name => $app->registry('profile_services', $edit_type, 'name'),
edit_ident => $ident,
edit_streams => $profile->{streams} || [],
);
$tmpl_name = 'dialog_edit_profile.tmpl';
}
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl($tmpl_name);
return $app->build_page($tmpl, {
edit_author_id => $author->id,
_build_service_data(
networks => $app->registry('profile_services'),
streams => $app->registry('action_streams'),
author => $author,
),
%edit_profile,
});
}
sub edit_other_profile {
my $app = shift;
$app->validate_magic() or return;
my $author = _edit_author( $app->param('author_id') ) or return;
my $type = $app->param('profile_type');
my $orig_ident = $app->param('original_ident');
$author->remove_profile($type, $orig_ident);
$app->forward('add_other_profile', success_msg => 'edited');
}
sub add_other_profile {
my $app = shift;
my %param = @_;
$app->validate_magic or return;
my $author = _edit_author( $app->param('author_id') ) or return;
my( $ident, $uri, $label, $type );
if ( $type = $app->param( 'profile_type' ) ) {
my $reg = $app->registry('profile_services');
my $network = $reg->{$type}
or croak "Unknown network $type";
$label = $network->{name} . ' Profile';
$ident = $app->param( 'profile_id' );
$ident =~ s{ \A \s* }{}xms;
$ident =~ s{ \s* \z }{}xms;
# Check for full URLs.
if (!$network->{ident_exact}) {
my $url_pattern = $network->{url};
my ($pre_ident, $post_ident) = split /(?:\%s|\Q{{ident}}\E)/, $url_pattern, 2;
$pre_ident =~ s{ \A http:// }{}xms;
$post_ident =~ s{ / \z }{}xms;
if ($ident =~ m{ \A (?:http://)? \Q$pre_ident\E (.*?) \Q$post_ident\E /? \z }xms) {
$ident = $1;
}
}
$uri = $network->{url};
$uri =~ s{ (?:\%s|\Q{{ident}}\E) }{$ident}xmsg;
} else {
$ident = $uri = $app->param( 'profile_uri' );
$label = $app->param( 'profile_label' );
$type = 'website';
}
my $profile = {
type => $type,
ident => $ident,
label => $label,
uri => $uri,
};
my %streams = map { join(q{_}, $type, $_) => 1 }
grep { $_ ne 'plugin' && $app->param(join q{_}, 'stream', $type, $_) }
keys %{ $app->registry('action_streams', $type) || {} };
$profile->{streams} = \%streams if %streams;
$app->run_callbacks('pre_add_profile.' . $type, $app, $author, $profile);
$author->add_profile($profile);
$app->run_callbacks('post_add_profile.' . $type, $app, $author, $profile);
my $success_msg = $param{success_msg} || 'added';
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => $author->id, $success_msg => 1 },
));
}
sub remove_other_profile {
my( $app ) = @_;
$app->validate_magic or return;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
$users{$author_id} ||= _edit_author({ id => $author_id,
no_error => 1 });
my $author = $users{$author_id} or next PROFILE;
$app->run_callbacks('pre_remove_profile.' . $type, $app, $author, $type, $ident);
$author->remove_profile( $type, $ident );
$app->run_callbacks('post_remove_profile.' . $type, $app, $author, $type, $ident);
$page_author_id = $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), removed => 1 },
));
}
sub profile_add_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
$app->param('author_id', $user->id);
my $type = $app->param('profile_type')
or return $app->error( $app->translate("Invalid request.") );
# The profile side interface doesn't have stream selection, so select
# them all by default.
# TODO: factor out the adding logic (and parameterize stream selection) to stop faking params
foreach my $stream ( keys %{ $app->registry('action_streams', $type) || {} } ) {
next if $stream eq 'plugin';
$app->param(join('_', 'stream', $type, $stream), 1);
}
add_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub profile_first_update_events {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub profile_delete_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
# TODO: factor out this logic instead of having to fake params
my $id = scalar $app->param('id');
$id = $user->id . ':' . $id;
$app->param('id', $id);
remove_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub itemset_update_profiles {
my $app = shift;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
$users{$author_id} ||= _edit_author({ id => $author_id,
no_error => 1 });
my $author = $users{$author_id} or next PROFILE;
my $profiles = $author->other_profiles($type);
if (!$profiles) {
next PROFILE;
}
my @profiles = grep { $_->{ident} eq $ident } @$profiles;
for my $author_profile (@profiles) {
update_events_for_profile($author, $author_profile,
synchronous => 1);
}
$page_author_id ||= $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), updated => 1 },
));
}
sub first_profile_update {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub rebuild_action_stream_blogs {
my ($cb, $app) = @_;
my $plugin = MT->component('ActionStreams');
my $pd_iter = MT->model('plugindata')->load_iter({
plugin => $plugin->key,
key => { like => 'configuration:blog:%' }
});
my %rebuild;
while ( my $pd = $pd_iter->() ) {
next unless $pd->data('rebuild_for_action_stream_events');
my ($blog_id) = $pd->key =~ m/:blog:(\d+)$/;
$rebuild{$blog_id} = 1;
}
for my $blog_id (keys %rebuild) {
# TODO: limit this to indexes that publish action stream data, once
# we can magically infer template content before building it
my $blog = MT->model('blog')->load( $blog_id ) or next;
# Republish all the blog's known non-virtual index fileinfos that
# have real template objects.
my $finfo_class = MT->model('fileinfo');
my $finfo_template_col = $finfo_class->driver->dbd->db_column_name(
$finfo_class->datasource, 'template_id');
my @fileinfos = $finfo_class->load({
blog_id => $blog->id,
archive_type => 'index',
virtual => [ \'IS NULL', 0 ],
}, {
join => MT->model('template')->join_on(undef,
{ id => \"= $finfo_template_col" }),
});
require MT::TheSchwartz;
require TheSchwartz::Job;
for my $fi (@fileinfos) {
my $job = TheSchwartz::Job->new();
$job->funcname('MT::Worker::Publish');
$job->uniqkey($fi->id);
$job->run_after(time + 240); # 4 minutes
MT::TheSchwartz->insert($job);
}
}
}
sub widget_recent {
my ($app, $tmpl, $widget_param) = @_;
$tmpl->param('author_id', $app->user->id);
$tmpl->param('blog_id', $app->blog->id) if $app->blog;
}
sub widget_blog_dashboard_only {
my ($page, $scope) = @_;
return if $scope eq 'dashboard:system';
return 1;
}
sub update_events {
my $mt = MT->app;
$mt->run_callbacks('pre_action_streams_task', $mt);
my $au_class = MT->model('author');
my $author_iter = $au_class->search({
status => $au_class->ACTIVE(),
}, {
join => [ $au_class->meta_pkg, 'author_id', { type => 'other_profiles' } ],
});
while (my $author = $author_iter->()) {
my $profiles = $author->other_profiles();
$mt->run_callbacks('pre_update_action_streams', $mt, $author, $profiles);
PROFILE: for my $profile (@$profiles) {
update_events_for_profile($author, $profile);
}
$mt->run_callbacks('post_update_action_streams', $mt, $author, $profiles);
}
$mt->run_callbacks('post_action_streams_task', $mt);
}
sub update_events_for_profile {
my ($author, $profile, %param) = @_;
my $type = $profile->{type};
my $streams = $profile->{streams};
return if !$streams || !%$streams;
require ActionStreams::Event;
my @event_classes = ActionStreams::Event->classes_for_type($type)
or return;
my $mt = MT->app;
$mt->run_callbacks('pre_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
EVENTCLASS: for my $event_class (@event_classes) {
next EVENTCLASS if !$streams->{$event_class->class_type};
if ($param{synchronous}) {
$event_class->update_events_loggily(
author => $author,
hide_timeless => $param{hide_timeless} ? 1 : 0,
%$profile,
);
}
else {
# Defer regular updates to job workers.
require ActionStreams::Worker;
ActionStreams::Worker->make_work(
event_class => $event_class,
author => $author,
%$profile,
);
}
}
$mt->run_callbacks('post_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
}
1;
diff --git a/plugins/ActionStreams/tmpl/list_profileevent.tmpl b/plugins/ActionStreams/tmpl/list_profileevent.tmpl
index a9f51f5..b0b658f 100644
--- a/plugins/ActionStreams/tmpl/list_profileevent.tmpl
+++ b/plugins/ActionStreams/tmpl/list_profileevent.tmpl
@@ -1,276 +1,276 @@
<mt:setvar name="edit_author" value="1">
<mt:setvar name="list_profileevent" value="1">
-<mt:setvar name="page_title" value="<__trans phrase="Action Stream">">
+<mt:setvarblock name="page_title"><__trans phrase="Action Stream for [_1]" params="<mt:Var name="edit_author_name">"></mt:setvarblock>
<mt:setvarblock name="html_head" append="1">
<link rel="stylesheet" type="text/css" href="<mt:var name="static_uri">plugins/ActionStreams/css/action-streams.css" />
<script type="text/javascript">
<!--
var tableSelect;
function init() {
// set up table select awesomeness
tableSelect = new TC.TableSelect("profileevent-listing-table");
tableSelect.rowSelect = true;
}
TC.attachLoadEvent(init);
function finishPluginActionAll(f, action) {
var select_all = getByID('select-all-checkbox')
if (select_all) {
select_all.checked = true;
tableSelect.select(select_all);
}
return doForMarkedInThisWindow(f, '', 'profileevents', 'id', 'itemset_action',
{'action_name': action}, 'to act upon');
}
function toggleFilter() {
var filterActive = getByID("filter-title");
if (filterActive.style.display == "none") {
filterActive.style.display = "block";
getByID("filter-select").style.display = "none";
} else {
filterActive.style.display = "none";
getByID("filter-select").style.display = "block";
<mt:unless name="filter">setFilterCol('service');</mt:unless>
}
}
function setFilterCol(choice) {
var sel = getByID('filter-select');
if (!sel) return;
sel.className = "filter-" + choice;
if (choice != 'none') {
var fld = getByID('filter-col');
if (choice == 'service')
fld.selectedIndex = 0;
else if (choice == 'visible')
fld.selectedIndex = 1;
else if (choice == 'exacttag')
fld.selectedIndex = 2;
else if (choice == 'normalizedtag')
fld.selectedIndex = 3;
else if (choice == 'category_id')
fld.selectedIndex = 4;
else if (choice == 'asset_id')
fld.selectedIndex = <mt:if name="category_loop">5<mt:else>4</mt:if>;
col_span = getByID("filter-text-col");
if (fld.selectedIndex > -1 && col_span)
col_span.innerHTML = '<strong>' + fld.options[fld.selectedIndex].text + '</strong>';
}
}
function enableFilterButton(fld) {
if (fld && (fld.id == "filter-col")) {
var opt = fld.options[fld.selectedIndex];
if (opt.value == 'author_id') {
var authfld = getByID("author_id-val");
var authopt = authfld.options[authfld.selectedIndex];
if (authopt.value == "") {
getByID("filter-button").style.display = "none";
return;
}
}
}
getByID("filter-button").style.display = "inline";
}
// -->
</script>
<style type="text/css">
<!--
#filter-visible, #filter-service { display: none }
.filter-visible #filter-visible,
.filter-service #filter-service { display: inline }
#profileevent-listing-table .date { white-space: nowrap; }
#profileevent-listing-table .service { width: 8em; }
#main-content { padding-top: 5px; }
.content-nav #main-content .msg { margin-left: 0px; }
<mt:loop name="service_styles">
.service-<mt:var name="service_type"> { background-image: url(<mt:var name="service_icon">); }
</mt:loop>
// -->
</style>
</mt:setvarblock>
<mt:setvarblock name="content_nav">
<mt:include name="include/users_content_nav.tmpl">
</mt:setvarblock>
<mt:setvarblock name="system_msg">
<mt:if name="saved_deleted">
<mtapp:statusmsg
id="saved_deleted"
class="success">
<__trans phrase="The selected events were deleted.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="hidden">
<mtapp:statusmsg
id="hidden"
class="success">
<__trans phrase="The selected events were hidden.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="shown">
<mtapp:statusmsg
id="shown"
class="success">
<__trans phrase="The selected events were shown.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="all_hidden">
<mtapp:statusmsg
id="all_hidden"
class="success">
<__trans phrase="All action stream events were hidden.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="all_shown">
<mtapp:statusmsg
id="all_shown"
class="sucess">
<__trans phrase="All action stream events were shown.">
</mtapp:statusmsg>
</mt:if>
</mt:setvarblock>
<mt:setvarblock name="html_body_footer">
<mt:include name="include/display_options.tmpl">
</mt:setvarblock>
<mt:setvarblock name="action_buttons">
<a href="javascript:void(0)"
onclick="doForMarkedInThisWindow(getByID('profileevent-listing-form'), '<__trans phrase="event">', '<__trans phrase="events">', 'id', 'itemset_hide_events'); return false"
accesskey="h"
title="<__trans phrase="Hide selected events (h)">"
><__trans phrase="Hide"></a>
<a href="javascript:void(0)"
onclick="doForMarkedInThisWindow(getByID('profileevent-listing-form'), '<__trans phrase="event">', '<__trans phrase="events">', 'id', 'itemset_show_events'); return false"
accesskey="h"
title="<__trans phrase="Show selected events (h)">"
><__trans phrase="Show"></a>
</mt:setvarblock>
<mt:include name="include/header.tmpl">
<div class="listing-filter">
<div class="listing-filter-inner inner pkg">
<form id="filter-form" method="get" action="<mt:var name="mt_url">">
<input type="hidden" name="__mode" value="<mt:var name="mode">" />
<mt:if name="id">
<input type="hidden" name="id" value="<mt:var name="id" escape="url">" />
</mt:if>
<mt:if name="is_power_edit">
<input type="hidden" name="is_power_edit" value="1" />
</mt:if>
<input id="filter" type="hidden" name="filter" value="" />
<input id="filter_val" type="hidden" name="filter_val" value="" />
</form>
<form id="filter-select-form" method="get" onsubmit="return execFilter(this)">
<div class="filter">
<div id="filter-title">
<mt:if name="filter_key">
<strong>Showing only: <mt:var name="filter_label" escape="html"></strong>
<a class="filter-link" href="<mt:var name="script_url">?__mode=<mt:var name="mode">&id=<mt:var name="id" escape="url">">[ Remove filter ]</a>
<mt:else>
<mt:if name="filter">
<mt:else>
<strong>All stream actions</strong>
<a class="filter-link" href="javascript:void(0)" onclick="toggleFilter()">[ change ]</a>
</mt:if>
</mt:if>
</div>
<div id="filter-select" class="page-title" style="display: none">
Show only actions where
<select id="filter-col" name="filter" onchange="setFilterCol(this.options[this.selectedIndex].value); enableFilterButton(this)">
<!-- option value="stream">stream</option -->
<option value="service">service</option>
<option value="visible">visibility</option>
</select>
is
<span id="filter-visible">
<select id="visible-val" name="filter_val" onchange="enableFilterButton()">
<option value="hide">hidden</option>
<option value="show">shown</option>
</select>
</span>
<span id="filter-service">
<select id="service-val" name="filter_val" onchange="enableFilterButton()">
<mt:loop name="services">
<option value="<mt:var name="service_id">"><mt:var name="service_name"></option>
</mt:loop>
</select>
</span>
<span class="buttons">
<a href="javascript:void(0)"
id="filter-button"
onclick="return execFilter(getByID('filter-select-form'))"
type="submit"
>Filter</a>
<a href="javascript:void(0)"
onclick="toggleFilter(); return false"
type="submit"
>Cancel</a>
</span>
</div>
</div>
</form>
</div>
</div>
<mtapp:listing type="profileevent" default="<__trans phrase="No events could be found.">" empty_message="<__trans phrase="No events could be found.">">
<mt:if name="__first__">
<thead>
<tr>
<th class="cb"><input type="checkbox" id="select-all-checkbox" name="id-head" value="all" class="select" /></th>
<th class="status">
<img src="<mt:var name="static_uri">images/status_icons/invert-flag.gif" alt="<__trans phrase="Status">" title="<__trans phrase="Status">" width="9" height="9" />
</th>
<th class="event"><__trans phrase="Event"></th>
<th class="service"><span class="service-icon"><__trans phrase="Service"></span></th>
<th class="date"><__trans phrase="Created"></th>
<th class="view"><__trans phrase="View"></th>
</tr>
</thead>
<tbody>
</mt:if>
<tr class="<mt:if name="__odd__">odd<mt:else>even</mt:if>">
<td class="cb">
<input type="checkbox" name="id" value="<mt:var name="id">" class="select" />
</td>
<td class="status si status-<mt:if name="visible">publish<mt:else>pending</mt:if>">
<img src="<mt:var name="static_uri">images/spacer.gif" width="13" height="9" alt="<mt:if name="visible"><__trans phrase="Shown"><mt:else><__trans phrase="Hidden"></mt:if>" />
</td>
<td class="event">
<mt:var name="as_html" remove_html="1">
</td>
<td class="service">
<span class="service-icon service-<mt:var name="type" escape="html">"><mt:var name="service" escape="html"></span>
</td>
<td class="date">
<span title="<mt:var name="created_on_time_formatted">">
<mt:if name="dates_relative">
<mt:var name="created_on_relative">
<mt:else>
<mt:var name="created_on_formatted">
</mt:if>
</span>
</td>
<td class="view si status-view">
<mt:if name="url">
<a href="<mt:var name="url" escape="html">" target="<__trans phrase="_external_link_target">" title="<__trans phrase="View action link">"><img src="<mt:var name="static_uri">images/spacer.gif" alt="<__trans phrase="View action link">" width="13" height="9" /></a>
<mt:else>
 
</mt:if>
</td>
</tr>
</mtapp:listing>
<mt:include name="include/footer.tmpl">
diff --git a/plugins/ActionStreams/tmpl/other_profiles.tmpl b/plugins/ActionStreams/tmpl/other_profiles.tmpl
index af50e88..b969c59 100644
--- a/plugins/ActionStreams/tmpl/other_profiles.tmpl
+++ b/plugins/ActionStreams/tmpl/other_profiles.tmpl
@@ -1,129 +1,129 @@
<mt:setvar name="edit_author" value="1">
<mt:setvar name="other_profiles" value="1">
-<mt:setvarblock name="page_title"><__trans phrase="Other Profiles"></mt:setvarblock>
+<mt:setvarblock name="page_title"><__trans phrase="Other Profiles for [_1]" params="<mt:Var name="edit_author_name">"></mt:setvarblock>
<mt:setvarblock name="html_head" append="1">
<link rel="stylesheet" type="text/css" href="<mt:var name="static_uri">plugins/ActionStreams/css/action-streams.css" />
<style type="text/css">
.content-nav #main-content .msg { margin-left: 0px; }
#main-content {
padding-top:5px;
}
<mt:loop name="service_styles">
.service-<mt:var name="service_type"> { background-image: url(<mt:var name="service_icon">); }
</mt:loop>
</style>
<script type="text/javascript">
<!--
function verifyDelete( delete_item ){
conf = confirm( "Are you sure you want to delete " + delete_item + "?" );
if ( conf ) {
return true;
}
return false;
}
var tableSelect;
function init() {
// set up table select awesomeness
tableSelect = new TC.TableSelect("profile-listing-table");
tableSelect.rowSelect = true;
}
TC.attachLoadEvent(init);
// -->
</script>
</mt:setvarblock>
<mt:setvarblock name="system_msg">
<mt:if name="added">
<mtapp:statusmsg
id="added"
class="success">
<__trans phrase="The selected profile was added.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="removed">
<mtapp:statusmsg
id="removed"
class="success">
<__trans phrase="The selected profiles were removed.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="updated">
<mtapp:statusmsg
id="updated"
class="success">
<__trans phrase="The selected profiles were scanned for updates.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="edited">
<mtapp:statusmsg
id="edited"
class="success">
<__trans phrase="The changes to the profile have been saved.">
</mtapp:statusmsg>
</mt:if>
</mt:setvarblock>
<mt:setvarblock name="content_nav">
<mt:include name="include/users_content_nav.tmpl">
</mt:setvarblock>
<mt:setvarblock name="content_header">
<ul class="action-link-list">
<li>
<a href="javascript:void(0)" onclick="return openDialog(this.form, 'dialog_add_profile', 'author_id=<mt:var name="edit_author_id">&return_args=<mt:var name="return_args" escape="url">%26author_id=<mt:var name="edit_author_id">')" class="icon-left icon-create"><__trans phrase="Add Profile"></a>
</li>
</ul>
</mt:setvarblock>
<mt:setvarblock name="action_buttons">
<a href="javascript:void(0)"
onclick="doRemoveItems(getByID('profile-listing-form'), '<__trans phrase="profile">', '<__trans phrase="profiles">', null, null, { mode: 'remove_other_profile' }); return false"
accesskey="x"
title="<__trans phrase="Delete selected profiles (x)">"
><__trans phrase="Delete"></a>
<a href="javascript:void(0)"
onclick="doForMarkedInThisWindow(getByID('profile-listing-form'), '<__trans phrase="profile">', '<__trans phrase="profiles">', 'id', 'itemset_update_profiles'); return false"
title="<__trans phrase="Scan now for new actions">"
><__trans phrase="Update Now"></a>
</mt:setvarblock>
<mt:var name="position_actions_top" value="1">
<mt:include name="include/header.tmpl">
<mtapp:listing type="profile" loop="profiles" empty_message="No profiles were found." hide_pager="1">
<mt:if __first__>
<thead>
<tr>
<th class="cb"><input type="checkbox" name="id-head" value="all" class="select" /></th>
<th class="service"><span class="service-icon"><__trans phrase="Service"></span></th>
<th class="userid"><__trans phrase="Username"></th>
<th class="view"><__trans phrase="View"></th>
</tr>
</thead>
<tbody>
</mt:if>
<tr class="<mt:if __odd__>odd<mt:else>even</mt:if>">
<td class="cb"><input type="checkbox" name="id" class="select" value="<mt:var name="edit_author_id" escape="html">:<mt:var name="type" escape="html">:<mt:var name="ident" escape="html">" /></td>
<td class="service network"><span class="service-icon service-<mt:var name="type">"><a href="javascript:void(0)" onclick="return openDialog(this.form, 'dialog_edit_profile', 'author_id=<mt:var name="edit_author_id">&profile_type=<mt:var name="type" escape="url">&profile_ident=<mt:var name="ident" escape="url">&return_args=<mt:var name="return_args" escape="url">%26author_id=<mt:var name="edit_author_id">')"><mt:var name="label" escape="html"></a></span></td>
<td class="userid"><mt:var name="ident" escape="html"></td>
<td class="view si status-view">
<a href="<mt:var name="uri" escape="html">" target="<__trans phrase="external_link_target">" title="<__trans phrase="View Profile">"><img src="<mt:var name="static_uri">images/spacer.gif" alt="<__trans phrase="View Profile">" width="13" height="9" /></a>
</td>
</tr>
<mt:if __last__>
</tbody>
</mt:if>
</mtapp:listing>
<mt:include name="include/footer.tmpl">
|
markpasc/mt-plugin-action-streams
|
016353090288e4bff0660cc9b72f7718aed0e055
|
Refactored author loading code in preparation for fixing bugzid:92089. Now all methods in ActionStreams::Plugin use the method _edit_author() to load the author and check permissions. Upon failure, it returns standard, already-localized MT error messages. (This is a rework of the same commit contained in r1432 and reverted in r1442. Found many other methods which used the same code I've now refactored)
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
index e0d1c92..313fa57 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
@@ -1,711 +1,706 @@
package ActionStreams::Plugin;
use strict;
use warnings;
use Carp qw( croak );
use MT::Util qw( relative_date offset_time epoch2ts ts2epoch format_ts );
sub users_content_nav {
my ($cb, $app, $html_ref) = @_;
return unless $app->param('id');
$$html_ref =~ s{class=["']active["']}{}xmsg
if $app->mode eq 'list_profileevent' || $app->mode eq 'other_profiles';
$$html_ref =~ m{ "> ((?:<b>)?) <__trans \s phrase="Permissions"> ((?:</b>)?) </a> }xms;
my ($open_bold, $close_bold) = ($1, $2);
my $html = <<"EOF";
<mt:if var="USER_VIEW">
<li><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">">$open_bold<__trans phrase="Other Profiles">$close_bold</a></li>
<li><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">">$open_bold<__trans phrase="Action Stream">$close_bold</a></li>
</mt:if>
<mt:if var="edit_author">
<li<mt:if name="other_profiles"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="id" escape="url">">$open_bold<__trans phrase="Other Profiles">$close_bold</a></li>
<li<mt:if name="list_profileevent"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="id" escape="url">">$open_bold<__trans phrase="Action Stream">$close_bold</a></li>
</mt:if>
EOF
$$html_ref =~ s{(?=</ul>)}{$html}xmsg;
}
sub icon_url_for_service {
my $class = shift;
my ($type, $ndata) = @_;
my $plug = $ndata->{plugin} or return;
my $icon_url;
if ($ndata->{icon} && $ndata->{icon} =~ m{ \A \w:// }xms) {
$icon_url = $ndata->{icon};
}
elsif ($ndata->{icon}) {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
$ndata->{icon};
}
elsif ($plug->id eq 'actionstreams') {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
'images', 'services', $type . '.png';
}
return $icon_url;
}
+sub _edit_author {
+ my $arg = 'HASH' eq ref($_[0]) ? shift : { id => shift };
+
+ my $app = MT->instance;
+ my $trans_error = sub {
+ return $app->error($app->translate(@_)) unless $arg->{no_error};
+ };
+
+ $arg->{id} or return $trans_error->('No id');
+
+ my $class = MT->model('author');
+ my $author = $class->load( $arg->{id} )
+ or return $trans_error->("No such [_1].", lc( $class->class_label ));
+
+ return $trans_error->("Permission denied.")
+ if ! $app->user
+ or $app->user->id != $arg->{id} && !$app->user->is_superuser();
+
+ return $author;
+}
+
sub list_profileevent {
my $app = shift;
my %param = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
- my $author_id = $app->param('id')
- or return;
- return $app->error('Not permitted to view')
- if $app->user->id != $author_id && !$app->user->is_superuser();
+ my $author = _edit_author( $app->param('id') ) or return;
my %service_styles;
my @service_styles_loop;
my $code = sub {
my ($event, $row) = @_;
my @meta_col = keys %{ $event->properties->{meta_columns} || {} };
$row->{$_} = $event->{$_} for @meta_col;
$row->{as_html} = $event->as_html();
my ($service, $stream_id) = split /_/, $row->{class}, 2;
$row->{type} = $service;
my $nets = $app->registry('profile_services') || {};
my $net = $nets->{$service};
$row->{service} = $net->{name} if $net;
$row->{url} = $event->url;
if (!$service_styles{$service}) {
if (!$net->{plugin} || $net->{plugin}->id ne 'actionstreams') {
if (my $icon = __PACKAGE__->icon_url_for_service($service, $net)) {
push @service_styles_loop, {
service_type => $service,
service_icon => $icon,
};
}
}
$service_styles{$service} = 1;
}
my $ts = $row->{created_on};
$row->{created_on_relative} = relative_date($ts, time);
$row->{created_on_formatted} = format_ts(
MT::App::CMS->LISTING_DATETIME_FORMAT(),
epoch2ts(undef, offset_time(ts2epoch(undef, $ts))),
undef,
$app->user ? $app->user->preferred_language : undef,
);
};
# Make sure all classes are loaded.
require ActionStreams::Event;
for my $prevt (keys %{ $app->registry('action_streams') }) {
ActionStreams::Event->classes_for_type($prevt);
}
my $plugin = MT->component('ActionStreams');
my %params = map { $_ => $app->param($_) ? 1 : 0 }
qw( saved_deleted hidden shown );
$params{services} = [];
my $services = $app->registry('profile_services');
while (my ($prevt, $service) = each %$services) {
push @{ $params{services} }, {
service_id => $prevt,
service_name => $service->{name},
};
}
$params{services} = [ sort { lc $a->{service_name} cmp lc $b->{service_name} } @{ $params{services} } ];
my %terms = (
class => '*',
- author_id => $author_id,
+ author_id => $author->id,
);
my %args = (
sort => 'created_on',
direction => 'descend',
);
if (my $filter = $app->param('filter')) {
$params{filter_key} = $filter;
my $filter_val = $params{filter_val} = $app->param('filter_val');
if ($filter eq 'service') {
$params{filter_label} = $app->translate('Actions from the service [_1]', $app->registry('profile_services')->{$filter_val}->{name});
$terms{class} = $filter_val . '_%';
$args{like} = { class => 1 };
}
elsif ($filter eq 'visible') {
$params{filter_label} = ($filter_val eq 'show') ? 'Actions that are shown'
: 'Actions that are hidden';
$terms{visible} = $filter_val eq 'show' ? 1 : 0;
}
}
- $params{id} = $params{edit_author_id} = $author_id;
+ $params{id} = $params{edit_author_id} = $author->id;
$params{service_styles} = \@service_styles_loop;
$app->listing({
type => 'profileevent',
terms => \%terms,
args => \%args,
listing_screen => 1,
code => $code,
template => $plugin->load_tmpl('list_profileevent.tmpl'),
params => \%params,
});
}
sub itemset_hide_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(0);
$event->save;
}
$app->add_return_arg( hidden => 1 );
$app->call_return;
}
sub itemset_show_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(1);
$event->save;
}
$app->add_return_arg( shown => 1 );
$app->call_return;
}
sub _itemset_hide_show_all_events {
my ($app, $new_visible) = @_;
$app->validate_magic or return;
my $event_class = MT->model('profileevent');
# Really we should work directly from the selected author ID, but as an
# itemset event we only got some event IDs. So use its.
my ($event_id) = $app->param('id');
my $event = $event_class->load($event_id)
or return $app->error($app->translate('No such event [_1]', $event_id));
- my $author_id = $event->author_id;
- return $app->error('Not permitted to modify')
- if $author_id != $app->user->id && !$app->user->is_superuser();
+ my $author = _edit_author( $event->author_id ) or return;
my $driver = $event_class->driver;
my $stmt = $driver->prepare_statement($event_class, {
# TODO: include filter value when we have filters
- author_id => $author_id,
+ author_id => $author->id,
visible => $new_visible ? 0 : 1,
});
my $sql = "UPDATE " . $driver->table_for($event_class) . " SET "
. $driver->dbd->db_column_name($event_class->datasource, 'visible')
. " = ? " . $stmt->as_sql_where;
# Work around error in MT::ObjectDriver::Driver::DBI::sql by doing it inline.
my $dbh = $driver->rw_handle;
$dbh->do($sql, {}, $new_visible, @{ $stmt->{bind} })
or return $app->error($dbh->errstr);
return 1;
}
sub itemset_hide_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 0) or return;
$app->add_return_arg( all_hidden => 1 );
$app->call_return;
}
sub itemset_show_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 1) or return;
$app->add_return_arg( all_shown => 1 );
$app->call_return;
}
sub _build_service_data {
my %info = @_;
my ($networks, $streams, $author) = @info{qw( networks streams author )};
my (@service_styles_loop, @networks);
my %has_profiles;
if ($author) {
my $other_profiles = $author->other_profiles();
$has_profiles{$_->{type}} = 1 for @$other_profiles;
}
my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
keys %$networks;
TYPE: for my $type (@network_keys) {
my $ndata = $networks->{$type}
or next TYPE;
my @streams;
if ($streams) {
my $streamdata = $streams->{$type} || {};
@streams =
sort { lc $a->{name} cmp lc $b->{name} }
grep { grep { $_ } @$_{qw( class scraper xpath rss atom )} }
map { +{ stream => $_, %{ $streamdata->{$_} } } }
grep { $_ ne 'plugin' }
keys %$streamdata;
}
my $ret = {
type => $type,
%$ndata,
label => $ndata->{name},
user_has_account => ($has_profiles{$type} ? 1 : 0),
};
$ret->{streams} = \@streams if @streams;
push @networks, $ret;
if (!$ndata->{plugin} || $ndata->{plugin}->id ne 'actionstreams') {
push @service_styles_loop, {
service_type => $type,
service_icon => __PACKAGE__->icon_url_for_service($type, $ndata),
};
}
}
return (
service_styles => \@service_styles_loop,
networks => \@networks,
);
}
sub other_profiles {
my( $app ) = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
- my $author_id = $app->param('id')
- or return $app->error('Author id is required');
- my $user = MT->model('author')->load($author_id)
- or return $app->error('Author id is invalid');
- return $app->error('Not permitted to view')
- if $app->user->id != $author_id && !$app->user->is_superuser();
+ my $author = _edit_author( $app->param('id') ) or return;
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl( 'other_profiles.tmpl' );
my @profiles = sort { lc $a->{label} cmp lc $b->{label} }
- @{ $user->other_profiles || [] };
+ @{ $author->other_profiles || [] };
my %messages = map { $_ => $app->param($_) ? 1 : 0 }
(qw( added removed updated edited ));
return $app->build_page( $tmpl, {
- id => $user->id,
- edit_author_id => $user->id,
+ id => $author->id,
+ edit_author_id => $author->id,
profiles => \@profiles,
listing_screen => 1,
_build_service_data(
networks => $app->registry('profile_services'),
),
%messages,
} );
}
sub dialog_add_edit_profile {
my ($app) = @_;
- return $app->error('Not permitted to view')
- if $app->user->id != $app->param('author_id') && !$app->user->is_superuser();
- my $author = MT->model('author')->load($app->param('author_id'))
- or return $app->error('No such author [_1]', $app->param('author_id'));
+ my $author = _edit_author( $app->param('author_id') ) or return;
my %edit_profile;
my $tmpl_name = 'dialog_add_profile.tmpl';
if (my $edit_type = $app->param('profile_type')) {
my $ident = $app->param('profile_ident') || q{};
my ($profile) = grep { $_->{ident} eq $ident }
@{ $author->other_profiles($edit_type) };
%edit_profile = (
edit_type => $edit_type,
edit_type_name => $app->registry('profile_services', $edit_type, 'name'),
edit_ident => $ident,
edit_streams => $profile->{streams} || [],
);
$tmpl_name = 'dialog_edit_profile.tmpl';
}
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl($tmpl_name);
return $app->build_page($tmpl, {
- edit_author_id => $app->param('author_id'),
+ edit_author_id => $author->id,
_build_service_data(
networks => $app->registry('profile_services'),
streams => $app->registry('action_streams'),
author => $author,
),
%edit_profile,
});
}
sub edit_other_profile {
my $app = shift;
$app->validate_magic() or return;
- my $author_id = $app->param('author_id')
- or return $app->error('Author id is required');
- my $user = MT->model('author')->load($author_id)
- or return $app->error('Author id is invalid');
- return $app->error('Not permitted to edit')
- if $app->user->id != $author_id && !$app->user->is_superuser();
-
- my $type = $app->param('profile_type');
+ my $author = _edit_author( $app->param('author_id') ) or return;
+ my $type = $app->param('profile_type');
my $orig_ident = $app->param('original_ident');
- $user->remove_profile($type, $orig_ident);
+ $author->remove_profile($type, $orig_ident);
$app->forward('add_other_profile', success_msg => 'edited');
}
sub add_other_profile {
my $app = shift;
my %param = @_;
$app->validate_magic or return;
- my $author_id = $app->param('author_id')
- or return $app->error('Author id is required');
- my $user = MT->model('author')->load($author_id)
- or return $app->error('Author id is invalid');
- return $app->error('Not permitted to add')
- if $app->user->id != $author_id && !$app->user->is_superuser();
+ my $author = _edit_author( $app->param('author_id') ) or return;
my( $ident, $uri, $label, $type );
if ( $type = $app->param( 'profile_type' ) ) {
my $reg = $app->registry('profile_services');
my $network = $reg->{$type}
or croak "Unknown network $type";
$label = $network->{name} . ' Profile';
$ident = $app->param( 'profile_id' );
$ident =~ s{ \A \s* }{}xms;
$ident =~ s{ \s* \z }{}xms;
# Check for full URLs.
if (!$network->{ident_exact}) {
my $url_pattern = $network->{url};
my ($pre_ident, $post_ident) = split /(?:\%s|\Q{{ident}}\E)/, $url_pattern, 2;
$pre_ident =~ s{ \A http:// }{}xms;
$post_ident =~ s{ / \z }{}xms;
if ($ident =~ m{ \A (?:http://)? \Q$pre_ident\E (.*?) \Q$post_ident\E /? \z }xms) {
$ident = $1;
}
}
$uri = $network->{url};
$uri =~ s{ (?:\%s|\Q{{ident}}\E) }{$ident}xmsg;
} else {
$ident = $uri = $app->param( 'profile_uri' );
$label = $app->param( 'profile_label' );
$type = 'website';
}
my $profile = {
type => $type,
ident => $ident,
label => $label,
uri => $uri,
};
my %streams = map { join(q{_}, $type, $_) => 1 }
grep { $_ ne 'plugin' && $app->param(join q{_}, 'stream', $type, $_) }
keys %{ $app->registry('action_streams', $type) || {} };
$profile->{streams} = \%streams if %streams;
- $app->run_callbacks('pre_add_profile.' . $type, $app, $user, $profile);
- $user->add_profile($profile);
- $app->run_callbacks('post_add_profile.' . $type, $app, $user, $profile);
+ $app->run_callbacks('pre_add_profile.' . $type, $app, $author, $profile);
+ $author->add_profile($profile);
+ $app->run_callbacks('post_add_profile.' . $type, $app, $author, $profile);
my $success_msg = $param{success_msg} || 'added';
return $app->redirect($app->uri(
mode => 'other_profiles',
- args => { id => $author_id, $success_msg => 1 },
+ args => { id => $author->id, $success_msg => 1 },
));
}
sub remove_other_profile {
my( $app ) = @_;
$app->validate_magic or return;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
- my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
- or next PROFILE;
- next PROFILE
- if $app->user->id != $author_id && !$app->user->is_superuser();
+ $users{$author_id} ||= _edit_author({ id => $author_id,
+ no_error => 1 });
+ my $author = $users{$author_id} or next PROFILE;
- $app->run_callbacks('pre_remove_profile.' . $type, $app, $user, $type, $ident);
- $user->remove_profile( $type, $ident );
- $app->run_callbacks('post_remove_profile.' . $type, $app, $user, $type, $ident);
+ $app->run_callbacks('pre_remove_profile.' . $type, $app, $author, $type, $ident);
+ $author->remove_profile( $type, $ident );
+ $app->run_callbacks('post_remove_profile.' . $type, $app, $author, $type, $ident);
$page_author_id = $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), removed => 1 },
));
}
sub profile_add_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
$app->param('author_id', $user->id);
my $type = $app->param('profile_type')
or return $app->error( $app->translate("Invalid request.") );
# The profile side interface doesn't have stream selection, so select
# them all by default.
# TODO: factor out the adding logic (and parameterize stream selection) to stop faking params
foreach my $stream ( keys %{ $app->registry('action_streams', $type) || {} } ) {
next if $stream eq 'plugin';
$app->param(join('_', 'stream', $type, $stream), 1);
}
add_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub profile_first_update_events {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub profile_delete_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
# TODO: factor out this logic instead of having to fake params
my $id = scalar $app->param('id');
$id = $user->id . ':' . $id;
$app->param('id', $id);
remove_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub itemset_update_profiles {
my $app = shift;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
- my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
- or next PROFILE;
- next PROFILE
- if $app->user->id != $author_id && !$app->user->is_superuser();
+ $users{$author_id} ||= _edit_author({ id => $author_id,
+ no_error => 1 });
+ my $author = $users{$author_id} or next PROFILE;
- my $profiles = $user->other_profiles($type);
+ my $profiles = $author->other_profiles($type);
if (!$profiles) {
next PROFILE;
}
my @profiles = grep { $_->{ident} eq $ident } @$profiles;
for my $author_profile (@profiles) {
- update_events_for_profile($user, $author_profile,
+ update_events_for_profile($author, $author_profile,
synchronous => 1);
}
$page_author_id ||= $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), updated => 1 },
));
}
sub first_profile_update {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub rebuild_action_stream_blogs {
my ($cb, $app) = @_;
my $plugin = MT->component('ActionStreams');
my $pd_iter = MT->model('plugindata')->load_iter({
plugin => $plugin->key,
key => { like => 'configuration:blog:%' }
});
my %rebuild;
while ( my $pd = $pd_iter->() ) {
next unless $pd->data('rebuild_for_action_stream_events');
my ($blog_id) = $pd->key =~ m/:blog:(\d+)$/;
$rebuild{$blog_id} = 1;
}
for my $blog_id (keys %rebuild) {
# TODO: limit this to indexes that publish action stream data, once
# we can magically infer template content before building it
my $blog = MT->model('blog')->load( $blog_id ) or next;
# Republish all the blog's known non-virtual index fileinfos that
# have real template objects.
my $finfo_class = MT->model('fileinfo');
my $finfo_template_col = $finfo_class->driver->dbd->db_column_name(
$finfo_class->datasource, 'template_id');
my @fileinfos = $finfo_class->load({
blog_id => $blog->id,
archive_type => 'index',
virtual => [ \'IS NULL', 0 ],
}, {
join => MT->model('template')->join_on(undef,
{ id => \"= $finfo_template_col" }),
});
require MT::TheSchwartz;
require TheSchwartz::Job;
for my $fi (@fileinfos) {
my $job = TheSchwartz::Job->new();
$job->funcname('MT::Worker::Publish');
$job->uniqkey($fi->id);
$job->run_after(time + 240); # 4 minutes
MT::TheSchwartz->insert($job);
}
}
}
sub widget_recent {
my ($app, $tmpl, $widget_param) = @_;
$tmpl->param('author_id', $app->user->id);
$tmpl->param('blog_id', $app->blog->id) if $app->blog;
}
sub widget_blog_dashboard_only {
my ($page, $scope) = @_;
return if $scope eq 'dashboard:system';
return 1;
}
sub update_events {
my $mt = MT->app;
$mt->run_callbacks('pre_action_streams_task', $mt);
my $au_class = MT->model('author');
my $author_iter = $au_class->search({
status => $au_class->ACTIVE(),
}, {
join => [ $au_class->meta_pkg, 'author_id', { type => 'other_profiles' } ],
});
while (my $author = $author_iter->()) {
my $profiles = $author->other_profiles();
$mt->run_callbacks('pre_update_action_streams', $mt, $author, $profiles);
PROFILE: for my $profile (@$profiles) {
update_events_for_profile($author, $profile);
}
$mt->run_callbacks('post_update_action_streams', $mt, $author, $profiles);
}
$mt->run_callbacks('post_action_streams_task', $mt);
}
sub update_events_for_profile {
my ($author, $profile, %param) = @_;
my $type = $profile->{type};
my $streams = $profile->{streams};
return if !$streams || !%$streams;
require ActionStreams::Event;
my @event_classes = ActionStreams::Event->classes_for_type($type)
or return;
my $mt = MT->app;
$mt->run_callbacks('pre_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
EVENTCLASS: for my $event_class (@event_classes) {
next EVENTCLASS if !$streams->{$event_class->class_type};
if ($param{synchronous}) {
$event_class->update_events_loggily(
author => $author,
hide_timeless => $param{hide_timeless} ? 1 : 0,
%$profile,
);
}
else {
# Defer regular updates to job workers.
require ActionStreams::Worker;
ActionStreams::Worker->make_work(
event_class => $event_class,
author => $author,
%$profile,
);
}
}
$mt->run_callbacks('post_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
}
1;
|
markpasc/mt-plugin-action-streams
|
63d7a6a73f945772365fd5a56342a98f25d4b068
|
Fixing error thrown when selecting show/hide all from the action stream events dropdown menu: 'Can't locate object method "is_superuser" via package "MT::App::CMS"' bugzid:91768
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
index 86412c2..e0d1c92 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
@@ -1,711 +1,711 @@
package ActionStreams::Plugin;
use strict;
use warnings;
use Carp qw( croak );
use MT::Util qw( relative_date offset_time epoch2ts ts2epoch format_ts );
sub users_content_nav {
my ($cb, $app, $html_ref) = @_;
return unless $app->param('id');
$$html_ref =~ s{class=["']active["']}{}xmsg
if $app->mode eq 'list_profileevent' || $app->mode eq 'other_profiles';
$$html_ref =~ m{ "> ((?:<b>)?) <__trans \s phrase="Permissions"> ((?:</b>)?) </a> }xms;
my ($open_bold, $close_bold) = ($1, $2);
my $html = <<"EOF";
<mt:if var="USER_VIEW">
<li><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">">$open_bold<__trans phrase="Other Profiles">$close_bold</a></li>
<li><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">">$open_bold<__trans phrase="Action Stream">$close_bold</a></li>
</mt:if>
<mt:if var="edit_author">
<li<mt:if name="other_profiles"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="id" escape="url">">$open_bold<__trans phrase="Other Profiles">$close_bold</a></li>
<li<mt:if name="list_profileevent"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="id" escape="url">">$open_bold<__trans phrase="Action Stream">$close_bold</a></li>
</mt:if>
EOF
$$html_ref =~ s{(?=</ul>)}{$html}xmsg;
}
sub icon_url_for_service {
my $class = shift;
my ($type, $ndata) = @_;
my $plug = $ndata->{plugin} or return;
my $icon_url;
if ($ndata->{icon} && $ndata->{icon} =~ m{ \A \w:// }xms) {
$icon_url = $ndata->{icon};
}
elsif ($ndata->{icon}) {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
$ndata->{icon};
}
elsif ($plug->id eq 'actionstreams') {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
'images', 'services', $type . '.png';
}
return $icon_url;
}
sub list_profileevent {
my $app = shift;
my %param = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
my $author_id = $app->param('id')
or return;
return $app->error('Not permitted to view')
if $app->user->id != $author_id && !$app->user->is_superuser();
my %service_styles;
my @service_styles_loop;
my $code = sub {
my ($event, $row) = @_;
my @meta_col = keys %{ $event->properties->{meta_columns} || {} };
$row->{$_} = $event->{$_} for @meta_col;
$row->{as_html} = $event->as_html();
my ($service, $stream_id) = split /_/, $row->{class}, 2;
$row->{type} = $service;
my $nets = $app->registry('profile_services') || {};
my $net = $nets->{$service};
$row->{service} = $net->{name} if $net;
$row->{url} = $event->url;
if (!$service_styles{$service}) {
if (!$net->{plugin} || $net->{plugin}->id ne 'actionstreams') {
if (my $icon = __PACKAGE__->icon_url_for_service($service, $net)) {
push @service_styles_loop, {
service_type => $service,
service_icon => $icon,
};
}
}
$service_styles{$service} = 1;
}
my $ts = $row->{created_on};
$row->{created_on_relative} = relative_date($ts, time);
$row->{created_on_formatted} = format_ts(
MT::App::CMS->LISTING_DATETIME_FORMAT(),
epoch2ts(undef, offset_time(ts2epoch(undef, $ts))),
undef,
$app->user ? $app->user->preferred_language : undef,
);
};
# Make sure all classes are loaded.
require ActionStreams::Event;
for my $prevt (keys %{ $app->registry('action_streams') }) {
ActionStreams::Event->classes_for_type($prevt);
}
my $plugin = MT->component('ActionStreams');
my %params = map { $_ => $app->param($_) ? 1 : 0 }
qw( saved_deleted hidden shown );
$params{services} = [];
my $services = $app->registry('profile_services');
while (my ($prevt, $service) = each %$services) {
push @{ $params{services} }, {
service_id => $prevt,
service_name => $service->{name},
};
}
$params{services} = [ sort { lc $a->{service_name} cmp lc $b->{service_name} } @{ $params{services} } ];
my %terms = (
class => '*',
author_id => $author_id,
);
my %args = (
sort => 'created_on',
direction => 'descend',
);
if (my $filter = $app->param('filter')) {
$params{filter_key} = $filter;
my $filter_val = $params{filter_val} = $app->param('filter_val');
if ($filter eq 'service') {
$params{filter_label} = $app->translate('Actions from the service [_1]', $app->registry('profile_services')->{$filter_val}->{name});
$terms{class} = $filter_val . '_%';
$args{like} = { class => 1 };
}
elsif ($filter eq 'visible') {
$params{filter_label} = ($filter_val eq 'show') ? 'Actions that are shown'
: 'Actions that are hidden';
$terms{visible} = $filter_val eq 'show' ? 1 : 0;
}
}
$params{id} = $params{edit_author_id} = $author_id;
$params{service_styles} = \@service_styles_loop;
$app->listing({
type => 'profileevent',
terms => \%terms,
args => \%args,
listing_screen => 1,
code => $code,
template => $plugin->load_tmpl('list_profileevent.tmpl'),
params => \%params,
});
}
sub itemset_hide_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(0);
$event->save;
}
$app->add_return_arg( hidden => 1 );
$app->call_return;
}
sub itemset_show_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(1);
$event->save;
}
$app->add_return_arg( shown => 1 );
$app->call_return;
}
sub _itemset_hide_show_all_events {
my ($app, $new_visible) = @_;
$app->validate_magic or return;
my $event_class = MT->model('profileevent');
# Really we should work directly from the selected author ID, but as an
# itemset event we only got some event IDs. So use its.
my ($event_id) = $app->param('id');
my $event = $event_class->load($event_id)
or return $app->error($app->translate('No such event [_1]', $event_id));
my $author_id = $event->author_id;
return $app->error('Not permitted to modify')
- if $author_id != $app->user->id && !$app->is_superuser();
+ if $author_id != $app->user->id && !$app->user->is_superuser();
my $driver = $event_class->driver;
my $stmt = $driver->prepare_statement($event_class, {
# TODO: include filter value when we have filters
author_id => $author_id,
visible => $new_visible ? 0 : 1,
});
my $sql = "UPDATE " . $driver->table_for($event_class) . " SET "
. $driver->dbd->db_column_name($event_class->datasource, 'visible')
. " = ? " . $stmt->as_sql_where;
# Work around error in MT::ObjectDriver::Driver::DBI::sql by doing it inline.
my $dbh = $driver->rw_handle;
$dbh->do($sql, {}, $new_visible, @{ $stmt->{bind} })
or return $app->error($dbh->errstr);
return 1;
}
sub itemset_hide_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 0) or return;
$app->add_return_arg( all_hidden => 1 );
$app->call_return;
}
sub itemset_show_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 1) or return;
$app->add_return_arg( all_shown => 1 );
$app->call_return;
}
sub _build_service_data {
my %info = @_;
my ($networks, $streams, $author) = @info{qw( networks streams author )};
my (@service_styles_loop, @networks);
my %has_profiles;
if ($author) {
my $other_profiles = $author->other_profiles();
$has_profiles{$_->{type}} = 1 for @$other_profiles;
}
my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
keys %$networks;
TYPE: for my $type (@network_keys) {
my $ndata = $networks->{$type}
or next TYPE;
my @streams;
if ($streams) {
my $streamdata = $streams->{$type} || {};
@streams =
sort { lc $a->{name} cmp lc $b->{name} }
grep { grep { $_ } @$_{qw( class scraper xpath rss atom )} }
map { +{ stream => $_, %{ $streamdata->{$_} } } }
grep { $_ ne 'plugin' }
keys %$streamdata;
}
my $ret = {
type => $type,
%$ndata,
label => $ndata->{name},
user_has_account => ($has_profiles{$type} ? 1 : 0),
};
$ret->{streams} = \@streams if @streams;
push @networks, $ret;
if (!$ndata->{plugin} || $ndata->{plugin}->id ne 'actionstreams') {
push @service_styles_loop, {
service_type => $type,
service_icon => __PACKAGE__->icon_url_for_service($type, $ndata),
};
}
}
return (
service_styles => \@service_styles_loop,
networks => \@networks,
);
}
sub other_profiles {
my( $app ) = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
my $author_id = $app->param('id')
or return $app->error('Author id is required');
my $user = MT->model('author')->load($author_id)
or return $app->error('Author id is invalid');
return $app->error('Not permitted to view')
if $app->user->id != $author_id && !$app->user->is_superuser();
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl( 'other_profiles.tmpl' );
my @profiles = sort { lc $a->{label} cmp lc $b->{label} }
@{ $user->other_profiles || [] };
my %messages = map { $_ => $app->param($_) ? 1 : 0 }
(qw( added removed updated edited ));
return $app->build_page( $tmpl, {
id => $user->id,
edit_author_id => $user->id,
profiles => \@profiles,
listing_screen => 1,
_build_service_data(
networks => $app->registry('profile_services'),
),
%messages,
} );
}
sub dialog_add_edit_profile {
my ($app) = @_;
return $app->error('Not permitted to view')
if $app->user->id != $app->param('author_id') && !$app->user->is_superuser();
my $author = MT->model('author')->load($app->param('author_id'))
or return $app->error('No such author [_1]', $app->param('author_id'));
my %edit_profile;
my $tmpl_name = 'dialog_add_profile.tmpl';
if (my $edit_type = $app->param('profile_type')) {
my $ident = $app->param('profile_ident') || q{};
my ($profile) = grep { $_->{ident} eq $ident }
@{ $author->other_profiles($edit_type) };
%edit_profile = (
edit_type => $edit_type,
edit_type_name => $app->registry('profile_services', $edit_type, 'name'),
edit_ident => $ident,
edit_streams => $profile->{streams} || [],
);
$tmpl_name = 'dialog_edit_profile.tmpl';
}
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl($tmpl_name);
return $app->build_page($tmpl, {
edit_author_id => $app->param('author_id'),
_build_service_data(
networks => $app->registry('profile_services'),
streams => $app->registry('action_streams'),
author => $author,
),
%edit_profile,
});
}
sub edit_other_profile {
my $app = shift;
$app->validate_magic() or return;
my $author_id = $app->param('author_id')
or return $app->error('Author id is required');
my $user = MT->model('author')->load($author_id)
or return $app->error('Author id is invalid');
return $app->error('Not permitted to edit')
if $app->user->id != $author_id && !$app->user->is_superuser();
my $type = $app->param('profile_type');
my $orig_ident = $app->param('original_ident');
$user->remove_profile($type, $orig_ident);
$app->forward('add_other_profile', success_msg => 'edited');
}
sub add_other_profile {
my $app = shift;
my %param = @_;
$app->validate_magic or return;
my $author_id = $app->param('author_id')
or return $app->error('Author id is required');
my $user = MT->model('author')->load($author_id)
or return $app->error('Author id is invalid');
return $app->error('Not permitted to add')
if $app->user->id != $author_id && !$app->user->is_superuser();
my( $ident, $uri, $label, $type );
if ( $type = $app->param( 'profile_type' ) ) {
my $reg = $app->registry('profile_services');
my $network = $reg->{$type}
or croak "Unknown network $type";
$label = $network->{name} . ' Profile';
$ident = $app->param( 'profile_id' );
$ident =~ s{ \A \s* }{}xms;
$ident =~ s{ \s* \z }{}xms;
# Check for full URLs.
if (!$network->{ident_exact}) {
my $url_pattern = $network->{url};
my ($pre_ident, $post_ident) = split /(?:\%s|\Q{{ident}}\E)/, $url_pattern, 2;
$pre_ident =~ s{ \A http:// }{}xms;
$post_ident =~ s{ / \z }{}xms;
if ($ident =~ m{ \A (?:http://)? \Q$pre_ident\E (.*?) \Q$post_ident\E /? \z }xms) {
$ident = $1;
}
}
$uri = $network->{url};
$uri =~ s{ (?:\%s|\Q{{ident}}\E) }{$ident}xmsg;
} else {
$ident = $uri = $app->param( 'profile_uri' );
$label = $app->param( 'profile_label' );
$type = 'website';
}
my $profile = {
type => $type,
ident => $ident,
label => $label,
uri => $uri,
};
my %streams = map { join(q{_}, $type, $_) => 1 }
grep { $_ ne 'plugin' && $app->param(join q{_}, 'stream', $type, $_) }
keys %{ $app->registry('action_streams', $type) || {} };
$profile->{streams} = \%streams if %streams;
$app->run_callbacks('pre_add_profile.' . $type, $app, $user, $profile);
$user->add_profile($profile);
$app->run_callbacks('post_add_profile.' . $type, $app, $user, $profile);
my $success_msg = $param{success_msg} || 'added';
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => $author_id, $success_msg => 1 },
));
}
sub remove_other_profile {
my( $app ) = @_;
$app->validate_magic or return;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
or next PROFILE;
next PROFILE
if $app->user->id != $author_id && !$app->user->is_superuser();
$app->run_callbacks('pre_remove_profile.' . $type, $app, $user, $type, $ident);
$user->remove_profile( $type, $ident );
$app->run_callbacks('post_remove_profile.' . $type, $app, $user, $type, $ident);
$page_author_id = $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), removed => 1 },
));
}
sub profile_add_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
$app->param('author_id', $user->id);
my $type = $app->param('profile_type')
or return $app->error( $app->translate("Invalid request.") );
# The profile side interface doesn't have stream selection, so select
# them all by default.
# TODO: factor out the adding logic (and parameterize stream selection) to stop faking params
foreach my $stream ( keys %{ $app->registry('action_streams', $type) || {} } ) {
next if $stream eq 'plugin';
$app->param(join('_', 'stream', $type, $stream), 1);
}
add_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub profile_first_update_events {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub profile_delete_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
# TODO: factor out this logic instead of having to fake params
my $id = scalar $app->param('id');
$id = $user->id . ':' . $id;
$app->param('id', $id);
remove_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub itemset_update_profiles {
my $app = shift;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
or next PROFILE;
next PROFILE
if $app->user->id != $author_id && !$app->user->is_superuser();
my $profiles = $user->other_profiles($type);
if (!$profiles) {
next PROFILE;
}
my @profiles = grep { $_->{ident} eq $ident } @$profiles;
for my $author_profile (@profiles) {
update_events_for_profile($user, $author_profile,
synchronous => 1);
}
$page_author_id ||= $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), updated => 1 },
));
}
sub first_profile_update {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub rebuild_action_stream_blogs {
my ($cb, $app) = @_;
my $plugin = MT->component('ActionStreams');
my $pd_iter = MT->model('plugindata')->load_iter({
plugin => $plugin->key,
key => { like => 'configuration:blog:%' }
});
my %rebuild;
while ( my $pd = $pd_iter->() ) {
next unless $pd->data('rebuild_for_action_stream_events');
my ($blog_id) = $pd->key =~ m/:blog:(\d+)$/;
$rebuild{$blog_id} = 1;
}
for my $blog_id (keys %rebuild) {
# TODO: limit this to indexes that publish action stream data, once
# we can magically infer template content before building it
my $blog = MT->model('blog')->load( $blog_id ) or next;
# Republish all the blog's known non-virtual index fileinfos that
# have real template objects.
my $finfo_class = MT->model('fileinfo');
my $finfo_template_col = $finfo_class->driver->dbd->db_column_name(
$finfo_class->datasource, 'template_id');
my @fileinfos = $finfo_class->load({
blog_id => $blog->id,
archive_type => 'index',
virtual => [ \'IS NULL', 0 ],
}, {
join => MT->model('template')->join_on(undef,
{ id => \"= $finfo_template_col" }),
});
require MT::TheSchwartz;
require TheSchwartz::Job;
for my $fi (@fileinfos) {
my $job = TheSchwartz::Job->new();
$job->funcname('MT::Worker::Publish');
$job->uniqkey($fi->id);
$job->run_after(time + 240); # 4 minutes
MT::TheSchwartz->insert($job);
}
}
}
sub widget_recent {
my ($app, $tmpl, $widget_param) = @_;
$tmpl->param('author_id', $app->user->id);
$tmpl->param('blog_id', $app->blog->id) if $app->blog;
}
sub widget_blog_dashboard_only {
my ($page, $scope) = @_;
return if $scope eq 'dashboard:system';
return 1;
}
sub update_events {
my $mt = MT->app;
$mt->run_callbacks('pre_action_streams_task', $mt);
my $au_class = MT->model('author');
my $author_iter = $au_class->search({
status => $au_class->ACTIVE(),
}, {
join => [ $au_class->meta_pkg, 'author_id', { type => 'other_profiles' } ],
});
while (my $author = $author_iter->()) {
my $profiles = $author->other_profiles();
$mt->run_callbacks('pre_update_action_streams', $mt, $author, $profiles);
PROFILE: for my $profile (@$profiles) {
update_events_for_profile($author, $profile);
}
$mt->run_callbacks('post_update_action_streams', $mt, $author, $profiles);
}
$mt->run_callbacks('post_action_streams_task', $mt);
}
sub update_events_for_profile {
my ($author, $profile, %param) = @_;
my $type = $profile->{type};
my $streams = $profile->{streams};
return if !$streams || !%$streams;
require ActionStreams::Event;
my @event_classes = ActionStreams::Event->classes_for_type($type)
or return;
my $mt = MT->app;
$mt->run_callbacks('pre_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
EVENTCLASS: for my $event_class (@event_classes) {
next EVENTCLASS if !$streams->{$event_class->class_type};
if ($param{synchronous}) {
$event_class->update_events_loggily(
author => $author,
hide_timeless => $param{hide_timeless} ? 1 : 0,
%$profile,
);
}
else {
# Defer regular updates to job workers.
require ActionStreams::Worker;
ActionStreams::Worker->make_work(
event_class => $event_class,
author => $author,
%$profile,
);
}
}
$mt->run_callbacks('post_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
}
1;
|
markpasc/mt-plugin-action-streams
|
0184370555195aa296b76686e41c58a15a162c4c
|
Fixed typos in POD bugzid:92087
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm
index 91cb31a..fb839d6 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm
@@ -34,765 +34,765 @@ __PACKAGE__->install_properties({
datasource => 'profileevent',
primary_key => 'id',
});
__PACKAGE__->install_meta({
columns => [ qw(
title
url
thumbnail
via
via_id
) ],
});
# Oracle does not like an identifier of more than 30 characters.
sub datasource {
my $class = shift;
my $r = MT->request;
my $ds = $r->cache('as_event_ds');
return $ds if $ds;
my $dss_oracle = qr/(db[id]::)?oracle/;
if ( my $type = MT->config('ObjectDriver') ) {
if ((lc $type) =~ m/^$dss_oracle$/) {
$ds = 'as';
}
}
$ds = $class->properties->{datasource}
unless $ds;
$r->cache('as_event_ds', $ds);
return $ds;
}
sub encode_field_for_html {
my $event = shift;
my ($field) = @_;
return encode_html( $event->$field() );
}
sub as_html {
my $event = shift;
my %params = @_;
my $stream = $event->registry_entry or return '';
# How many spaces are there in the form?
my $form = $params{form} || $stream->{html_form} || q{};
my @nums = $form =~ m{ \[ _ (\d+) \] }xmsg;
my $max = shift @nums;
for my $num (@nums) {
$max = $num if $max < $num;
}
# Do we need to supply the author name?
my @content = map { $event->encode_field_for_html($_) }
@{ $stream->{html_params} };
if ($max > scalar @content) {
my $name = defined $params{name} ? $params{name}
: $event->author->nickname
;
unshift @content, encode_html($name);
}
return MT->translate($form, @content);
}
sub update_events_loggily {
my $class = shift;
my %profile = @_;
# Keep this option out of band so we don't have to count on
# implementations of update_events() passing it through.
local $hide_timeless = delete $profile{hide_timeless} ? 1 : 0;
my $warn = $SIG{__WARN__} || sub { print STDERR $_[0] };
local $SIG{__WARN__} = sub {
my ($msg) = @_;
$msg =~ s{ \n \z }{}xms;
$msg = MT->component('ActionStreams')->translate(
'[_1] updating [_2] events for [_3]',
$msg, $profile{type}, $profile{author}->name,
);
$warn->("$msg\n");
};
eval {
$class->update_events(%profile);
};
if (my $err = $@) {
my $plugin = MT->component('ActionStreams');
my $err_msg = $plugin->translate("Error updating events for [_1]'s [_2] stream (type [_3] ident [_4]): [_5]",
$profile{author}->name, $class->properties->{class_type},
$profile{type}, $profile{ident}, $err);
MT->log($err_msg);
die $err; # re-throw so we can handle from job invocation
}
}
sub update_events {
my $class = shift;
my %profile = @_;
my $author = delete $profile{author};
my $stream = $class->registry_entry or return;
my $fetch = $stream->{fetch} || {};
local $profile{url} = $stream->{url};
die "Oops, no url?" if !$profile{url};
die "Oops, no ident?" if !$profile{ident};
$profile{url} =~ s/ {{ident}} / $profile{ident} /xmsge;
my $items;
if (my $xpath_params = $stream->{xpath}) {
$items = $class->fetch_xpath(
%$xpath_params,
%$fetch,
%profile,
);
}
elsif (my $atom_params = $stream->{atom}) {
my $get = {
created_on => 'published',
modified_on => 'updated',
title => 'title',
url => q{link[@rel='alternate']/@href},
via => q{link[@rel='alternate']/@href},
via_id => 'id',
identifier => 'id',
};
$atom_params = {} if !ref $atom_params;
@$get{keys %$atom_params} = values %$atom_params;
$items = $class->fetch_xpath(
foreach => '//entry',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $rss_params = $stream->{rss}) {
my $get = {
title => 'title',
url => 'link',
via => 'link',
created_on => 'pubDate',
thumbnail => 'media:thumbnail/@url',
via_id => 'guid',
identifier => 'guid',
};
$rss_params = {} if !ref $rss_params;
@$get{keys %$rss_params} = values %$rss_params;
$items = $class->fetch_xpath(
foreach => '//item',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $scraper_params = $stream->{scraper}) {
my ($foreach, $get) = @$scraper_params{qw( foreach get )};
my $scraper = scraper {
process $foreach, 'res[]' => scraper {
while (my ($field, $sel) = each %$get) {
process $sel->[0], $field => $sel->[1];
}
};
result 'res';
};
$items = $class->fetch_scraper(
scraper => $scraper,
%$fetch,
%profile,
);
}
return if !$items;
$class->build_results(
items => $items,
stream => $stream,
author => $author,
profile => \%profile,
);
}
sub registry_entry {
my $event = shift;
my ($type, $stream) = split /_/, $event->properties->{class_type}, 2;
my $reg = MT->instance->registry('action_streams') or return;
my $service = $reg->{$type} or return;
$service->{$stream};
}
sub author {
my $event = shift;
my $author_id = $event->author_id
or return;
return MT->instance->model('author')->lookup($author_id);
}
sub blog_id { 0 }
sub classes_for_type {
my $class = shift;
my ($type) = @_;
my $prevts = MT->instance->registry('action_streams');
my $prevt = $prevts->{$type};
return if !$prevt;
my @classes;
PACKAGE: while (my ($stream_id, $stream) = each %$prevt) {
next if 'HASH' ne ref $stream;
next if !$stream->{class} && !$stream->{url};
my $pkg;
if ($pkg = $stream->{class}) {
$pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms;
if (!eval { $pkg->properties }) {
if (!eval "require $pkg; 1") {
my $error = $@ || q{};
my $pl = MT->component('ActionStreams');
MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]',
$pkg, $type, $stream_id, $error));
next PACKAGE;
}
}
}
else {
$pkg = join q{::}, $class, 'Auto', ucfirst $type,
ucfirst $stream_id;
if (!eval { $pkg->properties }) {
eval "package $pkg; use base qw( $class ); 1" or next;
my $class_type = join q{_}, $type, $stream_id;
$pkg->install_properties({ class_type => $class_type });
$pkg->install_meta({ columns => $stream->{fields} })
if $stream->{fields};
}
}
push @classes, $pkg;
}
return @classes;
}
my $ua;
sub ua {
my $class = shift;
my %params = @_;
$ua ||= MT->new_ua({
paranoid => 1,
timeout => 10,
});
$ua->max_size(250_000) if $ua->can('max_size');
$ua->agent($params{default_useragent} ? $ua->_agent
: "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version);
return $ua if $class->class_type eq 'event';
return $ua if $params{unconditional};
require ActionStreams::UserAgent::Adapter;
my $adapter = ActionStreams::UserAgent::Adapter->new(
ua => $ua,
action_type => $class->class_type,
die_on_not_modified => $params{die_on_not_modified} || 0,
);
return $adapter;
}
sub set_values {
my $event = shift;
my ($values) = @_;
for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) {
my $meta_val = delete $values->{$meta_col};
$event->$meta_col($meta_val) if defined $meta_val;
}
$event->SUPER::set_values($values);
}
sub fetch_xpath {
my $class = shift;
my %params = @_;
my $url = $params{url} || '';
if (!$url) {
MT->log("No URL to fetch for $class results");
return;
}
my $ua = $class->ua(%params);
my $res = $ua->get($url);
if (!$res->is_success()) {
MT->log("Could not fetch ${url}: " . $res->status_line())
if $res->code != 304;
return;
}
# Strip leading whitespace, since the parser doesn't like it.
# TODO: confirm we got xml?
my $content = $res->content;
$content =~ s{ \A \s+ }{}xms;
require XML::XPath;
my $x = XML::XPath->new( xml => $content );
my @items;
ITEM: for my $item ($x->findnodes($params{foreach})) {
my %item_data;
VALUE: while (my ($key, $val) = each %{ $params{get} }) {
next VALUE if !$val;
if ($key eq 'tags') {
my @outvals = $item->findnodes($val)
or next VALUE;
$item_data{$key} = [ map { $_->getNodeValue } @outvals ];
}
else {
my $outval = $item->findvalue($val)
or next VALUE;
$outval = "$outval";
if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) {
# try both RFC 822/1123 and ISO 8601 formats
$outval = MT::Util::epoch2ts(undef, str2time($outval))
|| MT::Util::iso2ts(undef, $outval);
}
$item_data{$key} = $outval if $outval;
}
}
push @items, \%item_data;
}
return \@items;
}
sub build_results {
my $class = shift;
my %params = @_;
my ($author, $items, $profile, $stream) =
@params{qw( author items profile stream )};
my $mt = MT->app;
ITEM: for my $item (@$items) {
my $event;
my $identifier = delete $item->{identifier};
if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) {
$identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} };
}
if (defined $identifier) {
$identifier = "$identifier";
($event) = $class->search({
author_id => $author->id,
identifier => $identifier,
});
}
$event ||= $class->new;
$mt->run_callbacks('pre_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
my $tags = delete $item->{tags};
$event->set_values({
author_id => $author->id,
identifier => $identifier,
%$item,
});
$event->tags(@$tags) if $tags;
if ($hide_timeless && !$event->created_on) {
$event->visible(0);
}
$mt->run_callbacks('post_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
$event->save() or MT->log($event->errstr);
}
1;
}
sub save {
my $event = shift;
# Built-in audit field setting will set a local time, so do it ourselves.
if (!$event->created_on) {
my $ts = MT::Util::epoch2ts(undef, time);
$event->created_on($ts);
$event->modified_on($ts);
}
return $event->SUPER::save(@_);
}
sub fetch_scraper {
my $class = shift;
my %params = @_;
my ($url, $scraper) = @params{qw( url scraper )};
$scraper->user_agent( $class->ua( %params, die_on_not_modified => 1 ) );
my $uri_obj = URI->new($url);
my $items = eval { $scraper->scrape($uri_obj) };
# Ignore Web::Scraper errors due to 304 Not Modified responses.
if (!$items && $@ && !UNIVERSAL::isa($@, 'ActionStreams::UserAgent::NotModified')) {
die; # rethrow
}
# we're only being used for our scraper.
return if !$items;
return $items if !ref $items;
return $items if 'ARRAY' ne ref $items;
ITEM: for my $item (@$items) {
next ITEM if !ref $item || ref $item ne 'HASH';
for my $field (keys %$item) {
if ($field eq 'tags') {
$item->{$field} = [ map { "$_" } @{ $item->{$field} } ];
}
else {
$item->{$field} = q{} . $item->{$field};
}
}
}
return $items;
}
1;
__END__
=head1 NAME
ActionStreams::Event - an Action Streams stream definition
=head1 SYNOPSIS
# in plugin's config.yaml
profile_services:
example:
streamid:
name: Dice Example
description: A simple die rolling Perl stream example.
html_form: [_1] rolled a [_2]!
html_params:
- title
class: My::Stream
# in plugin's lib/My/Stream.pm
package My::Stream;
use base qw( ActionStreams::Event );
__PACKAGE__->install_properties({
class_type => 'example_streamid',
});
sub update_events {
my $class = shift;
my %profile = @_;
# trivial example: save a random number
my $die_roll = int rand 20;
my %item = (
title => $die_roll,
identifier => $die_roll,
);
return $class->build_results(
author => $profile{author},
items => [ \%item ],
);
}
1;
=head1 DESCRIPTION
I<ActionStreams::Event> provides the basic implementation of an action stream.
Stream definitions are engines for turning web resources into I<actions> (also
called I<events>). This base class produces actions based on generic stream
recipes defined in the MT registry, as well as providing the internal machinery
for you to implement your own streams in Perl code.
=head1 METHODS TO IMPLEMENT
These are the methods one commonly implements (overrides) when implementing a
stream subclass.
-=head2 C<$class-E<GT>update_events(%profile)>
+=head2 C<$class-E<gt>update_events(%profile)>
Fetches the web resource specified by the profile parameters, collects data
from it into actions, and saves the action records for use later. Required
members of C<%profile> are:
=over 4
=item * C<author>
The C<MT::Author> instance for whom events should be collected.
=item * C<ident>
The author's identifier on the given service.
=back
Other information about the stream, such as the URL pattern into which the
C<ident> parameter can be replaced, is available through the
C<$class-E<gt>registry_entry()> method.
-=head2 C<$self-E<GT>as_html(%params)>
+=head2 C<$self-E<gt>as_html(%params)>
Returns the HTML version of the action, suitable for display to readers.
The default implementation uses the stream's registry definition to construct
the action: the author's name and the action's values as named in
C<html_params> are replaced into the stream's C<html_form> setting. You need
override it only if you have more complex requirements.
Optional members of C<%params> are:
=over 4
=item * C<form>
The formatting string to use. If not given, the C<html_form> specified for
this stream in the registry is used.
=item * C<name>
The text to use as the author's name if C<as_html> needs to provide it
automatically in the result. Author names are provided if there are more
tokens in C<html_form> than there are fields specified in C<html_params>.
If not given, the event's author's nickname is provided. Note that a defined
but empty name (such as C<q{}>) I<will> be used; in this case, the name will
appear to be omitted from the result of the C<as_html> call.
=back
=head1 AVAILABLE METHODS
These are the methods provided by I<ActionStreams::Event> to perform common
tasks. Call them from your overridden methods.
-=head2 C<$self-E<GT>set_values(\%values)>
+=head2 C<$self-E<gt>set_values(\%values)>
Stores the data given in C<%values> as members of this event.
-=head2 C<$class-E<GT>fetch_xpath(%param)>
+=head2 C<$class-E<gt>fetch_xpath(%param)>
Returns the items discovered by scanning a web resource by the given XPath
recipe. Required members of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be a
valid XML document.
=item * C<foreach>
The XPath selector with which to select the individual events from the
resource.
=item * C<get>
A hashref containing the XPath selectors with which to collect individual data
for each item, keyed on the names of the fields to contain the data.
=back
C<%param> may also contain additional arguments for the C<ua()> method.
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
-=head2 C<$class-E<GT>fetch_scraper(%param)>
+=head2 C<$class-E<gt>fetch_scraper(%param)>
Returns the items discovered by scanning by the given recipe. Required members
of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be an
HTML or XML document suitable for analysis by the C<Web::Scraper> module.
=item * C<scraper>
The C<Web::Scraper> scraper with which to extract item data from the specified
web resource. See L<Web::Scraper> for information on how to construct a
scraper.
=back
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
See also the below I<NOTE ON WEB::SCRAPER>.
-=head2 C<$class-E<GT>build_results(%param)>
+=head2 C<$class-E<gt>build_results(%param)>
Converts a set of collected items into saved action records of type C<$class>.
The required members of C<%param> are:
=over 4
=item * C<author>
The C<MT::Author> instance whose action the items represent.
=item * C<items>
An arrayref of items to save as actions. Each item is a hashref containing the
action data, keyed on the names of the fields containing the data.
=back
Optional parameters are:
=over 4
=item * C<profile>
An arrayref describing the data for the author's profile for the associated
stream, such as is returned by the C<MT::Author::other_profile()> method
supplied by the Action Streams plugin.
The profile member is not used directly by C<build_results()>; they are only
passed to callbacks.
=item * C<stream>
A hashref containing the settings from the registry about the stream, such as
is returned from the C<registry_entry()> method.
=back
-=head2 C<$class-E<GT>ua(%param)>
+=head2 C<$class-E<gt>ua(%param)>
Returns the common HTTP user-agent, an instance of C<LWP::UserAgent>, with
which you can fetch web resources.
The resulting user agent may provide automatic conditional HTTP support when
you call its C<get> method. A UA with conditional HTTP support enabled will
store the values of the conditional HTTP headers (C<ETag> and
C<Last-Modified>) received in responses as C<ActionStreams::UserAgent::Cache>
objects and, on subsequent requests of the same URL, automatically supply the
header values. When the remote HTTP server reports that such a resource has
not changed, the C<HTTP::Response> will be a C<304 Not Modified> response; the
user agent does not itself store and supply the resource content. Using other
C<LWP::UserAgent> methods such as C<post> or C<request> will I<not> trigger
automatic conditional HTTP support.
No arguments are required; possible optional parameters are:
=over 4
=item * C<default_useragent>
If set, the returned HTTP user-agent will use C<LWP::UserAgent>'s default
identifier in the HTTP C<User-Agent> header. If omitted, the UA will use the
Action Streams identifier of C<mt-actionstreams-lwp/I<version>>.
=item * C<unconditional>
If set, the return HTTP user-agent will I<not> automatically use conditional
HTTP to avoid requesting old content from compliant servers. That is, if
omitted, the UA I<will> automatically use conditional HTTP when you call its
C<get> method.
=item * C<die_on_not_modified>
If set, when the response of the HTTP user-agent's C<get> method is a
conditional HTTP C<304 Not Modified> response, throw an exception instead of
returning the response. (Use this option to return control to yourself when
passing UAs with conditional HTTP support to other Perl modules that don't
expect 304 responses.)
The thrown exception is an C<ActionStreams::UserAgent::NotModified> exception.
=back
-=head2 C<$self-E<GT>author()>
+=head2 C<$self-E<gt>author()>
Returns the C<MT::Author> instance associated with this event, if its
C<author_id> field has been set.
-=head2 C<$class-E<GT>install_properties(\%properties)>
+=head2 C<$class-E<gt>install_properties(\%properties)>
I<TODO>
-=head2 C<$class-E<GT>install_meta(\%properties)>
+=head2 C<$class-E<gt>install_meta(\%properties)>
I<TODO>
-=head2 C<$class-E<GT>registry_entry()>
+=head2 C<$class-E<gt>registry_entry()>
Returns the registry data for the stream represented by C<$class>.
-=head2 C<$class-E<GT>classes_for_type($service_id)>
+=head2 C<$class-E<gt>classes_for_type($service_id)>
Given a profile service ID (that is, a key from the C<profile_services> section
of the registry), returns a list of stream classes for scanning that service's
streams.
=head1 NOTE ON WEB::SCRAPER
The C<Web::Scraper> module is powerful, but it has complex dependencies. While
its pure Perl requirements are bundled with the Action Streams plugin, it also
requires a compiled XML module. Also, because of how its syntax works, you must
directly C<use> the module in your own code, contrary to the Movable Type idiom
of using C<require> so that modules are loaded only when they are sure to be
used.
If you attempt load C<Web::Scraper> in the normal way, but C<Web::Scraper> is
unable to load due to its missing requirement, whenever the plugin attempts to
load your scraper, the entire plugin will fail to load.
Therefore the C<ActionStreams::Scraper> wrapper module is provided for you. If
you need to load C<Web::Scraper> so as to make a scraper to pass
C<ActionStreams::Event::fetch_scraper()> method, instead write in your module:
use ActionStreams::Scraper;
This module provides the C<Web::Scraper> interface, but if C<Web::Scraper> is
unable to load, the error will be thrown when your module tries to I<use> it,
rather than when you I<load> it. That is, if C<Web::Scraper> can't load, no
errors will be thrown to end users until they try to use your stream.
=head1 AUTHOR
Mark Paschal E<lt>[email protected]<gt>
=cut
|
markpasc/mt-plugin-action-streams
|
79e5b2c8fa3fb562ab13317a3f6f493de74861bf
|
Undoing my checkin in r1432 and breaking it up into individual commits per markpasc's request
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm
index fb839d6..91cb31a 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm
@@ -34,765 +34,765 @@ __PACKAGE__->install_properties({
datasource => 'profileevent',
primary_key => 'id',
});
__PACKAGE__->install_meta({
columns => [ qw(
title
url
thumbnail
via
via_id
) ],
});
# Oracle does not like an identifier of more than 30 characters.
sub datasource {
my $class = shift;
my $r = MT->request;
my $ds = $r->cache('as_event_ds');
return $ds if $ds;
my $dss_oracle = qr/(db[id]::)?oracle/;
if ( my $type = MT->config('ObjectDriver') ) {
if ((lc $type) =~ m/^$dss_oracle$/) {
$ds = 'as';
}
}
$ds = $class->properties->{datasource}
unless $ds;
$r->cache('as_event_ds', $ds);
return $ds;
}
sub encode_field_for_html {
my $event = shift;
my ($field) = @_;
return encode_html( $event->$field() );
}
sub as_html {
my $event = shift;
my %params = @_;
my $stream = $event->registry_entry or return '';
# How many spaces are there in the form?
my $form = $params{form} || $stream->{html_form} || q{};
my @nums = $form =~ m{ \[ _ (\d+) \] }xmsg;
my $max = shift @nums;
for my $num (@nums) {
$max = $num if $max < $num;
}
# Do we need to supply the author name?
my @content = map { $event->encode_field_for_html($_) }
@{ $stream->{html_params} };
if ($max > scalar @content) {
my $name = defined $params{name} ? $params{name}
: $event->author->nickname
;
unshift @content, encode_html($name);
}
return MT->translate($form, @content);
}
sub update_events_loggily {
my $class = shift;
my %profile = @_;
# Keep this option out of band so we don't have to count on
# implementations of update_events() passing it through.
local $hide_timeless = delete $profile{hide_timeless} ? 1 : 0;
my $warn = $SIG{__WARN__} || sub { print STDERR $_[0] };
local $SIG{__WARN__} = sub {
my ($msg) = @_;
$msg =~ s{ \n \z }{}xms;
$msg = MT->component('ActionStreams')->translate(
'[_1] updating [_2] events for [_3]',
$msg, $profile{type}, $profile{author}->name,
);
$warn->("$msg\n");
};
eval {
$class->update_events(%profile);
};
if (my $err = $@) {
my $plugin = MT->component('ActionStreams');
my $err_msg = $plugin->translate("Error updating events for [_1]'s [_2] stream (type [_3] ident [_4]): [_5]",
$profile{author}->name, $class->properties->{class_type},
$profile{type}, $profile{ident}, $err);
MT->log($err_msg);
die $err; # re-throw so we can handle from job invocation
}
}
sub update_events {
my $class = shift;
my %profile = @_;
my $author = delete $profile{author};
my $stream = $class->registry_entry or return;
my $fetch = $stream->{fetch} || {};
local $profile{url} = $stream->{url};
die "Oops, no url?" if !$profile{url};
die "Oops, no ident?" if !$profile{ident};
$profile{url} =~ s/ {{ident}} / $profile{ident} /xmsge;
my $items;
if (my $xpath_params = $stream->{xpath}) {
$items = $class->fetch_xpath(
%$xpath_params,
%$fetch,
%profile,
);
}
elsif (my $atom_params = $stream->{atom}) {
my $get = {
created_on => 'published',
modified_on => 'updated',
title => 'title',
url => q{link[@rel='alternate']/@href},
via => q{link[@rel='alternate']/@href},
via_id => 'id',
identifier => 'id',
};
$atom_params = {} if !ref $atom_params;
@$get{keys %$atom_params} = values %$atom_params;
$items = $class->fetch_xpath(
foreach => '//entry',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $rss_params = $stream->{rss}) {
my $get = {
title => 'title',
url => 'link',
via => 'link',
created_on => 'pubDate',
thumbnail => 'media:thumbnail/@url',
via_id => 'guid',
identifier => 'guid',
};
$rss_params = {} if !ref $rss_params;
@$get{keys %$rss_params} = values %$rss_params;
$items = $class->fetch_xpath(
foreach => '//item',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $scraper_params = $stream->{scraper}) {
my ($foreach, $get) = @$scraper_params{qw( foreach get )};
my $scraper = scraper {
process $foreach, 'res[]' => scraper {
while (my ($field, $sel) = each %$get) {
process $sel->[0], $field => $sel->[1];
}
};
result 'res';
};
$items = $class->fetch_scraper(
scraper => $scraper,
%$fetch,
%profile,
);
}
return if !$items;
$class->build_results(
items => $items,
stream => $stream,
author => $author,
profile => \%profile,
);
}
sub registry_entry {
my $event = shift;
my ($type, $stream) = split /_/, $event->properties->{class_type}, 2;
my $reg = MT->instance->registry('action_streams') or return;
my $service = $reg->{$type} or return;
$service->{$stream};
}
sub author {
my $event = shift;
my $author_id = $event->author_id
or return;
return MT->instance->model('author')->lookup($author_id);
}
sub blog_id { 0 }
sub classes_for_type {
my $class = shift;
my ($type) = @_;
my $prevts = MT->instance->registry('action_streams');
my $prevt = $prevts->{$type};
return if !$prevt;
my @classes;
PACKAGE: while (my ($stream_id, $stream) = each %$prevt) {
next if 'HASH' ne ref $stream;
next if !$stream->{class} && !$stream->{url};
my $pkg;
if ($pkg = $stream->{class}) {
$pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms;
if (!eval { $pkg->properties }) {
if (!eval "require $pkg; 1") {
my $error = $@ || q{};
my $pl = MT->component('ActionStreams');
MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]',
$pkg, $type, $stream_id, $error));
next PACKAGE;
}
}
}
else {
$pkg = join q{::}, $class, 'Auto', ucfirst $type,
ucfirst $stream_id;
if (!eval { $pkg->properties }) {
eval "package $pkg; use base qw( $class ); 1" or next;
my $class_type = join q{_}, $type, $stream_id;
$pkg->install_properties({ class_type => $class_type });
$pkg->install_meta({ columns => $stream->{fields} })
if $stream->{fields};
}
}
push @classes, $pkg;
}
return @classes;
}
my $ua;
sub ua {
my $class = shift;
my %params = @_;
$ua ||= MT->new_ua({
paranoid => 1,
timeout => 10,
});
$ua->max_size(250_000) if $ua->can('max_size');
$ua->agent($params{default_useragent} ? $ua->_agent
: "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version);
return $ua if $class->class_type eq 'event';
return $ua if $params{unconditional};
require ActionStreams::UserAgent::Adapter;
my $adapter = ActionStreams::UserAgent::Adapter->new(
ua => $ua,
action_type => $class->class_type,
die_on_not_modified => $params{die_on_not_modified} || 0,
);
return $adapter;
}
sub set_values {
my $event = shift;
my ($values) = @_;
for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) {
my $meta_val = delete $values->{$meta_col};
$event->$meta_col($meta_val) if defined $meta_val;
}
$event->SUPER::set_values($values);
}
sub fetch_xpath {
my $class = shift;
my %params = @_;
my $url = $params{url} || '';
if (!$url) {
MT->log("No URL to fetch for $class results");
return;
}
my $ua = $class->ua(%params);
my $res = $ua->get($url);
if (!$res->is_success()) {
MT->log("Could not fetch ${url}: " . $res->status_line())
if $res->code != 304;
return;
}
# Strip leading whitespace, since the parser doesn't like it.
# TODO: confirm we got xml?
my $content = $res->content;
$content =~ s{ \A \s+ }{}xms;
require XML::XPath;
my $x = XML::XPath->new( xml => $content );
my @items;
ITEM: for my $item ($x->findnodes($params{foreach})) {
my %item_data;
VALUE: while (my ($key, $val) = each %{ $params{get} }) {
next VALUE if !$val;
if ($key eq 'tags') {
my @outvals = $item->findnodes($val)
or next VALUE;
$item_data{$key} = [ map { $_->getNodeValue } @outvals ];
}
else {
my $outval = $item->findvalue($val)
or next VALUE;
$outval = "$outval";
if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) {
# try both RFC 822/1123 and ISO 8601 formats
$outval = MT::Util::epoch2ts(undef, str2time($outval))
|| MT::Util::iso2ts(undef, $outval);
}
$item_data{$key} = $outval if $outval;
}
}
push @items, \%item_data;
}
return \@items;
}
sub build_results {
my $class = shift;
my %params = @_;
my ($author, $items, $profile, $stream) =
@params{qw( author items profile stream )};
my $mt = MT->app;
ITEM: for my $item (@$items) {
my $event;
my $identifier = delete $item->{identifier};
if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) {
$identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} };
}
if (defined $identifier) {
$identifier = "$identifier";
($event) = $class->search({
author_id => $author->id,
identifier => $identifier,
});
}
$event ||= $class->new;
$mt->run_callbacks('pre_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
my $tags = delete $item->{tags};
$event->set_values({
author_id => $author->id,
identifier => $identifier,
%$item,
});
$event->tags(@$tags) if $tags;
if ($hide_timeless && !$event->created_on) {
$event->visible(0);
}
$mt->run_callbacks('post_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
$event->save() or MT->log($event->errstr);
}
1;
}
sub save {
my $event = shift;
# Built-in audit field setting will set a local time, so do it ourselves.
if (!$event->created_on) {
my $ts = MT::Util::epoch2ts(undef, time);
$event->created_on($ts);
$event->modified_on($ts);
}
return $event->SUPER::save(@_);
}
sub fetch_scraper {
my $class = shift;
my %params = @_;
my ($url, $scraper) = @params{qw( url scraper )};
$scraper->user_agent( $class->ua( %params, die_on_not_modified => 1 ) );
my $uri_obj = URI->new($url);
my $items = eval { $scraper->scrape($uri_obj) };
# Ignore Web::Scraper errors due to 304 Not Modified responses.
if (!$items && $@ && !UNIVERSAL::isa($@, 'ActionStreams::UserAgent::NotModified')) {
die; # rethrow
}
# we're only being used for our scraper.
return if !$items;
return $items if !ref $items;
return $items if 'ARRAY' ne ref $items;
ITEM: for my $item (@$items) {
next ITEM if !ref $item || ref $item ne 'HASH';
for my $field (keys %$item) {
if ($field eq 'tags') {
$item->{$field} = [ map { "$_" } @{ $item->{$field} } ];
}
else {
$item->{$field} = q{} . $item->{$field};
}
}
}
return $items;
}
1;
__END__
=head1 NAME
ActionStreams::Event - an Action Streams stream definition
=head1 SYNOPSIS
# in plugin's config.yaml
profile_services:
example:
streamid:
name: Dice Example
description: A simple die rolling Perl stream example.
html_form: [_1] rolled a [_2]!
html_params:
- title
class: My::Stream
# in plugin's lib/My/Stream.pm
package My::Stream;
use base qw( ActionStreams::Event );
__PACKAGE__->install_properties({
class_type => 'example_streamid',
});
sub update_events {
my $class = shift;
my %profile = @_;
# trivial example: save a random number
my $die_roll = int rand 20;
my %item = (
title => $die_roll,
identifier => $die_roll,
);
return $class->build_results(
author => $profile{author},
items => [ \%item ],
);
}
1;
=head1 DESCRIPTION
I<ActionStreams::Event> provides the basic implementation of an action stream.
Stream definitions are engines for turning web resources into I<actions> (also
called I<events>). This base class produces actions based on generic stream
recipes defined in the MT registry, as well as providing the internal machinery
for you to implement your own streams in Perl code.
=head1 METHODS TO IMPLEMENT
These are the methods one commonly implements (overrides) when implementing a
stream subclass.
-=head2 C<$class-E<gt>update_events(%profile)>
+=head2 C<$class-E<GT>update_events(%profile)>
Fetches the web resource specified by the profile parameters, collects data
from it into actions, and saves the action records for use later. Required
members of C<%profile> are:
=over 4
=item * C<author>
The C<MT::Author> instance for whom events should be collected.
=item * C<ident>
The author's identifier on the given service.
=back
Other information about the stream, such as the URL pattern into which the
C<ident> parameter can be replaced, is available through the
C<$class-E<gt>registry_entry()> method.
-=head2 C<$self-E<gt>as_html(%params)>
+=head2 C<$self-E<GT>as_html(%params)>
Returns the HTML version of the action, suitable for display to readers.
The default implementation uses the stream's registry definition to construct
the action: the author's name and the action's values as named in
C<html_params> are replaced into the stream's C<html_form> setting. You need
override it only if you have more complex requirements.
Optional members of C<%params> are:
=over 4
=item * C<form>
The formatting string to use. If not given, the C<html_form> specified for
this stream in the registry is used.
=item * C<name>
The text to use as the author's name if C<as_html> needs to provide it
automatically in the result. Author names are provided if there are more
tokens in C<html_form> than there are fields specified in C<html_params>.
If not given, the event's author's nickname is provided. Note that a defined
but empty name (such as C<q{}>) I<will> be used; in this case, the name will
appear to be omitted from the result of the C<as_html> call.
=back
=head1 AVAILABLE METHODS
These are the methods provided by I<ActionStreams::Event> to perform common
tasks. Call them from your overridden methods.
-=head2 C<$self-E<gt>set_values(\%values)>
+=head2 C<$self-E<GT>set_values(\%values)>
Stores the data given in C<%values> as members of this event.
-=head2 C<$class-E<gt>fetch_xpath(%param)>
+=head2 C<$class-E<GT>fetch_xpath(%param)>
Returns the items discovered by scanning a web resource by the given XPath
recipe. Required members of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be a
valid XML document.
=item * C<foreach>
The XPath selector with which to select the individual events from the
resource.
=item * C<get>
A hashref containing the XPath selectors with which to collect individual data
for each item, keyed on the names of the fields to contain the data.
=back
C<%param> may also contain additional arguments for the C<ua()> method.
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
-=head2 C<$class-E<gt>fetch_scraper(%param)>
+=head2 C<$class-E<GT>fetch_scraper(%param)>
Returns the items discovered by scanning by the given recipe. Required members
of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be an
HTML or XML document suitable for analysis by the C<Web::Scraper> module.
=item * C<scraper>
The C<Web::Scraper> scraper with which to extract item data from the specified
web resource. See L<Web::Scraper> for information on how to construct a
scraper.
=back
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
See also the below I<NOTE ON WEB::SCRAPER>.
-=head2 C<$class-E<gt>build_results(%param)>
+=head2 C<$class-E<GT>build_results(%param)>
Converts a set of collected items into saved action records of type C<$class>.
The required members of C<%param> are:
=over 4
=item * C<author>
The C<MT::Author> instance whose action the items represent.
=item * C<items>
An arrayref of items to save as actions. Each item is a hashref containing the
action data, keyed on the names of the fields containing the data.
=back
Optional parameters are:
=over 4
=item * C<profile>
An arrayref describing the data for the author's profile for the associated
stream, such as is returned by the C<MT::Author::other_profile()> method
supplied by the Action Streams plugin.
The profile member is not used directly by C<build_results()>; they are only
passed to callbacks.
=item * C<stream>
A hashref containing the settings from the registry about the stream, such as
is returned from the C<registry_entry()> method.
=back
-=head2 C<$class-E<gt>ua(%param)>
+=head2 C<$class-E<GT>ua(%param)>
Returns the common HTTP user-agent, an instance of C<LWP::UserAgent>, with
which you can fetch web resources.
The resulting user agent may provide automatic conditional HTTP support when
you call its C<get> method. A UA with conditional HTTP support enabled will
store the values of the conditional HTTP headers (C<ETag> and
C<Last-Modified>) received in responses as C<ActionStreams::UserAgent::Cache>
objects and, on subsequent requests of the same URL, automatically supply the
header values. When the remote HTTP server reports that such a resource has
not changed, the C<HTTP::Response> will be a C<304 Not Modified> response; the
user agent does not itself store and supply the resource content. Using other
C<LWP::UserAgent> methods such as C<post> or C<request> will I<not> trigger
automatic conditional HTTP support.
No arguments are required; possible optional parameters are:
=over 4
=item * C<default_useragent>
If set, the returned HTTP user-agent will use C<LWP::UserAgent>'s default
identifier in the HTTP C<User-Agent> header. If omitted, the UA will use the
Action Streams identifier of C<mt-actionstreams-lwp/I<version>>.
=item * C<unconditional>
If set, the return HTTP user-agent will I<not> automatically use conditional
HTTP to avoid requesting old content from compliant servers. That is, if
omitted, the UA I<will> automatically use conditional HTTP when you call its
C<get> method.
=item * C<die_on_not_modified>
If set, when the response of the HTTP user-agent's C<get> method is a
conditional HTTP C<304 Not Modified> response, throw an exception instead of
returning the response. (Use this option to return control to yourself when
passing UAs with conditional HTTP support to other Perl modules that don't
expect 304 responses.)
The thrown exception is an C<ActionStreams::UserAgent::NotModified> exception.
=back
-=head2 C<$self-E<gt>author()>
+=head2 C<$self-E<GT>author()>
Returns the C<MT::Author> instance associated with this event, if its
C<author_id> field has been set.
-=head2 C<$class-E<gt>install_properties(\%properties)>
+=head2 C<$class-E<GT>install_properties(\%properties)>
I<TODO>
-=head2 C<$class-E<gt>install_meta(\%properties)>
+=head2 C<$class-E<GT>install_meta(\%properties)>
I<TODO>
-=head2 C<$class-E<gt>registry_entry()>
+=head2 C<$class-E<GT>registry_entry()>
Returns the registry data for the stream represented by C<$class>.
-=head2 C<$class-E<gt>classes_for_type($service_id)>
+=head2 C<$class-E<GT>classes_for_type($service_id)>
Given a profile service ID (that is, a key from the C<profile_services> section
of the registry), returns a list of stream classes for scanning that service's
streams.
=head1 NOTE ON WEB::SCRAPER
The C<Web::Scraper> module is powerful, but it has complex dependencies. While
its pure Perl requirements are bundled with the Action Streams plugin, it also
requires a compiled XML module. Also, because of how its syntax works, you must
directly C<use> the module in your own code, contrary to the Movable Type idiom
of using C<require> so that modules are loaded only when they are sure to be
used.
If you attempt load C<Web::Scraper> in the normal way, but C<Web::Scraper> is
unable to load due to its missing requirement, whenever the plugin attempts to
load your scraper, the entire plugin will fail to load.
Therefore the C<ActionStreams::Scraper> wrapper module is provided for you. If
you need to load C<Web::Scraper> so as to make a scraper to pass
C<ActionStreams::Event::fetch_scraper()> method, instead write in your module:
use ActionStreams::Scraper;
This module provides the C<Web::Scraper> interface, but if C<Web::Scraper> is
unable to load, the error will be thrown when your module tries to I<use> it,
rather than when you I<load> it. That is, if C<Web::Scraper> can't load, no
errors will be thrown to end users until they try to use your stream.
=head1 AUTHOR
Mark Paschal E<lt>[email protected]<gt>
=cut
diff --git a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
index 9f43e7f..86412c2 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
@@ -1,726 +1,711 @@
package ActionStreams::Plugin;
use strict;
use warnings;
use Carp qw( croak );
use MT::Util qw( relative_date offset_time epoch2ts ts2epoch format_ts );
sub users_content_nav {
my ($cb, $app, $html_ref) = @_;
return unless $app->param('id');
$$html_ref =~ s{class=["']active["']}{}xmsg
if $app->mode eq 'list_profileevent' || $app->mode eq 'other_profiles';
$$html_ref =~ m{ "> ((?:<b>)?) <__trans \s phrase="Permissions"> ((?:</b>)?) </a> }xms;
my ($open_bold, $close_bold) = ($1, $2);
my $html = <<"EOF";
<mt:if var="USER_VIEW">
<li><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">">$open_bold<__trans phrase="Other Profiles">$close_bold</a></li>
<li><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">">$open_bold<__trans phrase="Action Stream">$close_bold</a></li>
</mt:if>
<mt:if var="edit_author">
<li<mt:if name="other_profiles"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="id" escape="url">">$open_bold<__trans phrase="Other Profiles">$close_bold</a></li>
<li<mt:if name="list_profileevent"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="id" escape="url">">$open_bold<__trans phrase="Action Stream">$close_bold</a></li>
</mt:if>
EOF
$$html_ref =~ s{(?=</ul>)}{$html}xmsg;
}
sub icon_url_for_service {
my $class = shift;
my ($type, $ndata) = @_;
my $plug = $ndata->{plugin} or return;
my $icon_url;
if ($ndata->{icon} && $ndata->{icon} =~ m{ \A \w:// }xms) {
$icon_url = $ndata->{icon};
}
elsif ($ndata->{icon}) {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
$ndata->{icon};
}
elsif ($plug->id eq 'actionstreams') {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
'images', 'services', $type . '.png';
}
return $icon_url;
}
-sub _edit_author {
- my $app = shift;
- my $author_id = $app->param('id')
- || ($app->user ? $app->user->id : undef);
-
- my $class = MT->model('author');
- my $author = $class->load($author_id) if $author_id;
-
- $author or return $app->error(
- $app->translate( "No such [_1].", lc( $class->class_label ) ) );
-
- return $app->error( $app->translate("Permission denied.") )
- if ! $app->user
- or $app->user->id != $author_id && !$app->user->is_superuser();
-
- return $author;
-}
-
sub list_profileevent {
my $app = shift;
my %param = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
- my $author = _edit_author($app) or return;
+ my $author_id = $app->param('id')
+ or return;
+ return $app->error('Not permitted to view')
+ if $app->user->id != $author_id && !$app->user->is_superuser();
my %service_styles;
my @service_styles_loop;
my $code = sub {
my ($event, $row) = @_;
my @meta_col = keys %{ $event->properties->{meta_columns} || {} };
$row->{$_} = $event->{$_} for @meta_col;
$row->{as_html} = $event->as_html();
my ($service, $stream_id) = split /_/, $row->{class}, 2;
$row->{type} = $service;
my $nets = $app->registry('profile_services') || {};
my $net = $nets->{$service};
$row->{service} = $net->{name} if $net;
$row->{url} = $event->url;
if (!$service_styles{$service}) {
if (!$net->{plugin} || $net->{plugin}->id ne 'actionstreams') {
if (my $icon = __PACKAGE__->icon_url_for_service($service, $net)) {
push @service_styles_loop, {
service_type => $service,
service_icon => $icon,
};
}
}
$service_styles{$service} = 1;
}
my $ts = $row->{created_on};
$row->{created_on_relative} = relative_date($ts, time);
$row->{created_on_formatted} = format_ts(
MT::App::CMS->LISTING_DATETIME_FORMAT(),
epoch2ts(undef, offset_time(ts2epoch(undef, $ts))),
undef,
$app->user ? $app->user->preferred_language : undef,
);
};
# Make sure all classes are loaded.
require ActionStreams::Event;
for my $prevt (keys %{ $app->registry('action_streams') }) {
ActionStreams::Event->classes_for_type($prevt);
}
my $plugin = MT->component('ActionStreams');
my %params = map { $_ => $app->param($_) ? 1 : 0 }
qw( saved_deleted hidden shown );
- $params{id} = $params{edit_author_id} = $author->id;
- $params{name} = $params{edit_author_name} = $author->name;
-
$params{services} = [];
my $services = $app->registry('profile_services');
while (my ($prevt, $service) = each %$services) {
push @{ $params{services} }, {
service_id => $prevt,
service_name => $service->{name},
};
}
$params{services} = [ sort { lc $a->{service_name} cmp lc $b->{service_name} } @{ $params{services} } ];
my %terms = (
class => '*',
- author_id => $author->id,
+ author_id => $author_id,
);
my %args = (
sort => 'created_on',
direction => 'descend',
);
if (my $filter = $app->param('filter')) {
$params{filter_key} = $filter;
my $filter_val = $params{filter_val} = $app->param('filter_val');
if ($filter eq 'service') {
$params{filter_label} = $app->translate('Actions from the service [_1]', $app->registry('profile_services')->{$filter_val}->{name});
$terms{class} = $filter_val . '_%';
$args{like} = { class => 1 };
}
elsif ($filter eq 'visible') {
$params{filter_label} = ($filter_val eq 'show') ? 'Actions that are shown'
: 'Actions that are hidden';
$terms{visible} = $filter_val eq 'show' ? 1 : 0;
}
}
+
+ $params{id} = $params{edit_author_id} = $author_id;
$params{service_styles} = \@service_styles_loop;
$app->listing({
type => 'profileevent',
terms => \%terms,
args => \%args,
listing_screen => 1,
code => $code,
template => $plugin->load_tmpl('list_profileevent.tmpl'),
params => \%params,
});
}
sub itemset_hide_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(0);
$event->save;
}
$app->add_return_arg( hidden => 1 );
$app->call_return;
}
sub itemset_show_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(1);
$event->save;
}
$app->add_return_arg( shown => 1 );
$app->call_return;
}
sub _itemset_hide_show_all_events {
my ($app, $new_visible) = @_;
$app->validate_magic or return;
my $event_class = MT->model('profileevent');
# Really we should work directly from the selected author ID, but as an
# itemset event we only got some event IDs. So use its.
my ($event_id) = $app->param('id');
my $event = $event_class->load($event_id)
or return $app->error($app->translate('No such event [_1]', $event_id));
my $author_id = $event->author_id;
return $app->error('Not permitted to modify')
- if ! $app->user
- or ! $app->user->is_superuser() && $author_id != $app->user->id;
+ if $author_id != $app->user->id && !$app->is_superuser();
my $driver = $event_class->driver;
my $stmt = $driver->prepare_statement($event_class, {
# TODO: include filter value when we have filters
author_id => $author_id,
visible => $new_visible ? 0 : 1,
});
my $sql = "UPDATE " . $driver->table_for($event_class) . " SET "
. $driver->dbd->db_column_name($event_class->datasource, 'visible')
. " = ? " . $stmt->as_sql_where;
# Work around error in MT::ObjectDriver::Driver::DBI::sql by doing it inline.
my $dbh = $driver->rw_handle;
$dbh->do($sql, {}, $new_visible, @{ $stmt->{bind} })
or return $app->error($dbh->errstr);
return 1;
}
sub itemset_hide_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 0) or return;
$app->add_return_arg( all_hidden => 1 );
$app->call_return;
}
sub itemset_show_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 1) or return;
$app->add_return_arg( all_shown => 1 );
$app->call_return;
}
sub _build_service_data {
my %info = @_;
my ($networks, $streams, $author) = @info{qw( networks streams author )};
my (@service_styles_loop, @networks);
my %has_profiles;
if ($author) {
my $other_profiles = $author->other_profiles();
$has_profiles{$_->{type}} = 1 for @$other_profiles;
}
my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
keys %$networks;
TYPE: for my $type (@network_keys) {
my $ndata = $networks->{$type}
or next TYPE;
my @streams;
if ($streams) {
my $streamdata = $streams->{$type} || {};
@streams =
sort { lc $a->{name} cmp lc $b->{name} }
grep { grep { $_ } @$_{qw( class scraper xpath rss atom )} }
map { +{ stream => $_, %{ $streamdata->{$_} } } }
grep { $_ ne 'plugin' }
keys %$streamdata;
}
my $ret = {
type => $type,
%$ndata,
label => $ndata->{name},
user_has_account => ($has_profiles{$type} ? 1 : 0),
};
$ret->{streams} = \@streams if @streams;
push @networks, $ret;
if (!$ndata->{plugin} || $ndata->{plugin}->id ne 'actionstreams') {
push @service_styles_loop, {
service_type => $type,
service_icon => __PACKAGE__->icon_url_for_service($type, $ndata),
};
}
}
return (
service_styles => \@service_styles_loop,
networks => \@networks,
);
}
sub other_profiles {
my( $app ) = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
- my $author = _edit_author($app) or return;
-
- my %params;
- $params{id} = $params{edit_author_id} = $author->id;
- $params{name} = $params{edit_author_name} = $author->name;
+ my $author_id = $app->param('id')
+ or return $app->error('Author id is required');
+ my $user = MT->model('author')->load($author_id)
+ or return $app->error('Author id is invalid');
+ return $app->error('Not permitted to view')
+ if $app->user->id != $author_id && !$app->user->is_superuser();
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl( 'other_profiles.tmpl' );
my @profiles = sort { lc $a->{label} cmp lc $b->{label} }
- @{ $author->other_profiles || [] };
+ @{ $user->other_profiles || [] };
my %messages = map { $_ => $app->param($_) ? 1 : 0 }
(qw( added removed updated edited ));
return $app->build_page( $tmpl, {
- %params,
+ id => $user->id,
+ edit_author_id => $user->id,
profiles => \@profiles,
listing_screen => 1,
_build_service_data(
networks => $app->registry('profile_services'),
),
%messages,
} );
}
sub dialog_add_edit_profile {
my ($app) = @_;
return $app->error('Not permitted to view')
if $app->user->id != $app->param('author_id') && !$app->user->is_superuser();
my $author = MT->model('author')->load($app->param('author_id'))
or return $app->error('No such author [_1]', $app->param('author_id'));
my %edit_profile;
my $tmpl_name = 'dialog_add_profile.tmpl';
if (my $edit_type = $app->param('profile_type')) {
my $ident = $app->param('profile_ident') || q{};
my ($profile) = grep { $_->{ident} eq $ident }
@{ $author->other_profiles($edit_type) };
%edit_profile = (
edit_type => $edit_type,
edit_type_name => $app->registry('profile_services', $edit_type, 'name'),
edit_ident => $ident,
edit_streams => $profile->{streams} || [],
);
$tmpl_name = 'dialog_edit_profile.tmpl';
}
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl($tmpl_name);
return $app->build_page($tmpl, {
edit_author_id => $app->param('author_id'),
_build_service_data(
networks => $app->registry('profile_services'),
streams => $app->registry('action_streams'),
author => $author,
),
%edit_profile,
});
}
sub edit_other_profile {
my $app = shift;
$app->validate_magic() or return;
my $author_id = $app->param('author_id')
or return $app->error('Author id is required');
my $user = MT->model('author')->load($author_id)
or return $app->error('Author id is invalid');
return $app->error('Not permitted to edit')
if $app->user->id != $author_id && !$app->user->is_superuser();
my $type = $app->param('profile_type');
my $orig_ident = $app->param('original_ident');
$user->remove_profile($type, $orig_ident);
$app->forward('add_other_profile', success_msg => 'edited');
}
sub add_other_profile {
my $app = shift;
my %param = @_;
$app->validate_magic or return;
my $author_id = $app->param('author_id')
or return $app->error('Author id is required');
my $user = MT->model('author')->load($author_id)
or return $app->error('Author id is invalid');
return $app->error('Not permitted to add')
if $app->user->id != $author_id && !$app->user->is_superuser();
my( $ident, $uri, $label, $type );
if ( $type = $app->param( 'profile_type' ) ) {
my $reg = $app->registry('profile_services');
my $network = $reg->{$type}
or croak "Unknown network $type";
$label = $network->{name} . ' Profile';
$ident = $app->param( 'profile_id' );
$ident =~ s{ \A \s* }{}xms;
$ident =~ s{ \s* \z }{}xms;
# Check for full URLs.
if (!$network->{ident_exact}) {
my $url_pattern = $network->{url};
my ($pre_ident, $post_ident) = split /(?:\%s|\Q{{ident}}\E)/, $url_pattern, 2;
$pre_ident =~ s{ \A http:// }{}xms;
$post_ident =~ s{ / \z }{}xms;
if ($ident =~ m{ \A (?:http://)? \Q$pre_ident\E (.*?) \Q$post_ident\E /? \z }xms) {
$ident = $1;
}
}
$uri = $network->{url};
$uri =~ s{ (?:\%s|\Q{{ident}}\E) }{$ident}xmsg;
} else {
$ident = $uri = $app->param( 'profile_uri' );
$label = $app->param( 'profile_label' );
$type = 'website';
}
my $profile = {
type => $type,
ident => $ident,
label => $label,
uri => $uri,
};
my %streams = map { join(q{_}, $type, $_) => 1 }
grep { $_ ne 'plugin' && $app->param(join q{_}, 'stream', $type, $_) }
keys %{ $app->registry('action_streams', $type) || {} };
$profile->{streams} = \%streams if %streams;
$app->run_callbacks('pre_add_profile.' . $type, $app, $user, $profile);
$user->add_profile($profile);
$app->run_callbacks('post_add_profile.' . $type, $app, $user, $profile);
my $success_msg = $param{success_msg} || 'added';
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => $author_id, $success_msg => 1 },
));
}
sub remove_other_profile {
my( $app ) = @_;
$app->validate_magic or return;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
or next PROFILE;
next PROFILE
if $app->user->id != $author_id && !$app->user->is_superuser();
$app->run_callbacks('pre_remove_profile.' . $type, $app, $user, $type, $ident);
$user->remove_profile( $type, $ident );
$app->run_callbacks('post_remove_profile.' . $type, $app, $user, $type, $ident);
$page_author_id = $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), removed => 1 },
));
}
sub profile_add_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
$app->param('author_id', $user->id);
my $type = $app->param('profile_type')
or return $app->error( $app->translate("Invalid request.") );
# The profile side interface doesn't have stream selection, so select
# them all by default.
# TODO: factor out the adding logic (and parameterize stream selection) to stop faking params
foreach my $stream ( keys %{ $app->registry('action_streams', $type) || {} } ) {
next if $stream eq 'plugin';
$app->param(join('_', 'stream', $type, $stream), 1);
}
add_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub profile_first_update_events {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub profile_delete_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
# TODO: factor out this logic instead of having to fake params
my $id = scalar $app->param('id');
$id = $user->id . ':' . $id;
$app->param('id', $id);
remove_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub itemset_update_profiles {
my $app = shift;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
or next PROFILE;
next PROFILE
if $app->user->id != $author_id && !$app->user->is_superuser();
my $profiles = $user->other_profiles($type);
if (!$profiles) {
next PROFILE;
}
my @profiles = grep { $_->{ident} eq $ident } @$profiles;
for my $author_profile (@profiles) {
update_events_for_profile($user, $author_profile,
synchronous => 1);
}
$page_author_id ||= $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), updated => 1 },
));
}
sub first_profile_update {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub rebuild_action_stream_blogs {
my ($cb, $app) = @_;
my $plugin = MT->component('ActionStreams');
my $pd_iter = MT->model('plugindata')->load_iter({
plugin => $plugin->key,
key => { like => 'configuration:blog:%' }
});
my %rebuild;
while ( my $pd = $pd_iter->() ) {
next unless $pd->data('rebuild_for_action_stream_events');
my ($blog_id) = $pd->key =~ m/:blog:(\d+)$/;
$rebuild{$blog_id} = 1;
}
for my $blog_id (keys %rebuild) {
# TODO: limit this to indexes that publish action stream data, once
# we can magically infer template content before building it
my $blog = MT->model('blog')->load( $blog_id ) or next;
# Republish all the blog's known non-virtual index fileinfos that
# have real template objects.
my $finfo_class = MT->model('fileinfo');
my $finfo_template_col = $finfo_class->driver->dbd->db_column_name(
$finfo_class->datasource, 'template_id');
my @fileinfos = $finfo_class->load({
blog_id => $blog->id,
archive_type => 'index',
virtual => [ \'IS NULL', 0 ],
}, {
join => MT->model('template')->join_on(undef,
{ id => \"= $finfo_template_col" }),
});
require MT::TheSchwartz;
require TheSchwartz::Job;
for my $fi (@fileinfos) {
my $job = TheSchwartz::Job->new();
$job->funcname('MT::Worker::Publish');
$job->uniqkey($fi->id);
$job->run_after(time + 240); # 4 minutes
MT::TheSchwartz->insert($job);
}
}
}
sub widget_recent {
my ($app, $tmpl, $widget_param) = @_;
$tmpl->param('author_id', $app->user->id);
$tmpl->param('blog_id', $app->blog->id) if $app->blog;
}
sub widget_blog_dashboard_only {
my ($page, $scope) = @_;
return if $scope eq 'dashboard:system';
return 1;
}
sub update_events {
my $mt = MT->app;
$mt->run_callbacks('pre_action_streams_task', $mt);
my $au_class = MT->model('author');
my $author_iter = $au_class->search({
status => $au_class->ACTIVE(),
}, {
join => [ $au_class->meta_pkg, 'author_id', { type => 'other_profiles' } ],
});
while (my $author = $author_iter->()) {
my $profiles = $author->other_profiles();
$mt->run_callbacks('pre_update_action_streams', $mt, $author, $profiles);
PROFILE: for my $profile (@$profiles) {
update_events_for_profile($author, $profile);
}
$mt->run_callbacks('post_update_action_streams', $mt, $author, $profiles);
}
$mt->run_callbacks('post_action_streams_task', $mt);
}
sub update_events_for_profile {
my ($author, $profile, %param) = @_;
my $type = $profile->{type};
my $streams = $profile->{streams};
return if !$streams || !%$streams;
require ActionStreams::Event;
my @event_classes = ActionStreams::Event->classes_for_type($type)
or return;
my $mt = MT->app;
$mt->run_callbacks('pre_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
EVENTCLASS: for my $event_class (@event_classes) {
next EVENTCLASS if !$streams->{$event_class->class_type};
if ($param{synchronous}) {
$event_class->update_events_loggily(
author => $author,
hide_timeless => $param{hide_timeless} ? 1 : 0,
%$profile,
);
}
else {
# Defer regular updates to job workers.
require ActionStreams::Worker;
ActionStreams::Worker->make_work(
event_class => $event_class,
author => $author,
%$profile,
);
}
}
$mt->run_callbacks('post_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
}
1;
diff --git a/plugins/ActionStreams/tmpl/list_profileevent.tmpl b/plugins/ActionStreams/tmpl/list_profileevent.tmpl
index b0b658f..a9f51f5 100644
--- a/plugins/ActionStreams/tmpl/list_profileevent.tmpl
+++ b/plugins/ActionStreams/tmpl/list_profileevent.tmpl
@@ -1,276 +1,276 @@
<mt:setvar name="edit_author" value="1">
<mt:setvar name="list_profileevent" value="1">
-<mt:setvarblock name="page_title"><__trans phrase="Action Stream for [_1]" params="<mt:Var name="edit_author_name">"></mt:setvarblock>
+<mt:setvar name="page_title" value="<__trans phrase="Action Stream">">
<mt:setvarblock name="html_head" append="1">
<link rel="stylesheet" type="text/css" href="<mt:var name="static_uri">plugins/ActionStreams/css/action-streams.css" />
<script type="text/javascript">
<!--
var tableSelect;
function init() {
// set up table select awesomeness
tableSelect = new TC.TableSelect("profileevent-listing-table");
tableSelect.rowSelect = true;
}
TC.attachLoadEvent(init);
function finishPluginActionAll(f, action) {
var select_all = getByID('select-all-checkbox')
if (select_all) {
select_all.checked = true;
tableSelect.select(select_all);
}
return doForMarkedInThisWindow(f, '', 'profileevents', 'id', 'itemset_action',
{'action_name': action}, 'to act upon');
}
function toggleFilter() {
var filterActive = getByID("filter-title");
if (filterActive.style.display == "none") {
filterActive.style.display = "block";
getByID("filter-select").style.display = "none";
} else {
filterActive.style.display = "none";
getByID("filter-select").style.display = "block";
<mt:unless name="filter">setFilterCol('service');</mt:unless>
}
}
function setFilterCol(choice) {
var sel = getByID('filter-select');
if (!sel) return;
sel.className = "filter-" + choice;
if (choice != 'none') {
var fld = getByID('filter-col');
if (choice == 'service')
fld.selectedIndex = 0;
else if (choice == 'visible')
fld.selectedIndex = 1;
else if (choice == 'exacttag')
fld.selectedIndex = 2;
else if (choice == 'normalizedtag')
fld.selectedIndex = 3;
else if (choice == 'category_id')
fld.selectedIndex = 4;
else if (choice == 'asset_id')
fld.selectedIndex = <mt:if name="category_loop">5<mt:else>4</mt:if>;
col_span = getByID("filter-text-col");
if (fld.selectedIndex > -1 && col_span)
col_span.innerHTML = '<strong>' + fld.options[fld.selectedIndex].text + '</strong>';
}
}
function enableFilterButton(fld) {
if (fld && (fld.id == "filter-col")) {
var opt = fld.options[fld.selectedIndex];
if (opt.value == 'author_id') {
var authfld = getByID("author_id-val");
var authopt = authfld.options[authfld.selectedIndex];
if (authopt.value == "") {
getByID("filter-button").style.display = "none";
return;
}
}
}
getByID("filter-button").style.display = "inline";
}
// -->
</script>
<style type="text/css">
<!--
#filter-visible, #filter-service { display: none }
.filter-visible #filter-visible,
.filter-service #filter-service { display: inline }
#profileevent-listing-table .date { white-space: nowrap; }
#profileevent-listing-table .service { width: 8em; }
#main-content { padding-top: 5px; }
.content-nav #main-content .msg { margin-left: 0px; }
<mt:loop name="service_styles">
.service-<mt:var name="service_type"> { background-image: url(<mt:var name="service_icon">); }
</mt:loop>
// -->
</style>
</mt:setvarblock>
<mt:setvarblock name="content_nav">
<mt:include name="include/users_content_nav.tmpl">
</mt:setvarblock>
<mt:setvarblock name="system_msg">
<mt:if name="saved_deleted">
<mtapp:statusmsg
id="saved_deleted"
class="success">
<__trans phrase="The selected events were deleted.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="hidden">
<mtapp:statusmsg
id="hidden"
class="success">
<__trans phrase="The selected events were hidden.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="shown">
<mtapp:statusmsg
id="shown"
class="success">
<__trans phrase="The selected events were shown.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="all_hidden">
<mtapp:statusmsg
id="all_hidden"
class="success">
<__trans phrase="All action stream events were hidden.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="all_shown">
<mtapp:statusmsg
id="all_shown"
class="sucess">
<__trans phrase="All action stream events were shown.">
</mtapp:statusmsg>
</mt:if>
</mt:setvarblock>
<mt:setvarblock name="html_body_footer">
<mt:include name="include/display_options.tmpl">
</mt:setvarblock>
<mt:setvarblock name="action_buttons">
<a href="javascript:void(0)"
onclick="doForMarkedInThisWindow(getByID('profileevent-listing-form'), '<__trans phrase="event">', '<__trans phrase="events">', 'id', 'itemset_hide_events'); return false"
accesskey="h"
title="<__trans phrase="Hide selected events (h)">"
><__trans phrase="Hide"></a>
<a href="javascript:void(0)"
onclick="doForMarkedInThisWindow(getByID('profileevent-listing-form'), '<__trans phrase="event">', '<__trans phrase="events">', 'id', 'itemset_show_events'); return false"
accesskey="h"
title="<__trans phrase="Show selected events (h)">"
><__trans phrase="Show"></a>
</mt:setvarblock>
<mt:include name="include/header.tmpl">
<div class="listing-filter">
<div class="listing-filter-inner inner pkg">
<form id="filter-form" method="get" action="<mt:var name="mt_url">">
<input type="hidden" name="__mode" value="<mt:var name="mode">" />
<mt:if name="id">
<input type="hidden" name="id" value="<mt:var name="id" escape="url">" />
</mt:if>
<mt:if name="is_power_edit">
<input type="hidden" name="is_power_edit" value="1" />
</mt:if>
<input id="filter" type="hidden" name="filter" value="" />
<input id="filter_val" type="hidden" name="filter_val" value="" />
</form>
<form id="filter-select-form" method="get" onsubmit="return execFilter(this)">
<div class="filter">
<div id="filter-title">
<mt:if name="filter_key">
<strong>Showing only: <mt:var name="filter_label" escape="html"></strong>
<a class="filter-link" href="<mt:var name="script_url">?__mode=<mt:var name="mode">&id=<mt:var name="id" escape="url">">[ Remove filter ]</a>
<mt:else>
<mt:if name="filter">
<mt:else>
<strong>All stream actions</strong>
<a class="filter-link" href="javascript:void(0)" onclick="toggleFilter()">[ change ]</a>
</mt:if>
</mt:if>
</div>
<div id="filter-select" class="page-title" style="display: none">
Show only actions where
<select id="filter-col" name="filter" onchange="setFilterCol(this.options[this.selectedIndex].value); enableFilterButton(this)">
<!-- option value="stream">stream</option -->
<option value="service">service</option>
<option value="visible">visibility</option>
</select>
is
<span id="filter-visible">
<select id="visible-val" name="filter_val" onchange="enableFilterButton()">
<option value="hide">hidden</option>
<option value="show">shown</option>
</select>
</span>
<span id="filter-service">
<select id="service-val" name="filter_val" onchange="enableFilterButton()">
<mt:loop name="services">
<option value="<mt:var name="service_id">"><mt:var name="service_name"></option>
</mt:loop>
</select>
</span>
<span class="buttons">
<a href="javascript:void(0)"
id="filter-button"
onclick="return execFilter(getByID('filter-select-form'))"
type="submit"
>Filter</a>
<a href="javascript:void(0)"
onclick="toggleFilter(); return false"
type="submit"
>Cancel</a>
</span>
</div>
</div>
</form>
</div>
</div>
<mtapp:listing type="profileevent" default="<__trans phrase="No events could be found.">" empty_message="<__trans phrase="No events could be found.">">
<mt:if name="__first__">
<thead>
<tr>
<th class="cb"><input type="checkbox" id="select-all-checkbox" name="id-head" value="all" class="select" /></th>
<th class="status">
<img src="<mt:var name="static_uri">images/status_icons/invert-flag.gif" alt="<__trans phrase="Status">" title="<__trans phrase="Status">" width="9" height="9" />
</th>
<th class="event"><__trans phrase="Event"></th>
<th class="service"><span class="service-icon"><__trans phrase="Service"></span></th>
<th class="date"><__trans phrase="Created"></th>
<th class="view"><__trans phrase="View"></th>
</tr>
</thead>
<tbody>
</mt:if>
<tr class="<mt:if name="__odd__">odd<mt:else>even</mt:if>">
<td class="cb">
<input type="checkbox" name="id" value="<mt:var name="id">" class="select" />
</td>
<td class="status si status-<mt:if name="visible">publish<mt:else>pending</mt:if>">
<img src="<mt:var name="static_uri">images/spacer.gif" width="13" height="9" alt="<mt:if name="visible"><__trans phrase="Shown"><mt:else><__trans phrase="Hidden"></mt:if>" />
</td>
<td class="event">
<mt:var name="as_html" remove_html="1">
</td>
<td class="service">
<span class="service-icon service-<mt:var name="type" escape="html">"><mt:var name="service" escape="html"></span>
</td>
<td class="date">
<span title="<mt:var name="created_on_time_formatted">">
<mt:if name="dates_relative">
<mt:var name="created_on_relative">
<mt:else>
<mt:var name="created_on_formatted">
</mt:if>
</span>
</td>
<td class="view si status-view">
<mt:if name="url">
<a href="<mt:var name="url" escape="html">" target="<__trans phrase="_external_link_target">" title="<__trans phrase="View action link">"><img src="<mt:var name="static_uri">images/spacer.gif" alt="<__trans phrase="View action link">" width="13" height="9" /></a>
<mt:else>
 
</mt:if>
</td>
</tr>
</mtapp:listing>
<mt:include name="include/footer.tmpl">
diff --git a/plugins/ActionStreams/tmpl/other_profiles.tmpl b/plugins/ActionStreams/tmpl/other_profiles.tmpl
index b969c59..af50e88 100644
--- a/plugins/ActionStreams/tmpl/other_profiles.tmpl
+++ b/plugins/ActionStreams/tmpl/other_profiles.tmpl
@@ -1,129 +1,129 @@
<mt:setvar name="edit_author" value="1">
<mt:setvar name="other_profiles" value="1">
-<mt:setvarblock name="page_title"><__trans phrase="Other Profiles for [_1]" params="<mt:Var name="edit_author_name">"></mt:setvarblock>
+<mt:setvarblock name="page_title"><__trans phrase="Other Profiles"></mt:setvarblock>
<mt:setvarblock name="html_head" append="1">
<link rel="stylesheet" type="text/css" href="<mt:var name="static_uri">plugins/ActionStreams/css/action-streams.css" />
<style type="text/css">
.content-nav #main-content .msg { margin-left: 0px; }
#main-content {
padding-top:5px;
}
<mt:loop name="service_styles">
.service-<mt:var name="service_type"> { background-image: url(<mt:var name="service_icon">); }
</mt:loop>
</style>
<script type="text/javascript">
<!--
function verifyDelete( delete_item ){
conf = confirm( "Are you sure you want to delete " + delete_item + "?" );
if ( conf ) {
return true;
}
return false;
}
var tableSelect;
function init() {
// set up table select awesomeness
tableSelect = new TC.TableSelect("profile-listing-table");
tableSelect.rowSelect = true;
}
TC.attachLoadEvent(init);
// -->
</script>
</mt:setvarblock>
<mt:setvarblock name="system_msg">
<mt:if name="added">
<mtapp:statusmsg
id="added"
class="success">
<__trans phrase="The selected profile was added.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="removed">
<mtapp:statusmsg
id="removed"
class="success">
<__trans phrase="The selected profiles were removed.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="updated">
<mtapp:statusmsg
id="updated"
class="success">
<__trans phrase="The selected profiles were scanned for updates.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="edited">
<mtapp:statusmsg
id="edited"
class="success">
<__trans phrase="The changes to the profile have been saved.">
</mtapp:statusmsg>
</mt:if>
</mt:setvarblock>
<mt:setvarblock name="content_nav">
<mt:include name="include/users_content_nav.tmpl">
</mt:setvarblock>
<mt:setvarblock name="content_header">
<ul class="action-link-list">
<li>
<a href="javascript:void(0)" onclick="return openDialog(this.form, 'dialog_add_profile', 'author_id=<mt:var name="edit_author_id">&return_args=<mt:var name="return_args" escape="url">%26author_id=<mt:var name="edit_author_id">')" class="icon-left icon-create"><__trans phrase="Add Profile"></a>
</li>
</ul>
</mt:setvarblock>
<mt:setvarblock name="action_buttons">
<a href="javascript:void(0)"
onclick="doRemoveItems(getByID('profile-listing-form'), '<__trans phrase="profile">', '<__trans phrase="profiles">', null, null, { mode: 'remove_other_profile' }); return false"
accesskey="x"
title="<__trans phrase="Delete selected profiles (x)">"
><__trans phrase="Delete"></a>
<a href="javascript:void(0)"
onclick="doForMarkedInThisWindow(getByID('profile-listing-form'), '<__trans phrase="profile">', '<__trans phrase="profiles">', 'id', 'itemset_update_profiles'); return false"
title="<__trans phrase="Scan now for new actions">"
><__trans phrase="Update Now"></a>
</mt:setvarblock>
<mt:var name="position_actions_top" value="1">
<mt:include name="include/header.tmpl">
<mtapp:listing type="profile" loop="profiles" empty_message="No profiles were found." hide_pager="1">
<mt:if __first__>
<thead>
<tr>
<th class="cb"><input type="checkbox" name="id-head" value="all" class="select" /></th>
<th class="service"><span class="service-icon"><__trans phrase="Service"></span></th>
<th class="userid"><__trans phrase="Username"></th>
<th class="view"><__trans phrase="View"></th>
</tr>
</thead>
<tbody>
</mt:if>
<tr class="<mt:if __odd__>odd<mt:else>even</mt:if>">
<td class="cb"><input type="checkbox" name="id" class="select" value="<mt:var name="edit_author_id" escape="html">:<mt:var name="type" escape="html">:<mt:var name="ident" escape="html">" /></td>
<td class="service network"><span class="service-icon service-<mt:var name="type">"><a href="javascript:void(0)" onclick="return openDialog(this.form, 'dialog_edit_profile', 'author_id=<mt:var name="edit_author_id">&profile_type=<mt:var name="type" escape="url">&profile_ident=<mt:var name="ident" escape="url">&return_args=<mt:var name="return_args" escape="url">%26author_id=<mt:var name="edit_author_id">')"><mt:var name="label" escape="html"></a></span></td>
<td class="userid"><mt:var name="ident" escape="html"></td>
<td class="view si status-view">
<a href="<mt:var name="uri" escape="html">" target="<__trans phrase="external_link_target">" title="<__trans phrase="View Profile">"><img src="<mt:var name="static_uri">images/spacer.gif" alt="<__trans phrase="View Profile">" width="13" height="9" /></a>
</td>
</tr>
<mt:if __last__>
</tbody>
</mt:if>
</mtapp:listing>
<mt:include name="include/footer.tmpl">
|
markpasc/mt-plugin-action-streams
|
4cb12789ce9670404cd822f1f153f07de577a766
|
Let OtherProfileVar work in the ActionStreams tag, even if it is occasionally wrong BugzID: 91839
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Tags.pm b/plugins/ActionStreams/lib/ActionStreams/Tags.pm
index 88c0ace..15b5aba 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Tags.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Tags.pm
@@ -1,467 +1,469 @@
package ActionStreams::Tags;
use strict;
use MT::Util qw( offset_time_list epoch2ts ts2epoch );
use ActionStreams::Plugin;
sub stream_action {
my ($ctx, $args, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamAction in a non-action-stream context!");
return $event->as_html(
defined $args->{name} ? (name => $args->{name}) : ()
);
}
sub stream_action_id {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionURL in a non-action-stream context!");
return $event->id || '';
}
sub stream_action_var {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionVar in a non-action-stream context!");
my $var = $arg->{var} || $arg->{name}
or return $ctx->error("Used StreamActionVar without a 'name' attribute!");
return $ctx->error("Use StreamActionVar to retrieve invalid variable $var from event of type " . ref $event)
if !$event->can($var) && !$event->has_column($var);
return $event->$var();
}
sub stream_action_date {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionDate in a non-action-stream context!");
my $c_on = $event->created_on;
local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $c_on) )
if $c_on;
return $ctx->_hdlr_date($arg);
}
sub stream_action_modified_date {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionModifiedDate in a non-action-stream context!");
my $m_on = $event->modified_on || $event->created_on;
local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $m_on) )
if $m_on;
return $ctx->_hdlr_date($arg);
}
sub stream_action_title {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionTitle in a non-action-stream context!");
return $event->title || '';
}
sub stream_action_url {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionURL in a non-action-stream context!");
return $event->url || '';
}
sub stream_action_thumbnail_url {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionThumbnailURL in a non-action-stream context!");
return $event->thumbnail || '';
}
sub stream_action_via {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionVia in a non-action-stream context!");
return $event->via || q{};
}
sub other_profile_var {
my( $ctx, $args ) = @_;
my $profile = $ctx->stash( 'other_profile' )
or return $ctx->error( 'No profile defined in ProfileVar' );
my $var = $args->{name} || 'uri';
return defined $profile->{ $var } ? $profile->{ $var } : '';
}
sub _author_ids_for_args {
my ($ctx, $args, $cond) = @_;
my @author_ids;
if (my $ids = $args->{author_ids} || $args->{author_id}) {
@author_ids = split /\s*,\s*/, $ids;
}
elsif (my $disp_names = $args->{display_names} || $args->{display_name}) {
my @names = split /\s*,\s*/, $disp_names;
my @authors = MT->model('author')->load({ nickname => \@names });
@author_ids = map { $_->id } @authors;
}
elsif (my $names = $args->{author} || $args->{authors}) {
# If arg is the special string 'all', then include all authors by returning undef instead of an empty array.
return if $names =~ m{ \A\s* all \s*\z }xmsi;
my @names = split /\s*,\s*/, $names;
my @authors = MT->model('author')->load({ name => \@names });
@author_ids = map { $_->id } @authors;
}
elsif (my $author = $ctx->stash('author')) {
@author_ids = ( $author->id );
}
elsif (my $blog = $ctx->stash('blog')) {
my @authors = MT->model('author')->load({
status => 1, # enabled
}, {
join => MT->model('permission')->join_on('author_id',
{ blog_id => $blog->id }, { unique => 1 }),
});
@author_ids = map { $_->[0]->id }
grep { $_->[1]->can_administer_blog || $_->[1]->can_create_post }
map { [ $_, $_->permissions($blog->id) ] }
@authors;
}
return \@author_ids;
}
sub action_streams {
my ($ctx, $args, $cond) = @_;
my %terms = (
class => '*',
visible => 1,
);
my $author_id = _author_ids_for_args(@_);
$terms{author_id} = $author_id if defined $author_id;
my %args = (
sort => ($args->{sort_by} || 'created_on'),
direction => ($args->{direction} || 'descend'),
);
my $app = MT->app;
undef $app unless $app->isa('MT::App');
if (my $limit = $args->{limit} || $args->{lastn}) {
$args{limit} = $limit eq 'auto' ? ( $app ? $app->param('limit') : 20 ) : $limit;
}
elsif (my $days = $args->{days}) {
my @ago = offset_time_list(time - 3600 * 24 * $days,
$ctx->stash('blog'));
my $ago = sprintf "%04d%02d%02d%02d%02d%02d",
$ago[5]+1900, $ago[4]+1, @ago[3,2,1,0];
$terms{created_on} = [ $ago ];
$args{range_incl}{created_on} = 1;
}
else {
$args{limit} = 20;
}
if (my $offset = $args->{offset}) {
if ($offset eq 'auto') {
$args{offset} = $app->param('offset')
if $app && $app->param('offset') > 0;
}
elsif ($offset =~ m/^\d+$/) {
$args{offset} = $offset;
}
}
my ($service, $stream) = @$args{qw( service stream )};
if ($service && $stream) {
$terms{class} = join q{_}, $service, $stream;
}
elsif ($service) {
$terms{class} = $service . '_%';
$args{like} = { class => 1 };
}
elsif ($stream) {
$terms{class} = '%_' . $stream;
$args{like} = { class => 1 };
}
# Make sure all classes are loaded.
require ActionStreams::Event;
for my $service (keys %{ MT->instance->registry('action_streams') || {} }) {
ActionStreams::Event->classes_for_type($service);
}
my @events = ActionStreams::Event->search(\%terms, \%args);
return $ctx->_hdlr_pass_tokens_else($args, $cond)
if !@events;
if ($args{sort} eq 'created_on') {
@events = sort { $b->created_on cmp $a->created_on || $b->id <=> $a->id } @events;
@events = reverse @events
if $args{direction} ne 'descend';
}
local $ctx->{__stash}{remaining_stream_actions} = \@events;
my $res = '';
my ($count, $total) = (0, scalar @events);
my $day_date = '';
EVENT: while (my $event = shift @events) {
my $new_day_date = _event_day($ctx, $event);
local $cond->{DateHeader} = $day_date ne $new_day_date ? 1 : 0;
local $cond->{DateFooter} = !@events ? 1
: $new_day_date ne _event_day($ctx, $events[0]) ? 1
: 0
;
$day_date = $new_day_date;
$count++;
defined (my $out = _build_about_event(
$ctx, $args, $cond,
event => $event,
count => $count,
total => $total,
)) or return;
$res .= $out;
}
return $res;
}
sub _build_about_event {
my ($ctx, $arg, $cond, %param) = @_;
my ($event, $count, $total) = @param{qw( event count total )};
local $ctx->{__stash}{stream_action} = $event;
my $author = $event->author;
local $ctx->{__stash}{author} = $event->author;
my $type = $event->class_type;
my ($service, $stream_id) = split /_/, $type, 2;
- my $profile = $author->other_profiles($service);
- next EVENT if !$profile;
- local $ctx->{__stash}{other_profile} = $profile;
+ # TODO: find from the event which other_profile is really associated
+ # instead of guessing it's the first one.
+ my $profiles = $author->other_profiles($service);
+ next EVENT if !$profiles || !@$profiles;
+ local ($ctx->{__stash}{other_profile}) = @$profiles;
my $vars = $ctx->{__stash}{vars} ||= {};
local $vars->{action_type} = $type;
local $vars->{service_type} = $service;
local $vars->{stream_type} = $stream_id;
local $vars->{__first__} = $count == 1;
local $vars->{__last__} = $count == $total;
local $vars->{__odd__} = ($count % 2) == 1;
local $vars->{__even__} = ($count % 2) == 0;
local $vars->{__counter__} = $count;
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
defined(my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error($builder->errstr);
return $out;
}
sub stream_action_rollup {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionRollup in a non-action-stream context!");
my $nexts = $ctx->stash('remaining_stream_actions');
return $ctx->else($arg, $cond)
if !$nexts || !@$nexts;
my $by_spec = $arg->{by} || 'date,action';
my %by = map { $_ => 1 } split /\s*,\s*/, $by_spec;
my $event_date = _event_day($ctx, $event);
my $event_class = $event->class;
my ($event_service, $event_stream) = split /_/, $event_class, 2;
my @rollup_events = ($event);
EVENT: while (@$nexts) {
my $next = $nexts->[0];
last EVENT if $by{date} && $event_date ne _event_day($ctx, $next);
last EVENT if $by{action} && $event_class ne $next->class;
last EVENT if $by{stream} && $next->class !~ m{ _ \Q$event_stream\E \z }xms;
last EVENT if $by{service} && $next->class !~ m{ \A \Q$event_service\E _ }xms;
# Eligible to roll up! Remove it from the remaining actions.
push @rollup_events, shift @$nexts;
}
return $ctx->else($arg, $cond)
if 1 >= scalar @rollup_events;
my $res;
my $count = 0;
for my $rup_event (@rollup_events) {
$count++;
defined (my $out = _build_about_event(
$ctx, $arg, $cond,
event => $rup_event,
count => $count,
total => scalar @rollup_events,
)) or return;
$res .= $arg->{glue} if $arg->{glue} && $count > 1;
$res .= $out;
}
return $res;
}
sub _event_day {
my ($ctx, $event) = @_;
return substr(epoch2ts($ctx->stash('blog'), ts2epoch(undef, $event->created_on)), 0, 8);
}
sub stream_action_tags {
my ($ctx, $args, $cond) = @_;
require MT::Entry;
my $event = $ctx->stash('stream_action');
return '' unless $event;
my $glue = $args->{glue} || '';
local $ctx->{__stash}{tag_max_count} = undef;
local $ctx->{__stash}{tag_min_count} = undef;
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
my $res = '';
my $tags = $event->get_tag_objects;
for my $tag (@$tags) {
next if $tag->is_private && !$args->{include_private};
local $ctx->{__stash}{Tag} = $tag;
local $ctx->{__stash}{tag_count} = undef;
local $ctx->{__stash}{tag_event_count} = undef; # ?
defined(my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error( $builder->errstr );
$res .= $glue if $res ne '';
$res .= $out;
}
$res;
}
sub other_profiles {
my( $ctx, $args, $cond ) = @_;
my $author_ids = _author_ids_for_args(@_);
my $author_id = shift @$author_ids
or return $ctx->error('No author specified for OtherProfiles');
my $user = MT->model('author')->load($author_id)
or return $ctx->error(MT->trans('No user [_1]', $author_id));
my @profiles = @{ $user->other_profiles() };
my $services = MT->app->registry('profile_services');
if (my $filter_type = $args->{type}) {
my $filter_except = $filter_type =~ s{ \A NOT \s+ }{}xmsi ? 1 : 0;
@profiles = grep {
my $profile = $_;
my $profile_type = $profile->{type};
my $service_type = ($services->{$profile_type} || {})->{service_type} || q{};
$filter_except ? $service_type ne $filter_type : $service_type eq $filter_type;
} @profiles;
}
@profiles = map { $_->[1] }
sort { $a->[0] cmp $b->[0] }
map { [ lc (($services->{ $_->{type} } || {})->{name} || q{}), $_ ] }
@profiles;
my $populate_icon = sub {
my ($item, $row) = @_;
my $type = $item->{type};
$row->{vars}{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $services->{$type});
};
return list(
context => $ctx,
arguments => $args,
conditions => $cond,
items => \@profiles,
stash_key => 'other_profile',
code => $populate_icon,
);
}
sub list {
my %param = @_;
my ($ctx, $args, $cond) = @param{qw( context arguments conditions )};
my ($items, $stash_key, $code) = @param{qw( items stash_key code )};
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
my $res = q{};
my $glue = $args->{glue};
$glue = '' unless defined $glue;
my $vars = ($ctx->{__stash}{vars} ||= {});
my ($count, $total) = (0, scalar @$items);
for my $item (@$items) {
local $ctx->{__stash}->{$stash_key} = $item;
my $row = {};
$code->($item, $row) if $code;
my $lvars = delete $row->{vars} if exists $row->{vars};
local @$vars{keys %$lvars} = values %$lvars
if $lvars;
local @{ $ctx->{__stash} }{keys %$row} = values %$row;
$count++;
my %loop_vars = (
__first__ => $count == 1,
__last__ => $count == $total,
__odd__ => $count % 2,
__even__ => !($count % 2),
__counter__ => $count,
);
local @$vars{keys %loop_vars} = values %loop_vars;
defined (my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error($builder->errstr);
$res .= $glue if ($res ne '') && ($out ne '') && ($glue ne '');
$res .= $out;
}
return $res;
}
sub profile_services {
my( $ctx, $args, $cond ) = @_;
my $app = MT->app;
my $networks = $app->registry('profile_services');
my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
keys %$networks;
my $out = "";
my $builder = $ctx->stash( 'builder' );
my $tokens = $ctx->stash( 'tokens' );
my $vars = ($ctx->{__stash}{vars} ||= {});
if ($args->{extra}) {
# Skip output completely if it's a "core" service but we want
# extras only.
@network_keys = grep { ! $networks->{$_}->{plugin} || ($networks->{$_}->{plugin}->id ne 'actionstreams') } @network_keys;
}
my ($count, $total) = (0, scalar @network_keys);
for my $type (@network_keys) {
$count++;
my %loop_vars = (
__first__ => $count == 1,
__last__ => $count == $total,
__odd__ => $count % 2,
__even__ => !($count % 2),
__counter__ => $count,
);
local @$vars{keys %loop_vars} = values %loop_vars;
my $ndata = $networks->{$type};
local @$vars{keys %$ndata} = values %$ndata;
local $vars->{label} = $ndata->{name};
local $vars->{type} = $type;
local $vars->{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $networks->{$type});
local $ctx->{__stash}{profile_service} = $ndata;
$out .= $builder->build( $ctx, $tokens, $cond );
}
return $out;
}
1;
|
markpasc/mt-plugin-action-streams
|
dea6c8aafd54a24311d00dee360d64e84587948a
|
Document new Event::ua() params BugzID: 91767
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm
index 0a565ce..fb839d6 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm
@@ -192,578 +192,607 @@ sub update_events {
foreach => '//item',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $scraper_params = $stream->{scraper}) {
my ($foreach, $get) = @$scraper_params{qw( foreach get )};
my $scraper = scraper {
process $foreach, 'res[]' => scraper {
while (my ($field, $sel) = each %$get) {
process $sel->[0], $field => $sel->[1];
}
};
result 'res';
};
$items = $class->fetch_scraper(
scraper => $scraper,
%$fetch,
%profile,
);
}
return if !$items;
$class->build_results(
items => $items,
stream => $stream,
author => $author,
profile => \%profile,
);
}
sub registry_entry {
my $event = shift;
my ($type, $stream) = split /_/, $event->properties->{class_type}, 2;
my $reg = MT->instance->registry('action_streams') or return;
my $service = $reg->{$type} or return;
$service->{$stream};
}
sub author {
my $event = shift;
my $author_id = $event->author_id
or return;
return MT->instance->model('author')->lookup($author_id);
}
sub blog_id { 0 }
sub classes_for_type {
my $class = shift;
my ($type) = @_;
my $prevts = MT->instance->registry('action_streams');
my $prevt = $prevts->{$type};
return if !$prevt;
my @classes;
PACKAGE: while (my ($stream_id, $stream) = each %$prevt) {
next if 'HASH' ne ref $stream;
next if !$stream->{class} && !$stream->{url};
my $pkg;
if ($pkg = $stream->{class}) {
$pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms;
if (!eval { $pkg->properties }) {
if (!eval "require $pkg; 1") {
my $error = $@ || q{};
my $pl = MT->component('ActionStreams');
MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]',
$pkg, $type, $stream_id, $error));
next PACKAGE;
}
}
}
else {
$pkg = join q{::}, $class, 'Auto', ucfirst $type,
ucfirst $stream_id;
if (!eval { $pkg->properties }) {
eval "package $pkg; use base qw( $class ); 1" or next;
my $class_type = join q{_}, $type, $stream_id;
$pkg->install_properties({ class_type => $class_type });
$pkg->install_meta({ columns => $stream->{fields} })
if $stream->{fields};
}
}
push @classes, $pkg;
}
return @classes;
}
my $ua;
sub ua {
my $class = shift;
my %params = @_;
$ua ||= MT->new_ua({
paranoid => 1,
timeout => 10,
});
$ua->max_size(250_000) if $ua->can('max_size');
$ua->agent($params{default_useragent} ? $ua->_agent
: "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version);
return $ua if $class->class_type eq 'event';
return $ua if $params{unconditional};
require ActionStreams::UserAgent::Adapter;
my $adapter = ActionStreams::UserAgent::Adapter->new(
ua => $ua,
action_type => $class->class_type,
die_on_not_modified => $params{die_on_not_modified} || 0,
);
return $adapter;
}
sub set_values {
my $event = shift;
my ($values) = @_;
for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) {
my $meta_val = delete $values->{$meta_col};
$event->$meta_col($meta_val) if defined $meta_val;
}
$event->SUPER::set_values($values);
}
sub fetch_xpath {
my $class = shift;
my %params = @_;
my $url = $params{url} || '';
if (!$url) {
MT->log("No URL to fetch for $class results");
return;
}
my $ua = $class->ua(%params);
my $res = $ua->get($url);
if (!$res->is_success()) {
MT->log("Could not fetch ${url}: " . $res->status_line())
if $res->code != 304;
return;
}
# Strip leading whitespace, since the parser doesn't like it.
# TODO: confirm we got xml?
my $content = $res->content;
$content =~ s{ \A \s+ }{}xms;
require XML::XPath;
my $x = XML::XPath->new( xml => $content );
my @items;
ITEM: for my $item ($x->findnodes($params{foreach})) {
my %item_data;
VALUE: while (my ($key, $val) = each %{ $params{get} }) {
next VALUE if !$val;
if ($key eq 'tags') {
my @outvals = $item->findnodes($val)
or next VALUE;
$item_data{$key} = [ map { $_->getNodeValue } @outvals ];
}
else {
my $outval = $item->findvalue($val)
or next VALUE;
$outval = "$outval";
if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) {
# try both RFC 822/1123 and ISO 8601 formats
$outval = MT::Util::epoch2ts(undef, str2time($outval))
|| MT::Util::iso2ts(undef, $outval);
}
$item_data{$key} = $outval if $outval;
}
}
push @items, \%item_data;
}
return \@items;
}
sub build_results {
my $class = shift;
my %params = @_;
my ($author, $items, $profile, $stream) =
@params{qw( author items profile stream )};
my $mt = MT->app;
ITEM: for my $item (@$items) {
my $event;
my $identifier = delete $item->{identifier};
if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) {
$identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} };
}
if (defined $identifier) {
$identifier = "$identifier";
($event) = $class->search({
author_id => $author->id,
identifier => $identifier,
});
}
$event ||= $class->new;
$mt->run_callbacks('pre_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
my $tags = delete $item->{tags};
$event->set_values({
author_id => $author->id,
identifier => $identifier,
%$item,
});
$event->tags(@$tags) if $tags;
if ($hide_timeless && !$event->created_on) {
$event->visible(0);
}
$mt->run_callbacks('post_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
$event->save() or MT->log($event->errstr);
}
1;
}
sub save {
my $event = shift;
# Built-in audit field setting will set a local time, so do it ourselves.
if (!$event->created_on) {
my $ts = MT::Util::epoch2ts(undef, time);
$event->created_on($ts);
$event->modified_on($ts);
}
return $event->SUPER::save(@_);
}
sub fetch_scraper {
my $class = shift;
my %params = @_;
my ($url, $scraper) = @params{qw( url scraper )};
$scraper->user_agent( $class->ua( %params, die_on_not_modified => 1 ) );
my $uri_obj = URI->new($url);
my $items = eval { $scraper->scrape($uri_obj) };
# Ignore Web::Scraper errors due to 304 Not Modified responses.
if (!$items && $@ && !UNIVERSAL::isa($@, 'ActionStreams::UserAgent::NotModified')) {
die; # rethrow
}
# we're only being used for our scraper.
return if !$items;
return $items if !ref $items;
return $items if 'ARRAY' ne ref $items;
ITEM: for my $item (@$items) {
next ITEM if !ref $item || ref $item ne 'HASH';
for my $field (keys %$item) {
if ($field eq 'tags') {
$item->{$field} = [ map { "$_" } @{ $item->{$field} } ];
}
else {
$item->{$field} = q{} . $item->{$field};
}
}
}
return $items;
}
1;
__END__
=head1 NAME
ActionStreams::Event - an Action Streams stream definition
=head1 SYNOPSIS
# in plugin's config.yaml
profile_services:
example:
streamid:
name: Dice Example
description: A simple die rolling Perl stream example.
html_form: [_1] rolled a [_2]!
html_params:
- title
class: My::Stream
# in plugin's lib/My/Stream.pm
package My::Stream;
use base qw( ActionStreams::Event );
__PACKAGE__->install_properties({
class_type => 'example_streamid',
});
sub update_events {
my $class = shift;
my %profile = @_;
# trivial example: save a random number
my $die_roll = int rand 20;
my %item = (
title => $die_roll,
identifier => $die_roll,
);
return $class->build_results(
author => $profile{author},
items => [ \%item ],
);
}
1;
=head1 DESCRIPTION
I<ActionStreams::Event> provides the basic implementation of an action stream.
Stream definitions are engines for turning web resources into I<actions> (also
called I<events>). This base class produces actions based on generic stream
recipes defined in the MT registry, as well as providing the internal machinery
for you to implement your own streams in Perl code.
=head1 METHODS TO IMPLEMENT
These are the methods one commonly implements (overrides) when implementing a
stream subclass.
=head2 C<$class-E<gt>update_events(%profile)>
Fetches the web resource specified by the profile parameters, collects data
from it into actions, and saves the action records for use later. Required
members of C<%profile> are:
=over 4
=item * C<author>
The C<MT::Author> instance for whom events should be collected.
=item * C<ident>
The author's identifier on the given service.
=back
Other information about the stream, such as the URL pattern into which the
C<ident> parameter can be replaced, is available through the
C<$class-E<gt>registry_entry()> method.
=head2 C<$self-E<gt>as_html(%params)>
Returns the HTML version of the action, suitable for display to readers.
The default implementation uses the stream's registry definition to construct
the action: the author's name and the action's values as named in
C<html_params> are replaced into the stream's C<html_form> setting. You need
override it only if you have more complex requirements.
Optional members of C<%params> are:
=over 4
=item * C<form>
The formatting string to use. If not given, the C<html_form> specified for
this stream in the registry is used.
=item * C<name>
The text to use as the author's name if C<as_html> needs to provide it
automatically in the result. Author names are provided if there are more
tokens in C<html_form> than there are fields specified in C<html_params>.
If not given, the event's author's nickname is provided. Note that a defined
but empty name (such as C<q{}>) I<will> be used; in this case, the name will
appear to be omitted from the result of the C<as_html> call.
=back
=head1 AVAILABLE METHODS
These are the methods provided by I<ActionStreams::Event> to perform common
tasks. Call them from your overridden methods.
=head2 C<$self-E<gt>set_values(\%values)>
Stores the data given in C<%values> as members of this event.
=head2 C<$class-E<gt>fetch_xpath(%param)>
Returns the items discovered by scanning a web resource by the given XPath
recipe. Required members of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be a
valid XML document.
=item * C<foreach>
The XPath selector with which to select the individual events from the
resource.
=item * C<get>
A hashref containing the XPath selectors with which to collect individual data
for each item, keyed on the names of the fields to contain the data.
=back
C<%param> may also contain additional arguments for the C<ua()> method.
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
=head2 C<$class-E<gt>fetch_scraper(%param)>
Returns the items discovered by scanning by the given recipe. Required members
of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be an
HTML or XML document suitable for analysis by the C<Web::Scraper> module.
=item * C<scraper>
The C<Web::Scraper> scraper with which to extract item data from the specified
web resource. See L<Web::Scraper> for information on how to construct a
scraper.
=back
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
See also the below I<NOTE ON WEB::SCRAPER>.
=head2 C<$class-E<gt>build_results(%param)>
Converts a set of collected items into saved action records of type C<$class>.
The required members of C<%param> are:
=over 4
=item * C<author>
The C<MT::Author> instance whose action the items represent.
=item * C<items>
An arrayref of items to save as actions. Each item is a hashref containing the
action data, keyed on the names of the fields containing the data.
=back
Optional parameters are:
=over 4
=item * C<profile>
An arrayref describing the data for the author's profile for the associated
stream, such as is returned by the C<MT::Author::other_profile()> method
supplied by the Action Streams plugin.
The profile member is not used directly by C<build_results()>; they are only
passed to callbacks.
=item * C<stream>
A hashref containing the settings from the registry about the stream, such as
is returned from the C<registry_entry()> method.
=back
=head2 C<$class-E<gt>ua(%param)>
Returns the common HTTP user-agent, an instance of C<LWP::UserAgent>, with
-which you can fetch web resources. No arguments are required; possible optional
-parameters are:
+which you can fetch web resources.
+
+The resulting user agent may provide automatic conditional HTTP support when
+you call its C<get> method. A UA with conditional HTTP support enabled will
+store the values of the conditional HTTP headers (C<ETag> and
+C<Last-Modified>) received in responses as C<ActionStreams::UserAgent::Cache>
+objects and, on subsequent requests of the same URL, automatically supply the
+header values. When the remote HTTP server reports that such a resource has
+not changed, the C<HTTP::Response> will be a C<304 Not Modified> response; the
+user agent does not itself store and supply the resource content. Using other
+C<LWP::UserAgent> methods such as C<post> or C<request> will I<not> trigger
+automatic conditional HTTP support.
+
+No arguments are required; possible optional parameters are:
=over 4
=item * C<default_useragent>
If set, the returned HTTP user-agent will use C<LWP::UserAgent>'s default
identifier in the HTTP C<User-Agent> header. If omitted, the UA will use the
Action Streams identifier of C<mt-actionstreams-lwp/I<version>>.
+=item * C<unconditional>
+
+If set, the return HTTP user-agent will I<not> automatically use conditional
+HTTP to avoid requesting old content from compliant servers. That is, if
+omitted, the UA I<will> automatically use conditional HTTP when you call its
+C<get> method.
+
+=item * C<die_on_not_modified>
+
+If set, when the response of the HTTP user-agent's C<get> method is a
+conditional HTTP C<304 Not Modified> response, throw an exception instead of
+returning the response. (Use this option to return control to yourself when
+passing UAs with conditional HTTP support to other Perl modules that don't
+expect 304 responses.)
+
+The thrown exception is an C<ActionStreams::UserAgent::NotModified> exception.
+
=back
=head2 C<$self-E<gt>author()>
Returns the C<MT::Author> instance associated with this event, if its
C<author_id> field has been set.
=head2 C<$class-E<gt>install_properties(\%properties)>
I<TODO>
=head2 C<$class-E<gt>install_meta(\%properties)>
I<TODO>
=head2 C<$class-E<gt>registry_entry()>
Returns the registry data for the stream represented by C<$class>.
=head2 C<$class-E<gt>classes_for_type($service_id)>
Given a profile service ID (that is, a key from the C<profile_services> section
of the registry), returns a list of stream classes for scanning that service's
streams.
=head1 NOTE ON WEB::SCRAPER
The C<Web::Scraper> module is powerful, but it has complex dependencies. While
its pure Perl requirements are bundled with the Action Streams plugin, it also
requires a compiled XML module. Also, because of how its syntax works, you must
directly C<use> the module in your own code, contrary to the Movable Type idiom
of using C<require> so that modules are loaded only when they are sure to be
used.
If you attempt load C<Web::Scraper> in the normal way, but C<Web::Scraper> is
unable to load due to its missing requirement, whenever the plugin attempts to
load your scraper, the entire plugin will fail to load.
Therefore the C<ActionStreams::Scraper> wrapper module is provided for you. If
you need to load C<Web::Scraper> so as to make a scraper to pass
C<ActionStreams::Event::fetch_scraper()> method, instead write in your module:
use ActionStreams::Scraper;
This module provides the C<Web::Scraper> interface, but if C<Web::Scraper> is
unable to load, the error will be thrown when your module tries to I<use> it,
rather than when you I<load> it. That is, if C<Web::Scraper> can't load, no
errors will be thrown to end users until they try to use your stream.
=head1 AUTHOR
Mark Paschal E<lt>[email protected]<gt>
=cut
|
markpasc/mt-plugin-action-streams
|
99358d5bba5bcb5449e606899a52e76a4bb7b5b4
|
Always fetch the HTML page for a Website profile anyway (we still need those URLs to check the feeds, even if the HTML page was Not Modified) BugzID: 91767
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm
index d63a174..0a565ce 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm
@@ -1,768 +1,769 @@
package ActionStreams::Event;
use strict;
use base qw( MT::Object MT::Taggable MT::Scorable );
our @EXPORT_OK = qw( classes_for_type );
use HTTP::Date qw( str2time );
use MT::Util qw( encode_html );
use ActionStreams::Scraper;
our $hide_timeless = 0;
__PACKAGE__->install_properties({
column_defs => {
id => 'integer not null auto_increment',
identifier => 'string(200)',
author_id => 'integer not null',
visible => 'integer not null',
},
defaults => {
visible => 1,
},
indexes => {
identifier => 1,
author_id => 1,
created_on => 1,
created_by => 1,
},
class_type => 'event',
audit => 1,
meta => 1,
datasource => 'profileevent',
primary_key => 'id',
});
__PACKAGE__->install_meta({
columns => [ qw(
title
url
thumbnail
via
via_id
) ],
});
# Oracle does not like an identifier of more than 30 characters.
sub datasource {
my $class = shift;
my $r = MT->request;
my $ds = $r->cache('as_event_ds');
return $ds if $ds;
my $dss_oracle = qr/(db[id]::)?oracle/;
if ( my $type = MT->config('ObjectDriver') ) {
if ((lc $type) =~ m/^$dss_oracle$/) {
$ds = 'as';
}
}
$ds = $class->properties->{datasource}
unless $ds;
$r->cache('as_event_ds', $ds);
return $ds;
}
sub encode_field_for_html {
my $event = shift;
my ($field) = @_;
return encode_html( $event->$field() );
}
sub as_html {
my $event = shift;
my %params = @_;
my $stream = $event->registry_entry or return '';
# How many spaces are there in the form?
my $form = $params{form} || $stream->{html_form} || q{};
my @nums = $form =~ m{ \[ _ (\d+) \] }xmsg;
my $max = shift @nums;
for my $num (@nums) {
$max = $num if $max < $num;
}
# Do we need to supply the author name?
my @content = map { $event->encode_field_for_html($_) }
@{ $stream->{html_params} };
if ($max > scalar @content) {
my $name = defined $params{name} ? $params{name}
: $event->author->nickname
;
unshift @content, encode_html($name);
}
return MT->translate($form, @content);
}
sub update_events_loggily {
my $class = shift;
my %profile = @_;
# Keep this option out of band so we don't have to count on
# implementations of update_events() passing it through.
local $hide_timeless = delete $profile{hide_timeless} ? 1 : 0;
my $warn = $SIG{__WARN__} || sub { print STDERR $_[0] };
local $SIG{__WARN__} = sub {
my ($msg) = @_;
$msg =~ s{ \n \z }{}xms;
$msg = MT->component('ActionStreams')->translate(
'[_1] updating [_2] events for [_3]',
$msg, $profile{type}, $profile{author}->name,
);
$warn->("$msg\n");
};
eval {
$class->update_events(%profile);
};
if (my $err = $@) {
my $plugin = MT->component('ActionStreams');
my $err_msg = $plugin->translate("Error updating events for [_1]'s [_2] stream (type [_3] ident [_4]): [_5]",
$profile{author}->name, $class->properties->{class_type},
$profile{type}, $profile{ident}, $err);
MT->log($err_msg);
die $err; # re-throw so we can handle from job invocation
}
}
sub update_events {
my $class = shift;
my %profile = @_;
my $author = delete $profile{author};
my $stream = $class->registry_entry or return;
my $fetch = $stream->{fetch} || {};
local $profile{url} = $stream->{url};
die "Oops, no url?" if !$profile{url};
die "Oops, no ident?" if !$profile{ident};
$profile{url} =~ s/ {{ident}} / $profile{ident} /xmsge;
my $items;
if (my $xpath_params = $stream->{xpath}) {
$items = $class->fetch_xpath(
%$xpath_params,
%$fetch,
%profile,
);
}
elsif (my $atom_params = $stream->{atom}) {
my $get = {
created_on => 'published',
modified_on => 'updated',
title => 'title',
url => q{link[@rel='alternate']/@href},
via => q{link[@rel='alternate']/@href},
via_id => 'id',
identifier => 'id',
};
$atom_params = {} if !ref $atom_params;
@$get{keys %$atom_params} = values %$atom_params;
$items = $class->fetch_xpath(
foreach => '//entry',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $rss_params = $stream->{rss}) {
my $get = {
title => 'title',
url => 'link',
via => 'link',
created_on => 'pubDate',
thumbnail => 'media:thumbnail/@url',
via_id => 'guid',
identifier => 'guid',
};
$rss_params = {} if !ref $rss_params;
@$get{keys %$rss_params} = values %$rss_params;
$items = $class->fetch_xpath(
foreach => '//item',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $scraper_params = $stream->{scraper}) {
my ($foreach, $get) = @$scraper_params{qw( foreach get )};
my $scraper = scraper {
process $foreach, 'res[]' => scraper {
while (my ($field, $sel) = each %$get) {
process $sel->[0], $field => $sel->[1];
}
};
result 'res';
};
$items = $class->fetch_scraper(
scraper => $scraper,
%$fetch,
%profile,
);
}
return if !$items;
$class->build_results(
items => $items,
stream => $stream,
author => $author,
profile => \%profile,
);
}
sub registry_entry {
my $event = shift;
my ($type, $stream) = split /_/, $event->properties->{class_type}, 2;
my $reg = MT->instance->registry('action_streams') or return;
my $service = $reg->{$type} or return;
$service->{$stream};
}
sub author {
my $event = shift;
my $author_id = $event->author_id
or return;
return MT->instance->model('author')->lookup($author_id);
}
sub blog_id { 0 }
sub classes_for_type {
my $class = shift;
my ($type) = @_;
my $prevts = MT->instance->registry('action_streams');
my $prevt = $prevts->{$type};
return if !$prevt;
my @classes;
PACKAGE: while (my ($stream_id, $stream) = each %$prevt) {
next if 'HASH' ne ref $stream;
next if !$stream->{class} && !$stream->{url};
my $pkg;
if ($pkg = $stream->{class}) {
$pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms;
if (!eval { $pkg->properties }) {
if (!eval "require $pkg; 1") {
my $error = $@ || q{};
my $pl = MT->component('ActionStreams');
MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]',
$pkg, $type, $stream_id, $error));
next PACKAGE;
}
}
}
else {
$pkg = join q{::}, $class, 'Auto', ucfirst $type,
ucfirst $stream_id;
if (!eval { $pkg->properties }) {
eval "package $pkg; use base qw( $class ); 1" or next;
my $class_type = join q{_}, $type, $stream_id;
$pkg->install_properties({ class_type => $class_type });
$pkg->install_meta({ columns => $stream->{fields} })
if $stream->{fields};
}
}
push @classes, $pkg;
}
return @classes;
}
my $ua;
sub ua {
my $class = shift;
my %params = @_;
$ua ||= MT->new_ua({
paranoid => 1,
timeout => 10,
});
$ua->max_size(250_000) if $ua->can('max_size');
$ua->agent($params{default_useragent} ? $ua->_agent
: "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version);
return $ua if $class->class_type eq 'event';
+ return $ua if $params{unconditional};
require ActionStreams::UserAgent::Adapter;
my $adapter = ActionStreams::UserAgent::Adapter->new(
ua => $ua,
action_type => $class->class_type,
die_on_not_modified => $params{die_on_not_modified} || 0,
);
return $adapter;
}
sub set_values {
my $event = shift;
my ($values) = @_;
for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) {
my $meta_val = delete $values->{$meta_col};
$event->$meta_col($meta_val) if defined $meta_val;
}
$event->SUPER::set_values($values);
}
sub fetch_xpath {
my $class = shift;
my %params = @_;
my $url = $params{url} || '';
if (!$url) {
MT->log("No URL to fetch for $class results");
return;
}
my $ua = $class->ua(%params);
my $res = $ua->get($url);
if (!$res->is_success()) {
MT->log("Could not fetch ${url}: " . $res->status_line())
if $res->code != 304;
return;
}
# Strip leading whitespace, since the parser doesn't like it.
# TODO: confirm we got xml?
my $content = $res->content;
$content =~ s{ \A \s+ }{}xms;
require XML::XPath;
my $x = XML::XPath->new( xml => $content );
my @items;
ITEM: for my $item ($x->findnodes($params{foreach})) {
my %item_data;
VALUE: while (my ($key, $val) = each %{ $params{get} }) {
next VALUE if !$val;
if ($key eq 'tags') {
my @outvals = $item->findnodes($val)
or next VALUE;
$item_data{$key} = [ map { $_->getNodeValue } @outvals ];
}
else {
my $outval = $item->findvalue($val)
or next VALUE;
$outval = "$outval";
if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) {
# try both RFC 822/1123 and ISO 8601 formats
$outval = MT::Util::epoch2ts(undef, str2time($outval))
|| MT::Util::iso2ts(undef, $outval);
}
$item_data{$key} = $outval if $outval;
}
}
push @items, \%item_data;
}
return \@items;
}
sub build_results {
my $class = shift;
my %params = @_;
my ($author, $items, $profile, $stream) =
@params{qw( author items profile stream )};
my $mt = MT->app;
ITEM: for my $item (@$items) {
my $event;
my $identifier = delete $item->{identifier};
if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) {
$identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} };
}
if (defined $identifier) {
$identifier = "$identifier";
($event) = $class->search({
author_id => $author->id,
identifier => $identifier,
});
}
$event ||= $class->new;
$mt->run_callbacks('pre_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
my $tags = delete $item->{tags};
$event->set_values({
author_id => $author->id,
identifier => $identifier,
%$item,
});
$event->tags(@$tags) if $tags;
if ($hide_timeless && !$event->created_on) {
$event->visible(0);
}
$mt->run_callbacks('post_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
$event->save() or MT->log($event->errstr);
}
1;
}
sub save {
my $event = shift;
# Built-in audit field setting will set a local time, so do it ourselves.
if (!$event->created_on) {
my $ts = MT::Util::epoch2ts(undef, time);
$event->created_on($ts);
$event->modified_on($ts);
}
return $event->SUPER::save(@_);
}
sub fetch_scraper {
my $class = shift;
my %params = @_;
my ($url, $scraper) = @params{qw( url scraper )};
$scraper->user_agent( $class->ua( %params, die_on_not_modified => 1 ) );
my $uri_obj = URI->new($url);
my $items = eval { $scraper->scrape($uri_obj) };
# Ignore Web::Scraper errors due to 304 Not Modified responses.
if (!$items && $@ && !UNIVERSAL::isa($@, 'ActionStreams::UserAgent::NotModified')) {
die; # rethrow
}
# we're only being used for our scraper.
return if !$items;
return $items if !ref $items;
return $items if 'ARRAY' ne ref $items;
ITEM: for my $item (@$items) {
next ITEM if !ref $item || ref $item ne 'HASH';
for my $field (keys %$item) {
if ($field eq 'tags') {
$item->{$field} = [ map { "$_" } @{ $item->{$field} } ];
}
else {
$item->{$field} = q{} . $item->{$field};
}
}
}
return $items;
}
1;
__END__
=head1 NAME
ActionStreams::Event - an Action Streams stream definition
=head1 SYNOPSIS
# in plugin's config.yaml
profile_services:
example:
streamid:
name: Dice Example
description: A simple die rolling Perl stream example.
html_form: [_1] rolled a [_2]!
html_params:
- title
class: My::Stream
# in plugin's lib/My/Stream.pm
package My::Stream;
use base qw( ActionStreams::Event );
__PACKAGE__->install_properties({
class_type => 'example_streamid',
});
sub update_events {
my $class = shift;
my %profile = @_;
# trivial example: save a random number
my $die_roll = int rand 20;
my %item = (
title => $die_roll,
identifier => $die_roll,
);
return $class->build_results(
author => $profile{author},
items => [ \%item ],
);
}
1;
=head1 DESCRIPTION
I<ActionStreams::Event> provides the basic implementation of an action stream.
Stream definitions are engines for turning web resources into I<actions> (also
called I<events>). This base class produces actions based on generic stream
recipes defined in the MT registry, as well as providing the internal machinery
for you to implement your own streams in Perl code.
=head1 METHODS TO IMPLEMENT
These are the methods one commonly implements (overrides) when implementing a
stream subclass.
=head2 C<$class-E<gt>update_events(%profile)>
Fetches the web resource specified by the profile parameters, collects data
from it into actions, and saves the action records for use later. Required
members of C<%profile> are:
=over 4
=item * C<author>
The C<MT::Author> instance for whom events should be collected.
=item * C<ident>
The author's identifier on the given service.
=back
Other information about the stream, such as the URL pattern into which the
C<ident> parameter can be replaced, is available through the
C<$class-E<gt>registry_entry()> method.
=head2 C<$self-E<gt>as_html(%params)>
Returns the HTML version of the action, suitable for display to readers.
The default implementation uses the stream's registry definition to construct
the action: the author's name and the action's values as named in
C<html_params> are replaced into the stream's C<html_form> setting. You need
override it only if you have more complex requirements.
Optional members of C<%params> are:
=over 4
=item * C<form>
The formatting string to use. If not given, the C<html_form> specified for
this stream in the registry is used.
=item * C<name>
The text to use as the author's name if C<as_html> needs to provide it
automatically in the result. Author names are provided if there are more
tokens in C<html_form> than there are fields specified in C<html_params>.
If not given, the event's author's nickname is provided. Note that a defined
but empty name (such as C<q{}>) I<will> be used; in this case, the name will
appear to be omitted from the result of the C<as_html> call.
=back
=head1 AVAILABLE METHODS
These are the methods provided by I<ActionStreams::Event> to perform common
tasks. Call them from your overridden methods.
=head2 C<$self-E<gt>set_values(\%values)>
Stores the data given in C<%values> as members of this event.
=head2 C<$class-E<gt>fetch_xpath(%param)>
Returns the items discovered by scanning a web resource by the given XPath
recipe. Required members of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be a
valid XML document.
=item * C<foreach>
The XPath selector with which to select the individual events from the
resource.
=item * C<get>
A hashref containing the XPath selectors with which to collect individual data
for each item, keyed on the names of the fields to contain the data.
=back
C<%param> may also contain additional arguments for the C<ua()> method.
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
=head2 C<$class-E<gt>fetch_scraper(%param)>
Returns the items discovered by scanning by the given recipe. Required members
of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be an
HTML or XML document suitable for analysis by the C<Web::Scraper> module.
=item * C<scraper>
The C<Web::Scraper> scraper with which to extract item data from the specified
web resource. See L<Web::Scraper> for information on how to construct a
scraper.
=back
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
See also the below I<NOTE ON WEB::SCRAPER>.
=head2 C<$class-E<gt>build_results(%param)>
Converts a set of collected items into saved action records of type C<$class>.
The required members of C<%param> are:
=over 4
=item * C<author>
The C<MT::Author> instance whose action the items represent.
=item * C<items>
An arrayref of items to save as actions. Each item is a hashref containing the
action data, keyed on the names of the fields containing the data.
=back
Optional parameters are:
=over 4
=item * C<profile>
An arrayref describing the data for the author's profile for the associated
stream, such as is returned by the C<MT::Author::other_profile()> method
supplied by the Action Streams plugin.
The profile member is not used directly by C<build_results()>; they are only
passed to callbacks.
=item * C<stream>
A hashref containing the settings from the registry about the stream, such as
is returned from the C<registry_entry()> method.
=back
=head2 C<$class-E<gt>ua(%param)>
Returns the common HTTP user-agent, an instance of C<LWP::UserAgent>, with
which you can fetch web resources. No arguments are required; possible optional
parameters are:
=over 4
=item * C<default_useragent>
If set, the returned HTTP user-agent will use C<LWP::UserAgent>'s default
identifier in the HTTP C<User-Agent> header. If omitted, the UA will use the
Action Streams identifier of C<mt-actionstreams-lwp/I<version>>.
=back
=head2 C<$self-E<gt>author()>
Returns the C<MT::Author> instance associated with this event, if its
C<author_id> field has been set.
=head2 C<$class-E<gt>install_properties(\%properties)>
I<TODO>
=head2 C<$class-E<gt>install_meta(\%properties)>
I<TODO>
=head2 C<$class-E<gt>registry_entry()>
Returns the registry data for the stream represented by C<$class>.
=head2 C<$class-E<gt>classes_for_type($service_id)>
Given a profile service ID (that is, a key from the C<profile_services> section
of the registry), returns a list of stream classes for scanning that service's
streams.
=head1 NOTE ON WEB::SCRAPER
The C<Web::Scraper> module is powerful, but it has complex dependencies. While
its pure Perl requirements are bundled with the Action Streams plugin, it also
requires a compiled XML module. Also, because of how its syntax works, you must
directly C<use> the module in your own code, contrary to the Movable Type idiom
of using C<require> so that modules are loaded only when they are sure to be
used.
If you attempt load C<Web::Scraper> in the normal way, but C<Web::Scraper> is
unable to load due to its missing requirement, whenever the plugin attempts to
load your scraper, the entire plugin will fail to load.
Therefore the C<ActionStreams::Scraper> wrapper module is provided for you. If
you need to load C<Web::Scraper> so as to make a scraper to pass
C<ActionStreams::Event::fetch_scraper()> method, instead write in your module:
use ActionStreams::Scraper;
This module provides the C<Web::Scraper> interface, but if C<Web::Scraper> is
unable to load, the error will be thrown when your module tries to I<use> it,
rather than when you I<load> it. That is, if C<Web::Scraper> can't load, no
errors will be thrown to end users until they try to use your stream.
=head1 AUTHOR
Mark Paschal E<lt>[email protected]<gt>
=cut
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event/Website.pm b/plugins/ActionStreams/lib/ActionStreams/Event/Website.pm
index 78c4a9e..fd3fe6f 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event/Website.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event/Website.pm
@@ -1,80 +1,81 @@
package ActionStreams::Event::Website;
use strict;
use base qw( ActionStreams::Event );
use ActionStreams::Scraper;
__PACKAGE__->install_properties({
class_type => 'website_posted',
});
__PACKAGE__->install_meta({
columns => [ qw(
summary
source_title
source_url
icon_url
) ],
});
sub update_events {
my $class = shift;
my %profile = @_;
my ($ident, $author) = @profile{qw( ident author )};
my $links = $class->fetch_scraper(
- url => $ident,
- scraper => scraper {
+ unconditional => 1,
+ url => $ident,
+ scraper => scraper {
process 'head link[type="application/atom+xml"]', 'atom[]' => '@href';
process 'head link[type="application/rss+xml"]', 'rss[]' => '@href';
process 'head link[rel~="shortcut"]', 'icon[]' => '@href';
},
);
return if !$links;
my ($feed_url, $items);
if (($feed_url) = @{ $links->{atom} || [] }) {
$items = $class->fetch_xpath(
url => $feed_url,
foreach => '//entry',
get => {
identifier => 'id/child::text()',
title => 'title/child::text()',
summary => 'summary/child::text()',
url => q(link[@rel='alternate']/@href),
source_title => 'ancestor::feed/title/child::text()',
source_url => q(ancestor::feed/link[@rel='alternate']/@href),
created_on => 'published/child::text()',
modified_on => 'updated/child::text()',
},
);
}
elsif (($feed_url) = @{ $links->{rss} || [] }) {
$items = $class->fetch_xpath(
url => $feed_url,
foreach => '//item',
get => {
identifier => 'guid/child::text()',
title => 'title/child::text()',
summary => 'description/child::text()',
url => 'link/child::text()',
source_title => 'ancestor::channel/title/child::text()',
source_url => 'ancestor::channel/link/child::text()',
created_on => 'pubDate/child::text()',
modified_on => 'pubDate/child::text()',
},
);
}
return if !$items;
if (my ($icon_url) = @{ $links->{icon} || [] }) {
$icon_url = q{} . $icon_url;
$_->{icon_url} = $icon_url for @$items;
}
$class->build_results( author => $author, items => $items );
}
1;
|
markpasc/mt-plugin-action-streams
|
02687f6bd360ae1a60cc4ce66d417fd995b01bd9
|
Return control to Event::fetch_scraper() if we tried to use Web::Scraper on a resource that was Not Modified since we last got it BugzID: 91767
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm
index 9094697..d63a174 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm
@@ -1,760 +1,768 @@
package ActionStreams::Event;
use strict;
use base qw( MT::Object MT::Taggable MT::Scorable );
our @EXPORT_OK = qw( classes_for_type );
use HTTP::Date qw( str2time );
use MT::Util qw( encode_html );
use ActionStreams::Scraper;
our $hide_timeless = 0;
__PACKAGE__->install_properties({
column_defs => {
id => 'integer not null auto_increment',
identifier => 'string(200)',
author_id => 'integer not null',
visible => 'integer not null',
},
defaults => {
visible => 1,
},
indexes => {
identifier => 1,
author_id => 1,
created_on => 1,
created_by => 1,
},
class_type => 'event',
audit => 1,
meta => 1,
datasource => 'profileevent',
primary_key => 'id',
});
__PACKAGE__->install_meta({
columns => [ qw(
title
url
thumbnail
via
via_id
) ],
});
# Oracle does not like an identifier of more than 30 characters.
sub datasource {
my $class = shift;
my $r = MT->request;
my $ds = $r->cache('as_event_ds');
return $ds if $ds;
my $dss_oracle = qr/(db[id]::)?oracle/;
if ( my $type = MT->config('ObjectDriver') ) {
if ((lc $type) =~ m/^$dss_oracle$/) {
$ds = 'as';
}
}
$ds = $class->properties->{datasource}
unless $ds;
$r->cache('as_event_ds', $ds);
return $ds;
}
sub encode_field_for_html {
my $event = shift;
my ($field) = @_;
return encode_html( $event->$field() );
}
sub as_html {
my $event = shift;
my %params = @_;
my $stream = $event->registry_entry or return '';
# How many spaces are there in the form?
my $form = $params{form} || $stream->{html_form} || q{};
my @nums = $form =~ m{ \[ _ (\d+) \] }xmsg;
my $max = shift @nums;
for my $num (@nums) {
$max = $num if $max < $num;
}
# Do we need to supply the author name?
my @content = map { $event->encode_field_for_html($_) }
@{ $stream->{html_params} };
if ($max > scalar @content) {
my $name = defined $params{name} ? $params{name}
: $event->author->nickname
;
unshift @content, encode_html($name);
}
return MT->translate($form, @content);
}
sub update_events_loggily {
my $class = shift;
my %profile = @_;
# Keep this option out of band so we don't have to count on
# implementations of update_events() passing it through.
local $hide_timeless = delete $profile{hide_timeless} ? 1 : 0;
my $warn = $SIG{__WARN__} || sub { print STDERR $_[0] };
local $SIG{__WARN__} = sub {
my ($msg) = @_;
$msg =~ s{ \n \z }{}xms;
$msg = MT->component('ActionStreams')->translate(
'[_1] updating [_2] events for [_3]',
$msg, $profile{type}, $profile{author}->name,
);
$warn->("$msg\n");
};
eval {
$class->update_events(%profile);
};
if (my $err = $@) {
my $plugin = MT->component('ActionStreams');
my $err_msg = $plugin->translate("Error updating events for [_1]'s [_2] stream (type [_3] ident [_4]): [_5]",
$profile{author}->name, $class->properties->{class_type},
$profile{type}, $profile{ident}, $err);
MT->log($err_msg);
die $err; # re-throw so we can handle from job invocation
}
}
sub update_events {
my $class = shift;
my %profile = @_;
my $author = delete $profile{author};
my $stream = $class->registry_entry or return;
my $fetch = $stream->{fetch} || {};
local $profile{url} = $stream->{url};
die "Oops, no url?" if !$profile{url};
die "Oops, no ident?" if !$profile{ident};
$profile{url} =~ s/ {{ident}} / $profile{ident} /xmsge;
my $items;
if (my $xpath_params = $stream->{xpath}) {
$items = $class->fetch_xpath(
%$xpath_params,
%$fetch,
%profile,
);
}
elsif (my $atom_params = $stream->{atom}) {
my $get = {
created_on => 'published',
modified_on => 'updated',
title => 'title',
url => q{link[@rel='alternate']/@href},
via => q{link[@rel='alternate']/@href},
via_id => 'id',
identifier => 'id',
};
$atom_params = {} if !ref $atom_params;
@$get{keys %$atom_params} = values %$atom_params;
$items = $class->fetch_xpath(
foreach => '//entry',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $rss_params = $stream->{rss}) {
my $get = {
title => 'title',
url => 'link',
via => 'link',
created_on => 'pubDate',
thumbnail => 'media:thumbnail/@url',
via_id => 'guid',
identifier => 'guid',
};
$rss_params = {} if !ref $rss_params;
@$get{keys %$rss_params} = values %$rss_params;
$items = $class->fetch_xpath(
foreach => '//item',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $scraper_params = $stream->{scraper}) {
my ($foreach, $get) = @$scraper_params{qw( foreach get )};
my $scraper = scraper {
process $foreach, 'res[]' => scraper {
while (my ($field, $sel) = each %$get) {
process $sel->[0], $field => $sel->[1];
}
};
result 'res';
};
$items = $class->fetch_scraper(
scraper => $scraper,
%$fetch,
%profile,
);
}
return if !$items;
$class->build_results(
items => $items,
stream => $stream,
author => $author,
profile => \%profile,
);
}
sub registry_entry {
my $event = shift;
my ($type, $stream) = split /_/, $event->properties->{class_type}, 2;
my $reg = MT->instance->registry('action_streams') or return;
my $service = $reg->{$type} or return;
$service->{$stream};
}
sub author {
my $event = shift;
my $author_id = $event->author_id
or return;
return MT->instance->model('author')->lookup($author_id);
}
sub blog_id { 0 }
sub classes_for_type {
my $class = shift;
my ($type) = @_;
my $prevts = MT->instance->registry('action_streams');
my $prevt = $prevts->{$type};
return if !$prevt;
my @classes;
PACKAGE: while (my ($stream_id, $stream) = each %$prevt) {
next if 'HASH' ne ref $stream;
next if !$stream->{class} && !$stream->{url};
my $pkg;
if ($pkg = $stream->{class}) {
$pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms;
if (!eval { $pkg->properties }) {
if (!eval "require $pkg; 1") {
my $error = $@ || q{};
my $pl = MT->component('ActionStreams');
MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]',
$pkg, $type, $stream_id, $error));
next PACKAGE;
}
}
}
else {
$pkg = join q{::}, $class, 'Auto', ucfirst $type,
ucfirst $stream_id;
if (!eval { $pkg->properties }) {
eval "package $pkg; use base qw( $class ); 1" or next;
my $class_type = join q{_}, $type, $stream_id;
$pkg->install_properties({ class_type => $class_type });
$pkg->install_meta({ columns => $stream->{fields} })
if $stream->{fields};
}
}
push @classes, $pkg;
}
return @classes;
}
my $ua;
sub ua {
my $class = shift;
my %params = @_;
$ua ||= MT->new_ua({
paranoid => 1,
timeout => 10,
});
$ua->max_size(250_000) if $ua->can('max_size');
$ua->agent($params{default_useragent} ? $ua->_agent
: "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version);
return $ua if $class->class_type eq 'event';
require ActionStreams::UserAgent::Adapter;
my $adapter = ActionStreams::UserAgent::Adapter->new(
- ua => $ua,
- action_type => $class->class_type,
+ ua => $ua,
+ action_type => $class->class_type,
+ die_on_not_modified => $params{die_on_not_modified} || 0,
);
return $adapter;
}
sub set_values {
my $event = shift;
my ($values) = @_;
for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) {
my $meta_val = delete $values->{$meta_col};
$event->$meta_col($meta_val) if defined $meta_val;
}
$event->SUPER::set_values($values);
}
sub fetch_xpath {
my $class = shift;
my %params = @_;
my $url = $params{url} || '';
if (!$url) {
MT->log("No URL to fetch for $class results");
return;
}
my $ua = $class->ua(%params);
my $res = $ua->get($url);
if (!$res->is_success()) {
MT->log("Could not fetch ${url}: " . $res->status_line())
if $res->code != 304;
return;
}
# Strip leading whitespace, since the parser doesn't like it.
# TODO: confirm we got xml?
my $content = $res->content;
$content =~ s{ \A \s+ }{}xms;
require XML::XPath;
my $x = XML::XPath->new( xml => $content );
my @items;
ITEM: for my $item ($x->findnodes($params{foreach})) {
my %item_data;
VALUE: while (my ($key, $val) = each %{ $params{get} }) {
next VALUE if !$val;
if ($key eq 'tags') {
my @outvals = $item->findnodes($val)
or next VALUE;
$item_data{$key} = [ map { $_->getNodeValue } @outvals ];
}
else {
my $outval = $item->findvalue($val)
or next VALUE;
$outval = "$outval";
if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) {
# try both RFC 822/1123 and ISO 8601 formats
$outval = MT::Util::epoch2ts(undef, str2time($outval))
|| MT::Util::iso2ts(undef, $outval);
}
$item_data{$key} = $outval if $outval;
}
}
push @items, \%item_data;
}
return \@items;
}
sub build_results {
my $class = shift;
my %params = @_;
my ($author, $items, $profile, $stream) =
@params{qw( author items profile stream )};
my $mt = MT->app;
ITEM: for my $item (@$items) {
my $event;
my $identifier = delete $item->{identifier};
if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) {
$identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} };
}
if (defined $identifier) {
$identifier = "$identifier";
($event) = $class->search({
author_id => $author->id,
identifier => $identifier,
});
}
$event ||= $class->new;
$mt->run_callbacks('pre_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
my $tags = delete $item->{tags};
$event->set_values({
author_id => $author->id,
identifier => $identifier,
%$item,
});
$event->tags(@$tags) if $tags;
if ($hide_timeless && !$event->created_on) {
$event->visible(0);
}
$mt->run_callbacks('post_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
$event->save() or MT->log($event->errstr);
}
1;
}
sub save {
my $event = shift;
# Built-in audit field setting will set a local time, so do it ourselves.
if (!$event->created_on) {
my $ts = MT::Util::epoch2ts(undef, time);
$event->created_on($ts);
$event->modified_on($ts);
}
return $event->SUPER::save(@_);
}
sub fetch_scraper {
my $class = shift;
my %params = @_;
my ($url, $scraper) = @params{qw( url scraper )};
- $scraper->user_agent($class->ua(%params));
- my $items = $scraper->scrape(URI->new($url));
+ $scraper->user_agent( $class->ua( %params, die_on_not_modified => 1 ) );
+ my $uri_obj = URI->new($url);
+ my $items = eval { $scraper->scrape($uri_obj) };
+
+ # Ignore Web::Scraper errors due to 304 Not Modified responses.
+ if (!$items && $@ && !UNIVERSAL::isa($@, 'ActionStreams::UserAgent::NotModified')) {
+ die; # rethrow
+ }
+
# we're only being used for our scraper.
return if !$items;
return $items if !ref $items;
return $items if 'ARRAY' ne ref $items;
ITEM: for my $item (@$items) {
next ITEM if !ref $item || ref $item ne 'HASH';
for my $field (keys %$item) {
if ($field eq 'tags') {
$item->{$field} = [ map { "$_" } @{ $item->{$field} } ];
}
else {
$item->{$field} = q{} . $item->{$field};
}
}
}
return $items;
}
1;
__END__
=head1 NAME
ActionStreams::Event - an Action Streams stream definition
=head1 SYNOPSIS
# in plugin's config.yaml
profile_services:
example:
streamid:
name: Dice Example
description: A simple die rolling Perl stream example.
html_form: [_1] rolled a [_2]!
html_params:
- title
class: My::Stream
# in plugin's lib/My/Stream.pm
package My::Stream;
use base qw( ActionStreams::Event );
__PACKAGE__->install_properties({
class_type => 'example_streamid',
});
sub update_events {
my $class = shift;
my %profile = @_;
# trivial example: save a random number
my $die_roll = int rand 20;
my %item = (
title => $die_roll,
identifier => $die_roll,
);
return $class->build_results(
author => $profile{author},
items => [ \%item ],
);
}
1;
=head1 DESCRIPTION
I<ActionStreams::Event> provides the basic implementation of an action stream.
Stream definitions are engines for turning web resources into I<actions> (also
called I<events>). This base class produces actions based on generic stream
recipes defined in the MT registry, as well as providing the internal machinery
for you to implement your own streams in Perl code.
=head1 METHODS TO IMPLEMENT
These are the methods one commonly implements (overrides) when implementing a
stream subclass.
=head2 C<$class-E<gt>update_events(%profile)>
Fetches the web resource specified by the profile parameters, collects data
from it into actions, and saves the action records for use later. Required
members of C<%profile> are:
=over 4
=item * C<author>
The C<MT::Author> instance for whom events should be collected.
=item * C<ident>
The author's identifier on the given service.
=back
Other information about the stream, such as the URL pattern into which the
C<ident> parameter can be replaced, is available through the
C<$class-E<gt>registry_entry()> method.
=head2 C<$self-E<gt>as_html(%params)>
Returns the HTML version of the action, suitable for display to readers.
The default implementation uses the stream's registry definition to construct
the action: the author's name and the action's values as named in
C<html_params> are replaced into the stream's C<html_form> setting. You need
override it only if you have more complex requirements.
Optional members of C<%params> are:
=over 4
=item * C<form>
The formatting string to use. If not given, the C<html_form> specified for
this stream in the registry is used.
=item * C<name>
The text to use as the author's name if C<as_html> needs to provide it
automatically in the result. Author names are provided if there are more
tokens in C<html_form> than there are fields specified in C<html_params>.
If not given, the event's author's nickname is provided. Note that a defined
but empty name (such as C<q{}>) I<will> be used; in this case, the name will
appear to be omitted from the result of the C<as_html> call.
=back
=head1 AVAILABLE METHODS
These are the methods provided by I<ActionStreams::Event> to perform common
tasks. Call them from your overridden methods.
=head2 C<$self-E<gt>set_values(\%values)>
Stores the data given in C<%values> as members of this event.
=head2 C<$class-E<gt>fetch_xpath(%param)>
Returns the items discovered by scanning a web resource by the given XPath
recipe. Required members of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be a
valid XML document.
=item * C<foreach>
The XPath selector with which to select the individual events from the
resource.
=item * C<get>
A hashref containing the XPath selectors with which to collect individual data
for each item, keyed on the names of the fields to contain the data.
=back
C<%param> may also contain additional arguments for the C<ua()> method.
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
=head2 C<$class-E<gt>fetch_scraper(%param)>
Returns the items discovered by scanning by the given recipe. Required members
of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be an
HTML or XML document suitable for analysis by the C<Web::Scraper> module.
=item * C<scraper>
The C<Web::Scraper> scraper with which to extract item data from the specified
web resource. See L<Web::Scraper> for information on how to construct a
scraper.
=back
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
See also the below I<NOTE ON WEB::SCRAPER>.
=head2 C<$class-E<gt>build_results(%param)>
Converts a set of collected items into saved action records of type C<$class>.
The required members of C<%param> are:
=over 4
=item * C<author>
The C<MT::Author> instance whose action the items represent.
=item * C<items>
An arrayref of items to save as actions. Each item is a hashref containing the
action data, keyed on the names of the fields containing the data.
=back
Optional parameters are:
=over 4
=item * C<profile>
An arrayref describing the data for the author's profile for the associated
stream, such as is returned by the C<MT::Author::other_profile()> method
supplied by the Action Streams plugin.
The profile member is not used directly by C<build_results()>; they are only
passed to callbacks.
=item * C<stream>
A hashref containing the settings from the registry about the stream, such as
is returned from the C<registry_entry()> method.
=back
=head2 C<$class-E<gt>ua(%param)>
Returns the common HTTP user-agent, an instance of C<LWP::UserAgent>, with
which you can fetch web resources. No arguments are required; possible optional
parameters are:
=over 4
=item * C<default_useragent>
If set, the returned HTTP user-agent will use C<LWP::UserAgent>'s default
identifier in the HTTP C<User-Agent> header. If omitted, the UA will use the
Action Streams identifier of C<mt-actionstreams-lwp/I<version>>.
=back
=head2 C<$self-E<gt>author()>
Returns the C<MT::Author> instance associated with this event, if its
C<author_id> field has been set.
=head2 C<$class-E<gt>install_properties(\%properties)>
I<TODO>
=head2 C<$class-E<gt>install_meta(\%properties)>
I<TODO>
=head2 C<$class-E<gt>registry_entry()>
Returns the registry data for the stream represented by C<$class>.
=head2 C<$class-E<gt>classes_for_type($service_id)>
Given a profile service ID (that is, a key from the C<profile_services> section
of the registry), returns a list of stream classes for scanning that service's
streams.
=head1 NOTE ON WEB::SCRAPER
The C<Web::Scraper> module is powerful, but it has complex dependencies. While
its pure Perl requirements are bundled with the Action Streams plugin, it also
requires a compiled XML module. Also, because of how its syntax works, you must
directly C<use> the module in your own code, contrary to the Movable Type idiom
of using C<require> so that modules are loaded only when they are sure to be
used.
If you attempt load C<Web::Scraper> in the normal way, but C<Web::Scraper> is
unable to load due to its missing requirement, whenever the plugin attempts to
load your scraper, the entire plugin will fail to load.
Therefore the C<ActionStreams::Scraper> wrapper module is provided for you. If
you need to load C<Web::Scraper> so as to make a scraper to pass
C<ActionStreams::Event::fetch_scraper()> method, instead write in your module:
use ActionStreams::Scraper;
This module provides the C<Web::Scraper> interface, but if C<Web::Scraper> is
unable to load, the error will be thrown when your module tries to I<use> it,
rather than when you I<load> it. That is, if C<Web::Scraper> can't load, no
errors will be thrown to end users until they try to use your stream.
=head1 AUTHOR
Mark Paschal E<lt>[email protected]<gt>
=cut
diff --git a/plugins/ActionStreams/lib/ActionStreams/UserAgent/Adapter.pm b/plugins/ActionStreams/lib/ActionStreams/UserAgent/Adapter.pm
index 008a022..66876b0 100644
--- a/plugins/ActionStreams/lib/ActionStreams/UserAgent/Adapter.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/UserAgent/Adapter.pm
@@ -1,96 +1,116 @@
+package ActionStreams::UserAgent::NotModified;
+
+use overload q{""} => \&as_string;
+
+sub new {
+ my ($class, $string) = @_;
+ return bless \$string, $class;
+}
+
+sub as_string {
+ my $self = shift;
+ return $$self;
+}
+
+
package ActionStreams::UserAgent::Adapter;
sub new {
my $class = shift;
my %param = @_;
return bless \%param, $class;
}
sub _add_cache_headers {
my $self = shift;
my %param = @_;
my ($uri, $headers) = @param{qw( uri headers )};
my $action_type = $self->{action_type}
or return;
my $cache = MT->model('as_ua_cache')->load({
url => $uri,
action_type => $action_type,
});
return if !$cache;
if (my $etag = $cache->etag) {
$headers->{If_None_Match} = $etag;
}
if (my $last_mod = $cache->last_modified) {
$headers->{If_Last_Modified} = $last_mod;
}
}
sub _save_cache_headers {
my $self = shift;
my ($resp) = @_;
# Don't do anything if our existing cache headers were effective.
return if $resp->code == 304;
my $action_type = $self->{action_type}
or return;
my $uri = $resp->request->uri;
my $cache = MT->model('as_ua_cache')->load({
url => $uri,
action_type => $action_type,
});
my $failed = !$resp->is_success();
my $no_cache_headers = !$resp->header('Etag') && !$resp->header('Last-Modified');
if ($failed || $no_cache_headers) {
$cache->remove() if $cache;
return;
}
$cache ||= MT->model('as_ua_cache')->new();
$cache->set_values({
url => $uri,
action_type => $action_type,
etag => ($resp->header('Etag') || undef),
last_modified => ($resp->header('Last-Modified') || undef),
});
$cache->save();
}
sub get {
my $self = shift;
my ($uri, %headers) = @_;
$self->_add_cache_headers( uri => $uri, headers => \%headers );
my $resp = $self->{ua}->get($uri, %headers);
+ if ($self->{die_on_not_modified} && $resp->code == 304) {
+ die ActionStreams::UserAgent::NotModified->new(
+ join q{ }, "GET", $uri, "failed:", $resp->status_line,
+ );
+ }
$self->_save_cache_headers($resp);
return $resp;
}
our $AUTOLOAD;
sub AUTOLOAD {
my $funcname = $AUTOLOAD;
$funcname =~ s{ \A .* :: }{}xms;
return if $funcname eq 'DESTROY';
my $fn = sub {
my $self = shift;
return shift->{ua}->$funcname(@_) if ref $self;
if (eval { require LWPx::ParanoidAgent; 1 }) {
return LWPx::ParanoidAgent->$funcname(@_);
}
return LWP::UserAgent->$funcname(@_);
};
{
no strict 'refs';
*{$AUTOLOAD} = $fn;
}
goto &$AUTOLOAD;
}
1;
|
markpasc/mt-plugin-action-streams
|
934cae55dd81b44ed7f5696ad8d95959902e2bb2
|
Stop throwing out caching headers just because they worked BugzID: 91767
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/UserAgent/Adapter.pm b/plugins/ActionStreams/lib/ActionStreams/UserAgent/Adapter.pm
index ef603aa..008a022 100644
--- a/plugins/ActionStreams/lib/ActionStreams/UserAgent/Adapter.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/UserAgent/Adapter.pm
@@ -1,93 +1,96 @@
package ActionStreams::UserAgent::Adapter;
sub new {
my $class = shift;
my %param = @_;
return bless \%param, $class;
}
sub _add_cache_headers {
my $self = shift;
my %param = @_;
my ($uri, $headers) = @param{qw( uri headers )};
my $action_type = $self->{action_type}
or return;
my $cache = MT->model('as_ua_cache')->load({
url => $uri,
action_type => $action_type,
});
return if !$cache;
if (my $etag = $cache->etag) {
$headers->{If_None_Match} = $etag;
}
if (my $last_mod = $cache->last_modified) {
$headers->{If_Last_Modified} = $last_mod;
}
}
sub _save_cache_headers {
my $self = shift;
my ($resp) = @_;
+ # Don't do anything if our existing cache headers were effective.
+ return if $resp->code == 304;
+
my $action_type = $self->{action_type}
or return;
my $uri = $resp->request->uri;
my $cache = MT->model('as_ua_cache')->load({
url => $uri,
action_type => $action_type,
});
my $failed = !$resp->is_success();
my $no_cache_headers = !$resp->header('Etag') && !$resp->header('Last-Modified');
if ($failed || $no_cache_headers) {
$cache->remove() if $cache;
return;
}
$cache ||= MT->model('as_ua_cache')->new();
$cache->set_values({
url => $uri,
action_type => $action_type,
etag => ($resp->header('Etag') || undef),
last_modified => ($resp->header('Last-Modified') || undef),
});
$cache->save();
}
sub get {
my $self = shift;
my ($uri, %headers) = @_;
$self->_add_cache_headers( uri => $uri, headers => \%headers );
my $resp = $self->{ua}->get($uri, %headers);
$self->_save_cache_headers($resp);
return $resp;
}
our $AUTOLOAD;
sub AUTOLOAD {
my $funcname = $AUTOLOAD;
$funcname =~ s{ \A .* :: }{}xms;
return if $funcname eq 'DESTROY';
my $fn = sub {
my $self = shift;
return shift->{ua}->$funcname(@_) if ref $self;
if (eval { require LWPx::ParanoidAgent; 1 }) {
return LWPx::ParanoidAgent->$funcname(@_);
}
return LWP::UserAgent->$funcname(@_);
};
{
no strict 'refs';
*{$AUTOLOAD} = $fn;
}
goto &$AUTOLOAD;
}
1;
|
markpasc/mt-plugin-action-streams
|
5d40db1023c5ea00772d39d59f5820fd3766d109
|
this spacing too
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Scraper.pm b/plugins/ActionStreams/lib/ActionStreams/Scraper.pm
index 44e642c..56e4a73 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Scraper.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Scraper.pm
@@ -1,37 +1,37 @@
package ActionStreams::Scraper;
my $import_error = 'Cannot update stream without Web::Scraper; a prerequisite may not be installed';
sub import {
my %methods;
if (eval { require Web::Scraper; 1 }) {
Web::Scraper->import();
%methods = (
scraper => \&scraper,
result => sub { goto &result },
process => sub { goto &process },
process_first => sub { goto &process_first },
);
}
elsif (my $err = $@) {
$import_error .= ': ' . $err;
%methods = (
scraper => sub (&) { die $import_error },
result => sub { die $import_error },
process => sub { die $import_error },
- process_first => sub { die $import_error },
+ process_first => sub { die $import_error },
);
}
# Export these methods like Web::Scraper does.
my $pkg = caller;
no strict 'refs';
while (my ($key, $val) = each %methods) {
*{"${pkg}::${key}"} = $val;
}
return 1;
}
1;
|
markpasc/mt-plugin-action-streams
|
ab7cdabd286fa4b70e47834b77c31262f3c090df
|
spacing
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Scraper.pm b/plugins/ActionStreams/lib/ActionStreams/Scraper.pm
index b14fbca..44e642c 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Scraper.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Scraper.pm
@@ -1,37 +1,37 @@
package ActionStreams::Scraper;
my $import_error = 'Cannot update stream without Web::Scraper; a prerequisite may not be installed';
sub import {
my %methods;
-
+
if (eval { require Web::Scraper; 1 }) {
Web::Scraper->import();
%methods = (
scraper => \&scraper,
result => sub { goto &result },
process => sub { goto &process },
process_first => sub { goto &process_first },
);
}
elsif (my $err = $@) {
$import_error .= ': ' . $err;
%methods = (
scraper => sub (&) { die $import_error },
result => sub { die $import_error },
process => sub { die $import_error },
process_first => sub { die $import_error },
);
}
-
+
# Export these methods like Web::Scraper does.
my $pkg = caller;
no strict 'refs';
while (my ($key, $val) = each %methods) {
*{"${pkg}::${key}"} = $val;
}
return 1;
}
1;
|
markpasc/mt-plugin-action-streams
|
18e6fdcace79b06ce36a982652d7044228d215d4
|
This update_events_safely method isn't actually particularly safe BugzID: 91767
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm
index 9bae2b3..9094697 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm
@@ -1,610 +1,610 @@
package ActionStreams::Event;
use strict;
use base qw( MT::Object MT::Taggable MT::Scorable );
our @EXPORT_OK = qw( classes_for_type );
use HTTP::Date qw( str2time );
use MT::Util qw( encode_html );
use ActionStreams::Scraper;
our $hide_timeless = 0;
__PACKAGE__->install_properties({
column_defs => {
id => 'integer not null auto_increment',
identifier => 'string(200)',
author_id => 'integer not null',
visible => 'integer not null',
},
defaults => {
visible => 1,
},
indexes => {
identifier => 1,
author_id => 1,
created_on => 1,
created_by => 1,
},
class_type => 'event',
audit => 1,
meta => 1,
datasource => 'profileevent',
primary_key => 'id',
});
__PACKAGE__->install_meta({
columns => [ qw(
title
url
thumbnail
via
via_id
) ],
});
# Oracle does not like an identifier of more than 30 characters.
sub datasource {
my $class = shift;
my $r = MT->request;
my $ds = $r->cache('as_event_ds');
return $ds if $ds;
my $dss_oracle = qr/(db[id]::)?oracle/;
if ( my $type = MT->config('ObjectDriver') ) {
if ((lc $type) =~ m/^$dss_oracle$/) {
$ds = 'as';
}
}
$ds = $class->properties->{datasource}
unless $ds;
$r->cache('as_event_ds', $ds);
return $ds;
}
sub encode_field_for_html {
my $event = shift;
my ($field) = @_;
return encode_html( $event->$field() );
}
sub as_html {
my $event = shift;
my %params = @_;
my $stream = $event->registry_entry or return '';
# How many spaces are there in the form?
my $form = $params{form} || $stream->{html_form} || q{};
my @nums = $form =~ m{ \[ _ (\d+) \] }xmsg;
my $max = shift @nums;
for my $num (@nums) {
$max = $num if $max < $num;
}
# Do we need to supply the author name?
my @content = map { $event->encode_field_for_html($_) }
@{ $stream->{html_params} };
if ($max > scalar @content) {
my $name = defined $params{name} ? $params{name}
: $event->author->nickname
;
unshift @content, encode_html($name);
}
return MT->translate($form, @content);
}
-sub update_events_safely {
+sub update_events_loggily {
my $class = shift;
my %profile = @_;
# Keep this option out of band so we don't have to count on
# implementations of update_events() passing it through.
local $hide_timeless = delete $profile{hide_timeless} ? 1 : 0;
my $warn = $SIG{__WARN__} || sub { print STDERR $_[0] };
local $SIG{__WARN__} = sub {
my ($msg) = @_;
$msg =~ s{ \n \z }{}xms;
$msg = MT->component('ActionStreams')->translate(
'[_1] updating [_2] events for [_3]',
$msg, $profile{type}, $profile{author}->name,
);
$warn->("$msg\n");
};
eval {
$class->update_events(%profile);
};
if (my $err = $@) {
my $plugin = MT->component('ActionStreams');
my $err_msg = $plugin->translate("Error updating events for [_1]'s [_2] stream (type [_3] ident [_4]): [_5]",
$profile{author}->name, $class->properties->{class_type},
$profile{type}, $profile{ident}, $err);
MT->log($err_msg);
die $err; # re-throw so we can handle from job invocation
}
}
sub update_events {
my $class = shift;
my %profile = @_;
my $author = delete $profile{author};
my $stream = $class->registry_entry or return;
my $fetch = $stream->{fetch} || {};
local $profile{url} = $stream->{url};
die "Oops, no url?" if !$profile{url};
die "Oops, no ident?" if !$profile{ident};
$profile{url} =~ s/ {{ident}} / $profile{ident} /xmsge;
my $items;
if (my $xpath_params = $stream->{xpath}) {
$items = $class->fetch_xpath(
%$xpath_params,
%$fetch,
%profile,
);
}
elsif (my $atom_params = $stream->{atom}) {
my $get = {
created_on => 'published',
modified_on => 'updated',
title => 'title',
url => q{link[@rel='alternate']/@href},
via => q{link[@rel='alternate']/@href},
via_id => 'id',
identifier => 'id',
};
$atom_params = {} if !ref $atom_params;
@$get{keys %$atom_params} = values %$atom_params;
$items = $class->fetch_xpath(
foreach => '//entry',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $rss_params = $stream->{rss}) {
my $get = {
title => 'title',
url => 'link',
via => 'link',
created_on => 'pubDate',
thumbnail => 'media:thumbnail/@url',
via_id => 'guid',
identifier => 'guid',
};
$rss_params = {} if !ref $rss_params;
@$get{keys %$rss_params} = values %$rss_params;
$items = $class->fetch_xpath(
foreach => '//item',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $scraper_params = $stream->{scraper}) {
my ($foreach, $get) = @$scraper_params{qw( foreach get )};
my $scraper = scraper {
process $foreach, 'res[]' => scraper {
while (my ($field, $sel) = each %$get) {
process $sel->[0], $field => $sel->[1];
}
};
result 'res';
};
$items = $class->fetch_scraper(
scraper => $scraper,
%$fetch,
%profile,
);
}
return if !$items;
$class->build_results(
items => $items,
stream => $stream,
author => $author,
profile => \%profile,
);
}
sub registry_entry {
my $event = shift;
my ($type, $stream) = split /_/, $event->properties->{class_type}, 2;
my $reg = MT->instance->registry('action_streams') or return;
my $service = $reg->{$type} or return;
$service->{$stream};
}
sub author {
my $event = shift;
my $author_id = $event->author_id
or return;
return MT->instance->model('author')->lookup($author_id);
}
sub blog_id { 0 }
sub classes_for_type {
my $class = shift;
my ($type) = @_;
my $prevts = MT->instance->registry('action_streams');
my $prevt = $prevts->{$type};
return if !$prevt;
my @classes;
PACKAGE: while (my ($stream_id, $stream) = each %$prevt) {
next if 'HASH' ne ref $stream;
next if !$stream->{class} && !$stream->{url};
my $pkg;
if ($pkg = $stream->{class}) {
$pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms;
if (!eval { $pkg->properties }) {
if (!eval "require $pkg; 1") {
my $error = $@ || q{};
my $pl = MT->component('ActionStreams');
MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]',
$pkg, $type, $stream_id, $error));
next PACKAGE;
}
}
}
else {
$pkg = join q{::}, $class, 'Auto', ucfirst $type,
ucfirst $stream_id;
if (!eval { $pkg->properties }) {
eval "package $pkg; use base qw( $class ); 1" or next;
my $class_type = join q{_}, $type, $stream_id;
$pkg->install_properties({ class_type => $class_type });
$pkg->install_meta({ columns => $stream->{fields} })
if $stream->{fields};
}
}
push @classes, $pkg;
}
return @classes;
}
my $ua;
sub ua {
my $class = shift;
my %params = @_;
$ua ||= MT->new_ua({
paranoid => 1,
timeout => 10,
});
$ua->max_size(250_000) if $ua->can('max_size');
$ua->agent($params{default_useragent} ? $ua->_agent
: "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version);
return $ua if $class->class_type eq 'event';
require ActionStreams::UserAgent::Adapter;
my $adapter = ActionStreams::UserAgent::Adapter->new(
ua => $ua,
action_type => $class->class_type,
);
return $adapter;
}
sub set_values {
my $event = shift;
my ($values) = @_;
for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) {
my $meta_val = delete $values->{$meta_col};
$event->$meta_col($meta_val) if defined $meta_val;
}
$event->SUPER::set_values($values);
}
sub fetch_xpath {
my $class = shift;
my %params = @_;
my $url = $params{url} || '';
if (!$url) {
MT->log("No URL to fetch for $class results");
return;
}
my $ua = $class->ua(%params);
my $res = $ua->get($url);
if (!$res->is_success()) {
MT->log("Could not fetch ${url}: " . $res->status_line())
if $res->code != 304;
return;
}
# Strip leading whitespace, since the parser doesn't like it.
# TODO: confirm we got xml?
my $content = $res->content;
$content =~ s{ \A \s+ }{}xms;
require XML::XPath;
my $x = XML::XPath->new( xml => $content );
my @items;
ITEM: for my $item ($x->findnodes($params{foreach})) {
my %item_data;
VALUE: while (my ($key, $val) = each %{ $params{get} }) {
next VALUE if !$val;
if ($key eq 'tags') {
my @outvals = $item->findnodes($val)
or next VALUE;
$item_data{$key} = [ map { $_->getNodeValue } @outvals ];
}
else {
my $outval = $item->findvalue($val)
or next VALUE;
$outval = "$outval";
if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) {
# try both RFC 822/1123 and ISO 8601 formats
$outval = MT::Util::epoch2ts(undef, str2time($outval))
|| MT::Util::iso2ts(undef, $outval);
}
$item_data{$key} = $outval if $outval;
}
}
push @items, \%item_data;
}
return \@items;
}
sub build_results {
my $class = shift;
my %params = @_;
my ($author, $items, $profile, $stream) =
@params{qw( author items profile stream )};
my $mt = MT->app;
ITEM: for my $item (@$items) {
my $event;
my $identifier = delete $item->{identifier};
if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) {
$identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} };
}
if (defined $identifier) {
$identifier = "$identifier";
($event) = $class->search({
author_id => $author->id,
identifier => $identifier,
});
}
$event ||= $class->new;
$mt->run_callbacks('pre_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
my $tags = delete $item->{tags};
$event->set_values({
author_id => $author->id,
identifier => $identifier,
%$item,
});
$event->tags(@$tags) if $tags;
if ($hide_timeless && !$event->created_on) {
$event->visible(0);
}
$mt->run_callbacks('post_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
$event->save() or MT->log($event->errstr);
}
1;
}
sub save {
my $event = shift;
# Built-in audit field setting will set a local time, so do it ourselves.
if (!$event->created_on) {
my $ts = MT::Util::epoch2ts(undef, time);
$event->created_on($ts);
$event->modified_on($ts);
}
return $event->SUPER::save(@_);
}
sub fetch_scraper {
my $class = shift;
my %params = @_;
my ($url, $scraper) = @params{qw( url scraper )};
$scraper->user_agent($class->ua(%params));
my $items = $scraper->scrape(URI->new($url));
# we're only being used for our scraper.
return if !$items;
return $items if !ref $items;
return $items if 'ARRAY' ne ref $items;
ITEM: for my $item (@$items) {
next ITEM if !ref $item || ref $item ne 'HASH';
for my $field (keys %$item) {
if ($field eq 'tags') {
$item->{$field} = [ map { "$_" } @{ $item->{$field} } ];
}
else {
$item->{$field} = q{} . $item->{$field};
}
}
}
return $items;
}
1;
__END__
=head1 NAME
ActionStreams::Event - an Action Streams stream definition
=head1 SYNOPSIS
# in plugin's config.yaml
profile_services:
example:
streamid:
name: Dice Example
description: A simple die rolling Perl stream example.
html_form: [_1] rolled a [_2]!
html_params:
- title
class: My::Stream
# in plugin's lib/My/Stream.pm
package My::Stream;
use base qw( ActionStreams::Event );
__PACKAGE__->install_properties({
class_type => 'example_streamid',
});
sub update_events {
my $class = shift;
my %profile = @_;
# trivial example: save a random number
my $die_roll = int rand 20;
my %item = (
title => $die_roll,
identifier => $die_roll,
);
return $class->build_results(
author => $profile{author},
items => [ \%item ],
);
}
1;
=head1 DESCRIPTION
I<ActionStreams::Event> provides the basic implementation of an action stream.
Stream definitions are engines for turning web resources into I<actions> (also
called I<events>). This base class produces actions based on generic stream
recipes defined in the MT registry, as well as providing the internal machinery
for you to implement your own streams in Perl code.
=head1 METHODS TO IMPLEMENT
These are the methods one commonly implements (overrides) when implementing a
stream subclass.
=head2 C<$class-E<gt>update_events(%profile)>
Fetches the web resource specified by the profile parameters, collects data
from it into actions, and saves the action records for use later. Required
members of C<%profile> are:
=over 4
=item * C<author>
The C<MT::Author> instance for whom events should be collected.
=item * C<ident>
The author's identifier on the given service.
=back
Other information about the stream, such as the URL pattern into which the
C<ident> parameter can be replaced, is available through the
C<$class-E<gt>registry_entry()> method.
=head2 C<$self-E<gt>as_html(%params)>
Returns the HTML version of the action, suitable for display to readers.
The default implementation uses the stream's registry definition to construct
the action: the author's name and the action's values as named in
C<html_params> are replaced into the stream's C<html_form> setting. You need
override it only if you have more complex requirements.
Optional members of C<%params> are:
=over 4
=item * C<form>
The formatting string to use. If not given, the C<html_form> specified for
this stream in the registry is used.
=item * C<name>
The text to use as the author's name if C<as_html> needs to provide it
automatically in the result. Author names are provided if there are more
tokens in C<html_form> than there are fields specified in C<html_params>.
If not given, the event's author's nickname is provided. Note that a defined
but empty name (such as C<q{}>) I<will> be used; in this case, the name will
appear to be omitted from the result of the C<as_html> call.
=back
=head1 AVAILABLE METHODS
These are the methods provided by I<ActionStreams::Event> to perform common
tasks. Call them from your overridden methods.
=head2 C<$self-E<gt>set_values(\%values)>
Stores the data given in C<%values> as members of this event.
=head2 C<$class-E<gt>fetch_xpath(%param)>
Returns the items discovered by scanning a web resource by the given XPath
recipe. Required members of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be a
valid XML document.
=item * C<foreach>
diff --git a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
index cce5fd8..9f43e7f 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
@@ -193,534 +193,534 @@ sub itemset_hide_events {
$event->visible(0);
$event->save;
}
$app->add_return_arg( hidden => 1 );
$app->call_return;
}
sub itemset_show_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(1);
$event->save;
}
$app->add_return_arg( shown => 1 );
$app->call_return;
}
sub _itemset_hide_show_all_events {
my ($app, $new_visible) = @_;
$app->validate_magic or return;
my $event_class = MT->model('profileevent');
# Really we should work directly from the selected author ID, but as an
# itemset event we only got some event IDs. So use its.
my ($event_id) = $app->param('id');
my $event = $event_class->load($event_id)
or return $app->error($app->translate('No such event [_1]', $event_id));
my $author_id = $event->author_id;
return $app->error('Not permitted to modify')
if ! $app->user
or ! $app->user->is_superuser() && $author_id != $app->user->id;
my $driver = $event_class->driver;
my $stmt = $driver->prepare_statement($event_class, {
# TODO: include filter value when we have filters
author_id => $author_id,
visible => $new_visible ? 0 : 1,
});
my $sql = "UPDATE " . $driver->table_for($event_class) . " SET "
. $driver->dbd->db_column_name($event_class->datasource, 'visible')
. " = ? " . $stmt->as_sql_where;
# Work around error in MT::ObjectDriver::Driver::DBI::sql by doing it inline.
my $dbh = $driver->rw_handle;
$dbh->do($sql, {}, $new_visible, @{ $stmt->{bind} })
or return $app->error($dbh->errstr);
return 1;
}
sub itemset_hide_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 0) or return;
$app->add_return_arg( all_hidden => 1 );
$app->call_return;
}
sub itemset_show_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 1) or return;
$app->add_return_arg( all_shown => 1 );
$app->call_return;
}
sub _build_service_data {
my %info = @_;
my ($networks, $streams, $author) = @info{qw( networks streams author )};
my (@service_styles_loop, @networks);
my %has_profiles;
if ($author) {
my $other_profiles = $author->other_profiles();
$has_profiles{$_->{type}} = 1 for @$other_profiles;
}
my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
keys %$networks;
TYPE: for my $type (@network_keys) {
my $ndata = $networks->{$type}
or next TYPE;
my @streams;
if ($streams) {
my $streamdata = $streams->{$type} || {};
@streams =
sort { lc $a->{name} cmp lc $b->{name} }
grep { grep { $_ } @$_{qw( class scraper xpath rss atom )} }
map { +{ stream => $_, %{ $streamdata->{$_} } } }
grep { $_ ne 'plugin' }
keys %$streamdata;
}
my $ret = {
type => $type,
%$ndata,
label => $ndata->{name},
user_has_account => ($has_profiles{$type} ? 1 : 0),
};
$ret->{streams} = \@streams if @streams;
push @networks, $ret;
if (!$ndata->{plugin} || $ndata->{plugin}->id ne 'actionstreams') {
push @service_styles_loop, {
service_type => $type,
service_icon => __PACKAGE__->icon_url_for_service($type, $ndata),
};
}
}
return (
service_styles => \@service_styles_loop,
networks => \@networks,
);
}
sub other_profiles {
my( $app ) = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
my $author = _edit_author($app) or return;
my %params;
$params{id} = $params{edit_author_id} = $author->id;
$params{name} = $params{edit_author_name} = $author->name;
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl( 'other_profiles.tmpl' );
my @profiles = sort { lc $a->{label} cmp lc $b->{label} }
@{ $author->other_profiles || [] };
my %messages = map { $_ => $app->param($_) ? 1 : 0 }
(qw( added removed updated edited ));
return $app->build_page( $tmpl, {
%params,
profiles => \@profiles,
listing_screen => 1,
_build_service_data(
networks => $app->registry('profile_services'),
),
%messages,
} );
}
sub dialog_add_edit_profile {
my ($app) = @_;
return $app->error('Not permitted to view')
if $app->user->id != $app->param('author_id') && !$app->user->is_superuser();
my $author = MT->model('author')->load($app->param('author_id'))
or return $app->error('No such author [_1]', $app->param('author_id'));
my %edit_profile;
my $tmpl_name = 'dialog_add_profile.tmpl';
if (my $edit_type = $app->param('profile_type')) {
my $ident = $app->param('profile_ident') || q{};
my ($profile) = grep { $_->{ident} eq $ident }
@{ $author->other_profiles($edit_type) };
%edit_profile = (
edit_type => $edit_type,
edit_type_name => $app->registry('profile_services', $edit_type, 'name'),
edit_ident => $ident,
edit_streams => $profile->{streams} || [],
);
$tmpl_name = 'dialog_edit_profile.tmpl';
}
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl($tmpl_name);
return $app->build_page($tmpl, {
edit_author_id => $app->param('author_id'),
_build_service_data(
networks => $app->registry('profile_services'),
streams => $app->registry('action_streams'),
author => $author,
),
%edit_profile,
});
}
sub edit_other_profile {
my $app = shift;
$app->validate_magic() or return;
my $author_id = $app->param('author_id')
or return $app->error('Author id is required');
my $user = MT->model('author')->load($author_id)
or return $app->error('Author id is invalid');
return $app->error('Not permitted to edit')
if $app->user->id != $author_id && !$app->user->is_superuser();
my $type = $app->param('profile_type');
my $orig_ident = $app->param('original_ident');
$user->remove_profile($type, $orig_ident);
$app->forward('add_other_profile', success_msg => 'edited');
}
sub add_other_profile {
my $app = shift;
my %param = @_;
$app->validate_magic or return;
my $author_id = $app->param('author_id')
or return $app->error('Author id is required');
my $user = MT->model('author')->load($author_id)
or return $app->error('Author id is invalid');
return $app->error('Not permitted to add')
if $app->user->id != $author_id && !$app->user->is_superuser();
my( $ident, $uri, $label, $type );
if ( $type = $app->param( 'profile_type' ) ) {
my $reg = $app->registry('profile_services');
my $network = $reg->{$type}
or croak "Unknown network $type";
$label = $network->{name} . ' Profile';
$ident = $app->param( 'profile_id' );
$ident =~ s{ \A \s* }{}xms;
$ident =~ s{ \s* \z }{}xms;
# Check for full URLs.
if (!$network->{ident_exact}) {
my $url_pattern = $network->{url};
my ($pre_ident, $post_ident) = split /(?:\%s|\Q{{ident}}\E)/, $url_pattern, 2;
$pre_ident =~ s{ \A http:// }{}xms;
$post_ident =~ s{ / \z }{}xms;
if ($ident =~ m{ \A (?:http://)? \Q$pre_ident\E (.*?) \Q$post_ident\E /? \z }xms) {
$ident = $1;
}
}
$uri = $network->{url};
$uri =~ s{ (?:\%s|\Q{{ident}}\E) }{$ident}xmsg;
} else {
$ident = $uri = $app->param( 'profile_uri' );
$label = $app->param( 'profile_label' );
$type = 'website';
}
my $profile = {
type => $type,
ident => $ident,
label => $label,
uri => $uri,
};
my %streams = map { join(q{_}, $type, $_) => 1 }
grep { $_ ne 'plugin' && $app->param(join q{_}, 'stream', $type, $_) }
keys %{ $app->registry('action_streams', $type) || {} };
$profile->{streams} = \%streams if %streams;
$app->run_callbacks('pre_add_profile.' . $type, $app, $user, $profile);
$user->add_profile($profile);
$app->run_callbacks('post_add_profile.' . $type, $app, $user, $profile);
my $success_msg = $param{success_msg} || 'added';
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => $author_id, $success_msg => 1 },
));
}
sub remove_other_profile {
my( $app ) = @_;
$app->validate_magic or return;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
or next PROFILE;
next PROFILE
if $app->user->id != $author_id && !$app->user->is_superuser();
$app->run_callbacks('pre_remove_profile.' . $type, $app, $user, $type, $ident);
$user->remove_profile( $type, $ident );
$app->run_callbacks('post_remove_profile.' . $type, $app, $user, $type, $ident);
$page_author_id = $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), removed => 1 },
));
}
sub profile_add_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
$app->param('author_id', $user->id);
my $type = $app->param('profile_type')
or return $app->error( $app->translate("Invalid request.") );
# The profile side interface doesn't have stream selection, so select
# them all by default.
# TODO: factor out the adding logic (and parameterize stream selection) to stop faking params
foreach my $stream ( keys %{ $app->registry('action_streams', $type) || {} } ) {
next if $stream eq 'plugin';
$app->param(join('_', 'stream', $type, $stream), 1);
}
add_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub profile_first_update_events {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub profile_delete_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
# TODO: factor out this logic instead of having to fake params
my $id = scalar $app->param('id');
$id = $user->id . ':' . $id;
$app->param('id', $id);
remove_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub itemset_update_profiles {
my $app = shift;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
or next PROFILE;
next PROFILE
if $app->user->id != $author_id && !$app->user->is_superuser();
my $profiles = $user->other_profiles($type);
if (!$profiles) {
next PROFILE;
}
my @profiles = grep { $_->{ident} eq $ident } @$profiles;
for my $author_profile (@profiles) {
update_events_for_profile($user, $author_profile,
synchronous => 1);
}
$page_author_id ||= $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), updated => 1 },
));
}
sub first_profile_update {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub rebuild_action_stream_blogs {
my ($cb, $app) = @_;
my $plugin = MT->component('ActionStreams');
my $pd_iter = MT->model('plugindata')->load_iter({
plugin => $plugin->key,
key => { like => 'configuration:blog:%' }
});
my %rebuild;
while ( my $pd = $pd_iter->() ) {
next unless $pd->data('rebuild_for_action_stream_events');
my ($blog_id) = $pd->key =~ m/:blog:(\d+)$/;
$rebuild{$blog_id} = 1;
}
for my $blog_id (keys %rebuild) {
# TODO: limit this to indexes that publish action stream data, once
# we can magically infer template content before building it
my $blog = MT->model('blog')->load( $blog_id ) or next;
# Republish all the blog's known non-virtual index fileinfos that
# have real template objects.
my $finfo_class = MT->model('fileinfo');
my $finfo_template_col = $finfo_class->driver->dbd->db_column_name(
$finfo_class->datasource, 'template_id');
my @fileinfos = $finfo_class->load({
blog_id => $blog->id,
archive_type => 'index',
virtual => [ \'IS NULL', 0 ],
}, {
join => MT->model('template')->join_on(undef,
{ id => \"= $finfo_template_col" }),
});
require MT::TheSchwartz;
require TheSchwartz::Job;
for my $fi (@fileinfos) {
my $job = TheSchwartz::Job->new();
$job->funcname('MT::Worker::Publish');
$job->uniqkey($fi->id);
$job->run_after(time + 240); # 4 minutes
MT::TheSchwartz->insert($job);
}
}
}
sub widget_recent {
my ($app, $tmpl, $widget_param) = @_;
$tmpl->param('author_id', $app->user->id);
$tmpl->param('blog_id', $app->blog->id) if $app->blog;
}
sub widget_blog_dashboard_only {
my ($page, $scope) = @_;
return if $scope eq 'dashboard:system';
return 1;
}
sub update_events {
my $mt = MT->app;
$mt->run_callbacks('pre_action_streams_task', $mt);
my $au_class = MT->model('author');
my $author_iter = $au_class->search({
status => $au_class->ACTIVE(),
}, {
join => [ $au_class->meta_pkg, 'author_id', { type => 'other_profiles' } ],
});
while (my $author = $author_iter->()) {
my $profiles = $author->other_profiles();
$mt->run_callbacks('pre_update_action_streams', $mt, $author, $profiles);
PROFILE: for my $profile (@$profiles) {
update_events_for_profile($author, $profile);
}
$mt->run_callbacks('post_update_action_streams', $mt, $author, $profiles);
}
$mt->run_callbacks('post_action_streams_task', $mt);
}
sub update_events_for_profile {
my ($author, $profile, %param) = @_;
my $type = $profile->{type};
my $streams = $profile->{streams};
return if !$streams || !%$streams;
require ActionStreams::Event;
my @event_classes = ActionStreams::Event->classes_for_type($type)
or return;
my $mt = MT->app;
$mt->run_callbacks('pre_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
EVENTCLASS: for my $event_class (@event_classes) {
next EVENTCLASS if !$streams->{$event_class->class_type};
if ($param{synchronous}) {
- $event_class->update_events_safely(
+ $event_class->update_events_loggily(
author => $author,
hide_timeless => $param{hide_timeless} ? 1 : 0,
%$profile,
);
}
else {
# Defer regular updates to job workers.
require ActionStreams::Worker;
ActionStreams::Worker->make_work(
event_class => $event_class,
author => $author,
%$profile,
);
}
}
$mt->run_callbacks('post_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
}
1;
diff --git a/plugins/ActionStreams/lib/ActionStreams/Worker.pm b/plugins/ActionStreams/lib/ActionStreams/Worker.pm
index 24c7db2..9a3e4f5 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Worker.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Worker.pm
@@ -1,52 +1,52 @@
package ActionStreams::Worker;
use strict;
use warnings;
use base qw( TheSchwartz::Worker );
sub make_work {
my $class = shift;
my %profile = @_;
require MT::TheSchwartz;
require TheSchwartz::Job;
my $job = TheSchwartz::Job->new;
$job->funcname(__PACKAGE__);
my $event_class = $profile{event_class};
my $author = delete $profile{author};
$profile{author_id} = $author->id;
$job->uniqkey(join q{:}, $author->id, $profile{ident}, $event_class);
$job->arg([ %profile ]);
MT::TheSchwartz->insert($job);
return $job;
}
sub work {
my $self = shift;
my ($job) = @_;
my %profile = @{ $job->arg };
my ($author_id, $event_class)
= delete @profile{qw( author_id event_class )};
$profile{author} = MT->model('author')->load($author_id);
if (!$profile{author}) {
my $plugin = MT->component('ActionStreams');
my $msg = $plugin->translate('No such author with ID [_1]',
$author_id);
return $job->permanent_failure($msg);
}
# If the class doesn't exist or isn't an ActionStreams::Event... well,
# we did all the updating we could, right?
- eval { $event_class->properties && $event_class->can('update_events_safely') }
+ eval { $event_class->properties && $event_class->can('update_events_loggily') }
or return $job->completed();
- eval { $event_class->update_events_safely(%profile); 1 }
+ eval { $event_class->update_events_loggily(%profile); 1 }
or return $job->permanent_failure($@ || q{});
return $job->completed();
}
1;
|
markpasc/mt-plugin-action-streams
|
43d47717f0f608f0599df87e67037b9f9d45b538
|
Fixed a number of bugs in ActionStreams plugin: * ActionStreams::Plugin - Added username to page title for list_profileevent other_profiles modes to provide proper context (e.g. "Other profiles for USERNAME" instead of just "Other profiles") to admins who might be looking at or editing multiple * Created ActionStreams::Plugin::_edit_author method as a central way to get the profile author and check permissions of the editing user. * Made the permission/object loading errors consistent with those already used (and translated!) in the app. * Fixed escape code bugs in ActionStreams::Event which caused $class->method to be rendered as $class-method. E<gt> vs E<GT>
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Event.pm b/plugins/ActionStreams/lib/ActionStreams/Event.pm
index b1de43b..9bae2b3 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Event.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Event.pm
@@ -25,736 +25,736 @@ __PACKAGE__->install_properties({
indexes => {
identifier => 1,
author_id => 1,
created_on => 1,
created_by => 1,
},
class_type => 'event',
audit => 1,
meta => 1,
datasource => 'profileevent',
primary_key => 'id',
});
__PACKAGE__->install_meta({
columns => [ qw(
title
url
thumbnail
via
via_id
) ],
});
# Oracle does not like an identifier of more than 30 characters.
sub datasource {
my $class = shift;
my $r = MT->request;
my $ds = $r->cache('as_event_ds');
return $ds if $ds;
my $dss_oracle = qr/(db[id]::)?oracle/;
if ( my $type = MT->config('ObjectDriver') ) {
if ((lc $type) =~ m/^$dss_oracle$/) {
$ds = 'as';
}
}
$ds = $class->properties->{datasource}
unless $ds;
$r->cache('as_event_ds', $ds);
return $ds;
}
sub encode_field_for_html {
my $event = shift;
my ($field) = @_;
return encode_html( $event->$field() );
}
sub as_html {
my $event = shift;
my %params = @_;
my $stream = $event->registry_entry or return '';
# How many spaces are there in the form?
my $form = $params{form} || $stream->{html_form} || q{};
my @nums = $form =~ m{ \[ _ (\d+) \] }xmsg;
my $max = shift @nums;
for my $num (@nums) {
$max = $num if $max < $num;
}
# Do we need to supply the author name?
my @content = map { $event->encode_field_for_html($_) }
@{ $stream->{html_params} };
if ($max > scalar @content) {
my $name = defined $params{name} ? $params{name}
: $event->author->nickname
;
unshift @content, encode_html($name);
}
return MT->translate($form, @content);
}
sub update_events_safely {
my $class = shift;
my %profile = @_;
# Keep this option out of band so we don't have to count on
# implementations of update_events() passing it through.
local $hide_timeless = delete $profile{hide_timeless} ? 1 : 0;
my $warn = $SIG{__WARN__} || sub { print STDERR $_[0] };
local $SIG{__WARN__} = sub {
my ($msg) = @_;
$msg =~ s{ \n \z }{}xms;
$msg = MT->component('ActionStreams')->translate(
'[_1] updating [_2] events for [_3]',
$msg, $profile{type}, $profile{author}->name,
);
$warn->("$msg\n");
};
eval {
$class->update_events(%profile);
};
if (my $err = $@) {
my $plugin = MT->component('ActionStreams');
my $err_msg = $plugin->translate("Error updating events for [_1]'s [_2] stream (type [_3] ident [_4]): [_5]",
$profile{author}->name, $class->properties->{class_type},
$profile{type}, $profile{ident}, $err);
MT->log($err_msg);
die $err; # re-throw so we can handle from job invocation
}
}
sub update_events {
my $class = shift;
my %profile = @_;
my $author = delete $profile{author};
my $stream = $class->registry_entry or return;
my $fetch = $stream->{fetch} || {};
local $profile{url} = $stream->{url};
die "Oops, no url?" if !$profile{url};
die "Oops, no ident?" if !$profile{ident};
$profile{url} =~ s/ {{ident}} / $profile{ident} /xmsge;
my $items;
if (my $xpath_params = $stream->{xpath}) {
$items = $class->fetch_xpath(
%$xpath_params,
%$fetch,
%profile,
);
}
elsif (my $atom_params = $stream->{atom}) {
my $get = {
created_on => 'published',
modified_on => 'updated',
title => 'title',
url => q{link[@rel='alternate']/@href},
via => q{link[@rel='alternate']/@href},
via_id => 'id',
identifier => 'id',
};
$atom_params = {} if !ref $atom_params;
@$get{keys %$atom_params} = values %$atom_params;
$items = $class->fetch_xpath(
foreach => '//entry',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $rss_params = $stream->{rss}) {
my $get = {
title => 'title',
url => 'link',
via => 'link',
created_on => 'pubDate',
thumbnail => 'media:thumbnail/@url',
via_id => 'guid',
identifier => 'guid',
};
$rss_params = {} if !ref $rss_params;
@$get{keys %$rss_params} = values %$rss_params;
$items = $class->fetch_xpath(
foreach => '//item',
get => $get,
%$fetch,
%profile
);
for my $item (@$items) {
if ($item->{modified_on} && !$item->{created_on}) {
$item->{created_on} = $item->{modified_on};
}
}
}
elsif (my $scraper_params = $stream->{scraper}) {
my ($foreach, $get) = @$scraper_params{qw( foreach get )};
my $scraper = scraper {
process $foreach, 'res[]' => scraper {
while (my ($field, $sel) = each %$get) {
process $sel->[0], $field => $sel->[1];
}
};
result 'res';
};
$items = $class->fetch_scraper(
scraper => $scraper,
%$fetch,
%profile,
);
}
return if !$items;
$class->build_results(
items => $items,
stream => $stream,
author => $author,
profile => \%profile,
);
}
sub registry_entry {
my $event = shift;
my ($type, $stream) = split /_/, $event->properties->{class_type}, 2;
my $reg = MT->instance->registry('action_streams') or return;
my $service = $reg->{$type} or return;
$service->{$stream};
}
sub author {
my $event = shift;
my $author_id = $event->author_id
or return;
return MT->instance->model('author')->lookup($author_id);
}
sub blog_id { 0 }
sub classes_for_type {
my $class = shift;
my ($type) = @_;
my $prevts = MT->instance->registry('action_streams');
my $prevt = $prevts->{$type};
return if !$prevt;
my @classes;
PACKAGE: while (my ($stream_id, $stream) = each %$prevt) {
next if 'HASH' ne ref $stream;
next if !$stream->{class} && !$stream->{url};
my $pkg;
if ($pkg = $stream->{class}) {
$pkg = join q{::}, $class, $pkg if $pkg && $pkg !~ m{::}xms;
if (!eval { $pkg->properties }) {
if (!eval "require $pkg; 1") {
my $error = $@ || q{};
my $pl = MT->component('ActionStreams');
MT->log($pl->translate('Could not load class [_1] for stream [_2] [_3]: [_4]',
$pkg, $type, $stream_id, $error));
next PACKAGE;
}
}
}
else {
$pkg = join q{::}, $class, 'Auto', ucfirst $type,
ucfirst $stream_id;
if (!eval { $pkg->properties }) {
eval "package $pkg; use base qw( $class ); 1" or next;
my $class_type = join q{_}, $type, $stream_id;
$pkg->install_properties({ class_type => $class_type });
$pkg->install_meta({ columns => $stream->{fields} })
if $stream->{fields};
}
}
push @classes, $pkg;
}
return @classes;
}
my $ua;
sub ua {
my $class = shift;
my %params = @_;
$ua ||= MT->new_ua({
paranoid => 1,
timeout => 10,
});
$ua->max_size(250_000) if $ua->can('max_size');
$ua->agent($params{default_useragent} ? $ua->_agent
: "mt-actionstreams-lwp/" . MT->component('ActionStreams')->version);
return $ua if $class->class_type eq 'event';
require ActionStreams::UserAgent::Adapter;
my $adapter = ActionStreams::UserAgent::Adapter->new(
ua => $ua,
action_type => $class->class_type,
);
return $adapter;
}
sub set_values {
my $event = shift;
my ($values) = @_;
for my $meta_col (keys %{ $event->properties->{meta_columns} || {} }) {
my $meta_val = delete $values->{$meta_col};
$event->$meta_col($meta_val) if defined $meta_val;
}
$event->SUPER::set_values($values);
}
sub fetch_xpath {
my $class = shift;
my %params = @_;
my $url = $params{url} || '';
if (!$url) {
MT->log("No URL to fetch for $class results");
return;
}
my $ua = $class->ua(%params);
my $res = $ua->get($url);
if (!$res->is_success()) {
MT->log("Could not fetch ${url}: " . $res->status_line())
if $res->code != 304;
return;
}
# Strip leading whitespace, since the parser doesn't like it.
# TODO: confirm we got xml?
my $content = $res->content;
$content =~ s{ \A \s+ }{}xms;
require XML::XPath;
my $x = XML::XPath->new( xml => $content );
my @items;
ITEM: for my $item ($x->findnodes($params{foreach})) {
my %item_data;
VALUE: while (my ($key, $val) = each %{ $params{get} }) {
next VALUE if !$val;
if ($key eq 'tags') {
my @outvals = $item->findnodes($val)
or next VALUE;
$item_data{$key} = [ map { $_->getNodeValue } @outvals ];
}
else {
my $outval = $item->findvalue($val)
or next VALUE;
$outval = "$outval";
if ($outval && ($key eq 'created_on' || $key eq 'modified_on')) {
# try both RFC 822/1123 and ISO 8601 formats
$outval = MT::Util::epoch2ts(undef, str2time($outval))
|| MT::Util::iso2ts(undef, $outval);
}
$item_data{$key} = $outval if $outval;
}
}
push @items, \%item_data;
}
return \@items;
}
sub build_results {
my $class = shift;
my %params = @_;
my ($author, $items, $profile, $stream) =
@params{qw( author items profile stream )};
my $mt = MT->app;
ITEM: for my $item (@$items) {
my $event;
my $identifier = delete $item->{identifier};
if (!defined $identifier && (defined $params{identifier} || defined $stream->{identifier})) {
$identifier = join q{:}, @$item{ split /,/, $params{identifier} || $stream->{identifier} };
}
if (defined $identifier) {
$identifier = "$identifier";
($event) = $class->search({
author_id => $author->id,
identifier => $identifier,
});
}
$event ||= $class->new;
$mt->run_callbacks('pre_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
my $tags = delete $item->{tags};
$event->set_values({
author_id => $author->id,
identifier => $identifier,
%$item,
});
$event->tags(@$tags) if $tags;
if ($hide_timeless && !$event->created_on) {
$event->visible(0);
}
$mt->run_callbacks('post_build_action_streams_event.'
. $class->class_type, $mt, $item, $event, $author, $profile);
$event->save() or MT->log($event->errstr);
}
1;
}
sub save {
my $event = shift;
# Built-in audit field setting will set a local time, so do it ourselves.
if (!$event->created_on) {
my $ts = MT::Util::epoch2ts(undef, time);
$event->created_on($ts);
$event->modified_on($ts);
}
return $event->SUPER::save(@_);
}
sub fetch_scraper {
my $class = shift;
my %params = @_;
my ($url, $scraper) = @params{qw( url scraper )};
$scraper->user_agent($class->ua(%params));
my $items = $scraper->scrape(URI->new($url));
# we're only being used for our scraper.
return if !$items;
return $items if !ref $items;
return $items if 'ARRAY' ne ref $items;
ITEM: for my $item (@$items) {
next ITEM if !ref $item || ref $item ne 'HASH';
for my $field (keys %$item) {
if ($field eq 'tags') {
$item->{$field} = [ map { "$_" } @{ $item->{$field} } ];
}
else {
$item->{$field} = q{} . $item->{$field};
}
}
}
return $items;
}
1;
__END__
=head1 NAME
ActionStreams::Event - an Action Streams stream definition
=head1 SYNOPSIS
# in plugin's config.yaml
profile_services:
example:
streamid:
name: Dice Example
description: A simple die rolling Perl stream example.
html_form: [_1] rolled a [_2]!
html_params:
- title
class: My::Stream
# in plugin's lib/My/Stream.pm
package My::Stream;
use base qw( ActionStreams::Event );
__PACKAGE__->install_properties({
class_type => 'example_streamid',
});
sub update_events {
my $class = shift;
my %profile = @_;
# trivial example: save a random number
my $die_roll = int rand 20;
my %item = (
title => $die_roll,
identifier => $die_roll,
);
return $class->build_results(
author => $profile{author},
items => [ \%item ],
);
}
1;
=head1 DESCRIPTION
I<ActionStreams::Event> provides the basic implementation of an action stream.
Stream definitions are engines for turning web resources into I<actions> (also
called I<events>). This base class produces actions based on generic stream
recipes defined in the MT registry, as well as providing the internal machinery
for you to implement your own streams in Perl code.
=head1 METHODS TO IMPLEMENT
These are the methods one commonly implements (overrides) when implementing a
stream subclass.
-=head2 C<$class-E<GT>update_events(%profile)>
+=head2 C<$class-E<gt>update_events(%profile)>
Fetches the web resource specified by the profile parameters, collects data
from it into actions, and saves the action records for use later. Required
members of C<%profile> are:
=over 4
=item * C<author>
The C<MT::Author> instance for whom events should be collected.
=item * C<ident>
The author's identifier on the given service.
=back
Other information about the stream, such as the URL pattern into which the
C<ident> parameter can be replaced, is available through the
C<$class-E<gt>registry_entry()> method.
-=head2 C<$self-E<GT>as_html(%params)>
+=head2 C<$self-E<gt>as_html(%params)>
Returns the HTML version of the action, suitable for display to readers.
The default implementation uses the stream's registry definition to construct
the action: the author's name and the action's values as named in
C<html_params> are replaced into the stream's C<html_form> setting. You need
override it only if you have more complex requirements.
Optional members of C<%params> are:
=over 4
=item * C<form>
The formatting string to use. If not given, the C<html_form> specified for
this stream in the registry is used.
=item * C<name>
The text to use as the author's name if C<as_html> needs to provide it
automatically in the result. Author names are provided if there are more
tokens in C<html_form> than there are fields specified in C<html_params>.
If not given, the event's author's nickname is provided. Note that a defined
but empty name (such as C<q{}>) I<will> be used; in this case, the name will
appear to be omitted from the result of the C<as_html> call.
=back
=head1 AVAILABLE METHODS
These are the methods provided by I<ActionStreams::Event> to perform common
tasks. Call them from your overridden methods.
-=head2 C<$self-E<GT>set_values(\%values)>
+=head2 C<$self-E<gt>set_values(\%values)>
Stores the data given in C<%values> as members of this event.
-=head2 C<$class-E<GT>fetch_xpath(%param)>
+=head2 C<$class-E<gt>fetch_xpath(%param)>
Returns the items discovered by scanning a web resource by the given XPath
recipe. Required members of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be a
valid XML document.
=item * C<foreach>
The XPath selector with which to select the individual events from the
resource.
=item * C<get>
A hashref containing the XPath selectors with which to collect individual data
for each item, keyed on the names of the fields to contain the data.
=back
C<%param> may also contain additional arguments for the C<ua()> method.
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
-=head2 C<$class-E<GT>fetch_scraper(%param)>
+=head2 C<$class-E<gt>fetch_scraper(%param)>
Returns the items discovered by scanning by the given recipe. Required members
of C<%param> are:
=over 4
=item * C<url>
The address of the web resource to scan for events. The resource should be an
HTML or XML document suitable for analysis by the C<Web::Scraper> module.
=item * C<scraper>
The C<Web::Scraper> scraper with which to extract item data from the specified
web resource. See L<Web::Scraper> for information on how to construct a
scraper.
=back
Returned items are hashrefs containing the discovered fields, suitable for
turning into C<ActionStreams::Event> records with the C<build_results()>
method.
See also the below I<NOTE ON WEB::SCRAPER>.
-=head2 C<$class-E<GT>build_results(%param)>
+=head2 C<$class-E<gt>build_results(%param)>
Converts a set of collected items into saved action records of type C<$class>.
The required members of C<%param> are:
=over 4
=item * C<author>
The C<MT::Author> instance whose action the items represent.
=item * C<items>
An arrayref of items to save as actions. Each item is a hashref containing the
action data, keyed on the names of the fields containing the data.
=back
Optional parameters are:
=over 4
=item * C<profile>
An arrayref describing the data for the author's profile for the associated
stream, such as is returned by the C<MT::Author::other_profile()> method
supplied by the Action Streams plugin.
The profile member is not used directly by C<build_results()>; they are only
passed to callbacks.
=item * C<stream>
A hashref containing the settings from the registry about the stream, such as
is returned from the C<registry_entry()> method.
=back
-=head2 C<$class-E<GT>ua(%param)>
+=head2 C<$class-E<gt>ua(%param)>
Returns the common HTTP user-agent, an instance of C<LWP::UserAgent>, with
which you can fetch web resources. No arguments are required; possible optional
parameters are:
=over 4
=item * C<default_useragent>
If set, the returned HTTP user-agent will use C<LWP::UserAgent>'s default
identifier in the HTTP C<User-Agent> header. If omitted, the UA will use the
Action Streams identifier of C<mt-actionstreams-lwp/I<version>>.
=back
-=head2 C<$self-E<GT>author()>
+=head2 C<$self-E<gt>author()>
Returns the C<MT::Author> instance associated with this event, if its
C<author_id> field has been set.
-=head2 C<$class-E<GT>install_properties(\%properties)>
+=head2 C<$class-E<gt>install_properties(\%properties)>
I<TODO>
-=head2 C<$class-E<GT>install_meta(\%properties)>
+=head2 C<$class-E<gt>install_meta(\%properties)>
I<TODO>
-=head2 C<$class-E<GT>registry_entry()>
+=head2 C<$class-E<gt>registry_entry()>
Returns the registry data for the stream represented by C<$class>.
-=head2 C<$class-E<GT>classes_for_type($service_id)>
+=head2 C<$class-E<gt>classes_for_type($service_id)>
Given a profile service ID (that is, a key from the C<profile_services> section
of the registry), returns a list of stream classes for scanning that service's
streams.
=head1 NOTE ON WEB::SCRAPER
The C<Web::Scraper> module is powerful, but it has complex dependencies. While
its pure Perl requirements are bundled with the Action Streams plugin, it also
requires a compiled XML module. Also, because of how its syntax works, you must
directly C<use> the module in your own code, contrary to the Movable Type idiom
of using C<require> so that modules are loaded only when they are sure to be
used.
If you attempt load C<Web::Scraper> in the normal way, but C<Web::Scraper> is
unable to load due to its missing requirement, whenever the plugin attempts to
load your scraper, the entire plugin will fail to load.
Therefore the C<ActionStreams::Scraper> wrapper module is provided for you. If
you need to load C<Web::Scraper> so as to make a scraper to pass
C<ActionStreams::Event::fetch_scraper()> method, instead write in your module:
use ActionStreams::Scraper;
This module provides the C<Web::Scraper> interface, but if C<Web::Scraper> is
unable to load, the error will be thrown when your module tries to I<use> it,
rather than when you I<load> it. That is, if C<Web::Scraper> can't load, no
errors will be thrown to end users until they try to use your stream.
=head1 AUTHOR
Mark Paschal E<lt>[email protected]<gt>
=cut
diff --git a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
index bb32a96..cce5fd8 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Plugin.pm
@@ -1,711 +1,726 @@
package ActionStreams::Plugin;
use strict;
use warnings;
use Carp qw( croak );
use MT::Util qw( relative_date offset_time epoch2ts ts2epoch format_ts );
sub users_content_nav {
my ($cb, $app, $html_ref) = @_;
return unless $app->param('id');
$$html_ref =~ s{class=["']active["']}{}xmsg
if $app->mode eq 'list_profileevent' || $app->mode eq 'other_profiles';
$$html_ref =~ m{ "> ((?:<b>)?) <__trans \s phrase="Permissions"> ((?:</b>)?) </a> }xms;
my ($open_bold, $close_bold) = ($1, $2);
my $html = <<"EOF";
<mt:if var="USER_VIEW">
<li><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">">$open_bold<__trans phrase="Other Profiles">$close_bold</a></li>
<li><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="EDIT_AUTHOR_ID" escape="url">">$open_bold<__trans phrase="Action Stream">$close_bold</a></li>
</mt:if>
<mt:if var="edit_author">
<li<mt:if name="other_profiles"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=other_profiles&id=<mt:var name="id" escape="url">">$open_bold<__trans phrase="Other Profiles">$close_bold</a></li>
<li<mt:if name="list_profileevent"> class="active"</mt:if>><a href="<mt:var name="SCRIPT_URL">?__mode=list_profileevent&id=<mt:var name="id" escape="url">">$open_bold<__trans phrase="Action Stream">$close_bold</a></li>
</mt:if>
EOF
$$html_ref =~ s{(?=</ul>)}{$html}xmsg;
}
sub icon_url_for_service {
my $class = shift;
my ($type, $ndata) = @_;
my $plug = $ndata->{plugin} or return;
my $icon_url;
if ($ndata->{icon} && $ndata->{icon} =~ m{ \A \w:// }xms) {
$icon_url = $ndata->{icon};
}
elsif ($ndata->{icon}) {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
$ndata->{icon};
}
elsif ($plug->id eq 'actionstreams') {
$icon_url = MT->app->static_path . join q{/}, $plug->envelope,
'images', 'services', $type . '.png';
}
return $icon_url;
}
+sub _edit_author {
+ my $app = shift;
+ my $author_id = $app->param('id')
+ || ($app->user ? $app->user->id : undef);
+
+ my $class = MT->model('author');
+ my $author = $class->load($author_id) if $author_id;
+
+ $author or return $app->error(
+ $app->translate( "No such [_1].", lc( $class->class_label ) ) );
+
+ return $app->error( $app->translate("Permission denied.") )
+ if ! $app->user
+ or $app->user->id != $author_id && !$app->user->is_superuser();
+
+ return $author;
+}
+
sub list_profileevent {
my $app = shift;
my %param = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
- my $author_id = $app->param('id')
- or return;
- return $app->error('Not permitted to view')
- if $app->user->id != $author_id && !$app->user->is_superuser();
+ my $author = _edit_author($app) or return;
my %service_styles;
my @service_styles_loop;
my $code = sub {
my ($event, $row) = @_;
my @meta_col = keys %{ $event->properties->{meta_columns} || {} };
$row->{$_} = $event->{$_} for @meta_col;
$row->{as_html} = $event->as_html();
my ($service, $stream_id) = split /_/, $row->{class}, 2;
$row->{type} = $service;
my $nets = $app->registry('profile_services') || {};
my $net = $nets->{$service};
$row->{service} = $net->{name} if $net;
$row->{url} = $event->url;
if (!$service_styles{$service}) {
if (!$net->{plugin} || $net->{plugin}->id ne 'actionstreams') {
if (my $icon = __PACKAGE__->icon_url_for_service($service, $net)) {
push @service_styles_loop, {
service_type => $service,
service_icon => $icon,
};
}
}
$service_styles{$service} = 1;
}
my $ts = $row->{created_on};
$row->{created_on_relative} = relative_date($ts, time);
$row->{created_on_formatted} = format_ts(
MT::App::CMS->LISTING_DATETIME_FORMAT(),
epoch2ts(undef, offset_time(ts2epoch(undef, $ts))),
undef,
$app->user ? $app->user->preferred_language : undef,
);
};
# Make sure all classes are loaded.
require ActionStreams::Event;
for my $prevt (keys %{ $app->registry('action_streams') }) {
ActionStreams::Event->classes_for_type($prevt);
}
my $plugin = MT->component('ActionStreams');
my %params = map { $_ => $app->param($_) ? 1 : 0 }
qw( saved_deleted hidden shown );
+ $params{id} = $params{edit_author_id} = $author->id;
+ $params{name} = $params{edit_author_name} = $author->name;
+
$params{services} = [];
my $services = $app->registry('profile_services');
while (my ($prevt, $service) = each %$services) {
push @{ $params{services} }, {
service_id => $prevt,
service_name => $service->{name},
};
}
$params{services} = [ sort { lc $a->{service_name} cmp lc $b->{service_name} } @{ $params{services} } ];
my %terms = (
class => '*',
- author_id => $author_id,
+ author_id => $author->id,
);
my %args = (
sort => 'created_on',
direction => 'descend',
);
if (my $filter = $app->param('filter')) {
$params{filter_key} = $filter;
my $filter_val = $params{filter_val} = $app->param('filter_val');
if ($filter eq 'service') {
$params{filter_label} = $app->translate('Actions from the service [_1]', $app->registry('profile_services')->{$filter_val}->{name});
$terms{class} = $filter_val . '_%';
$args{like} = { class => 1 };
}
elsif ($filter eq 'visible') {
$params{filter_label} = ($filter_val eq 'show') ? 'Actions that are shown'
: 'Actions that are hidden';
$terms{visible} = $filter_val eq 'show' ? 1 : 0;
}
}
-
- $params{id} = $params{edit_author_id} = $author_id;
$params{service_styles} = \@service_styles_loop;
$app->listing({
type => 'profileevent',
terms => \%terms,
args => \%args,
listing_screen => 1,
code => $code,
template => $plugin->load_tmpl('list_profileevent.tmpl'),
params => \%params,
});
}
sub itemset_hide_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(0);
$event->save;
}
$app->add_return_arg( hidden => 1 );
$app->call_return;
}
sub itemset_show_events {
my ($app) = @_;
$app->validate_magic or return;
my @events = $app->param('id');
for my $event_id (@events) {
my $event = MT->model('profileevent')->load($event_id)
or next;
next if $app->user->id != $event->author_id && !$app->user->is_superuser();
$event->visible(1);
$event->save;
}
$app->add_return_arg( shown => 1 );
$app->call_return;
}
sub _itemset_hide_show_all_events {
my ($app, $new_visible) = @_;
$app->validate_magic or return;
my $event_class = MT->model('profileevent');
# Really we should work directly from the selected author ID, but as an
# itemset event we only got some event IDs. So use its.
my ($event_id) = $app->param('id');
my $event = $event_class->load($event_id)
or return $app->error($app->translate('No such event [_1]', $event_id));
my $author_id = $event->author_id;
return $app->error('Not permitted to modify')
- if $author_id != $app->user->id && !$app->is_superuser();
+ if ! $app->user
+ or ! $app->user->is_superuser() && $author_id != $app->user->id;
my $driver = $event_class->driver;
my $stmt = $driver->prepare_statement($event_class, {
# TODO: include filter value when we have filters
author_id => $author_id,
visible => $new_visible ? 0 : 1,
});
my $sql = "UPDATE " . $driver->table_for($event_class) . " SET "
. $driver->dbd->db_column_name($event_class->datasource, 'visible')
. " = ? " . $stmt->as_sql_where;
# Work around error in MT::ObjectDriver::Driver::DBI::sql by doing it inline.
my $dbh = $driver->rw_handle;
$dbh->do($sql, {}, $new_visible, @{ $stmt->{bind} })
or return $app->error($dbh->errstr);
return 1;
}
sub itemset_hide_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 0) or return;
$app->add_return_arg( all_hidden => 1 );
$app->call_return;
}
sub itemset_show_all_events {
my $app = shift;
_itemset_hide_show_all_events($app, 1) or return;
$app->add_return_arg( all_shown => 1 );
$app->call_return;
}
sub _build_service_data {
my %info = @_;
my ($networks, $streams, $author) = @info{qw( networks streams author )};
my (@service_styles_loop, @networks);
my %has_profiles;
if ($author) {
my $other_profiles = $author->other_profiles();
$has_profiles{$_->{type}} = 1 for @$other_profiles;
}
my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
keys %$networks;
TYPE: for my $type (@network_keys) {
my $ndata = $networks->{$type}
or next TYPE;
my @streams;
if ($streams) {
my $streamdata = $streams->{$type} || {};
@streams =
sort { lc $a->{name} cmp lc $b->{name} }
grep { grep { $_ } @$_{qw( class scraper xpath rss atom )} }
map { +{ stream => $_, %{ $streamdata->{$_} } } }
grep { $_ ne 'plugin' }
keys %$streamdata;
}
my $ret = {
type => $type,
%$ndata,
label => $ndata->{name},
user_has_account => ($has_profiles{$type} ? 1 : 0),
};
$ret->{streams} = \@streams if @streams;
push @networks, $ret;
if (!$ndata->{plugin} || $ndata->{plugin}->id ne 'actionstreams') {
push @service_styles_loop, {
service_type => $type,
service_icon => __PACKAGE__->icon_url_for_service($type, $ndata),
};
}
}
return (
service_styles => \@service_styles_loop,
networks => \@networks,
);
}
sub other_profiles {
my( $app ) = @_;
$app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
- my $author_id = $app->param('id')
- or return $app->error('Author id is required');
- my $user = MT->model('author')->load($author_id)
- or return $app->error('Author id is invalid');
- return $app->error('Not permitted to view')
- if $app->user->id != $author_id && !$app->user->is_superuser();
+ my $author = _edit_author($app) or return;
+
+ my %params;
+ $params{id} = $params{edit_author_id} = $author->id;
+ $params{name} = $params{edit_author_name} = $author->name;
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl( 'other_profiles.tmpl' );
my @profiles = sort { lc $a->{label} cmp lc $b->{label} }
- @{ $user->other_profiles || [] };
+ @{ $author->other_profiles || [] };
my %messages = map { $_ => $app->param($_) ? 1 : 0 }
(qw( added removed updated edited ));
return $app->build_page( $tmpl, {
- id => $user->id,
- edit_author_id => $user->id,
+ %params,
profiles => \@profiles,
listing_screen => 1,
_build_service_data(
networks => $app->registry('profile_services'),
),
%messages,
} );
}
sub dialog_add_edit_profile {
my ($app) = @_;
return $app->error('Not permitted to view')
if $app->user->id != $app->param('author_id') && !$app->user->is_superuser();
my $author = MT->model('author')->load($app->param('author_id'))
or return $app->error('No such author [_1]', $app->param('author_id'));
my %edit_profile;
my $tmpl_name = 'dialog_add_profile.tmpl';
if (my $edit_type = $app->param('profile_type')) {
my $ident = $app->param('profile_ident') || q{};
my ($profile) = grep { $_->{ident} eq $ident }
@{ $author->other_profiles($edit_type) };
%edit_profile = (
edit_type => $edit_type,
edit_type_name => $app->registry('profile_services', $edit_type, 'name'),
edit_ident => $ident,
edit_streams => $profile->{streams} || [],
);
$tmpl_name = 'dialog_edit_profile.tmpl';
}
my $plugin = MT->component('ActionStreams');
my $tmpl = $plugin->load_tmpl($tmpl_name);
return $app->build_page($tmpl, {
edit_author_id => $app->param('author_id'),
_build_service_data(
networks => $app->registry('profile_services'),
streams => $app->registry('action_streams'),
author => $author,
),
%edit_profile,
});
}
sub edit_other_profile {
my $app = shift;
$app->validate_magic() or return;
my $author_id = $app->param('author_id')
or return $app->error('Author id is required');
my $user = MT->model('author')->load($author_id)
or return $app->error('Author id is invalid');
return $app->error('Not permitted to edit')
if $app->user->id != $author_id && !$app->user->is_superuser();
my $type = $app->param('profile_type');
my $orig_ident = $app->param('original_ident');
$user->remove_profile($type, $orig_ident);
$app->forward('add_other_profile', success_msg => 'edited');
}
sub add_other_profile {
my $app = shift;
my %param = @_;
$app->validate_magic or return;
my $author_id = $app->param('author_id')
or return $app->error('Author id is required');
my $user = MT->model('author')->load($author_id)
or return $app->error('Author id is invalid');
return $app->error('Not permitted to add')
if $app->user->id != $author_id && !$app->user->is_superuser();
my( $ident, $uri, $label, $type );
if ( $type = $app->param( 'profile_type' ) ) {
my $reg = $app->registry('profile_services');
my $network = $reg->{$type}
or croak "Unknown network $type";
$label = $network->{name} . ' Profile';
$ident = $app->param( 'profile_id' );
$ident =~ s{ \A \s* }{}xms;
$ident =~ s{ \s* \z }{}xms;
# Check for full URLs.
if (!$network->{ident_exact}) {
my $url_pattern = $network->{url};
my ($pre_ident, $post_ident) = split /(?:\%s|\Q{{ident}}\E)/, $url_pattern, 2;
$pre_ident =~ s{ \A http:// }{}xms;
$post_ident =~ s{ / \z }{}xms;
if ($ident =~ m{ \A (?:http://)? \Q$pre_ident\E (.*?) \Q$post_ident\E /? \z }xms) {
$ident = $1;
}
}
$uri = $network->{url};
$uri =~ s{ (?:\%s|\Q{{ident}}\E) }{$ident}xmsg;
} else {
$ident = $uri = $app->param( 'profile_uri' );
$label = $app->param( 'profile_label' );
$type = 'website';
}
my $profile = {
type => $type,
ident => $ident,
label => $label,
uri => $uri,
};
my %streams = map { join(q{_}, $type, $_) => 1 }
grep { $_ ne 'plugin' && $app->param(join q{_}, 'stream', $type, $_) }
keys %{ $app->registry('action_streams', $type) || {} };
$profile->{streams} = \%streams if %streams;
$app->run_callbacks('pre_add_profile.' . $type, $app, $user, $profile);
$user->add_profile($profile);
$app->run_callbacks('post_add_profile.' . $type, $app, $user, $profile);
my $success_msg = $param{success_msg} || 'added';
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => $author_id, $success_msg => 1 },
));
}
sub remove_other_profile {
my( $app ) = @_;
$app->validate_magic or return;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
or next PROFILE;
next PROFILE
if $app->user->id != $author_id && !$app->user->is_superuser();
$app->run_callbacks('pre_remove_profile.' . $type, $app, $user, $type, $ident);
$user->remove_profile( $type, $ident );
$app->run_callbacks('post_remove_profile.' . $type, $app, $user, $type, $ident);
$page_author_id = $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), removed => 1 },
));
}
sub profile_add_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
$app->param('author_id', $user->id);
my $type = $app->param('profile_type')
or return $app->error( $app->translate("Invalid request.") );
# The profile side interface doesn't have stream selection, so select
# them all by default.
# TODO: factor out the adding logic (and parameterize stream selection) to stop faking params
foreach my $stream ( keys %{ $app->registry('action_streams', $type) || {} } ) {
next if $stream eq 'plugin';
$app->param(join('_', 'stream', $type, $stream), 1);
}
add_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub profile_first_update_events {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub profile_delete_external_profile {
my $app = shift;
my %param = @_;
my $user = $app->_login_user_commenter();
return $app->error( $app->translate("Invalid request.") )
unless $user;
$app->validate_magic or return;
# TODO: make sure profile is an accepted type
# TODO: factor out this logic instead of having to fake params
my $id = scalar $app->param('id');
$id = $user->id . ':' . $id;
$app->param('id', $id);
remove_other_profile($app);
return if $app->errstr;
# forward on to community profile view
return $app->redirect($app->uri(
mode => 'view',
args => { id => $user->id,
( $app->blog ? ( blog_id => $app->blog->id ) : () ) },
));
}
sub itemset_update_profiles {
my $app = shift;
my %users;
my $page_author_id;
PROFILE: for my $profile ($app->param('id')) {
my ($author_id, $type, $ident) = split /:/, $profile, 3;
my $user = ($users{$author_id} ||= MT->model('author')->load($author_id))
or next PROFILE;
next PROFILE
if $app->user->id != $author_id && !$app->user->is_superuser();
my $profiles = $user->other_profiles($type);
if (!$profiles) {
next PROFILE;
}
my @profiles = grep { $_->{ident} eq $ident } @$profiles;
for my $author_profile (@profiles) {
update_events_for_profile($user, $author_profile,
synchronous => 1);
}
$page_author_id ||= $author_id;
}
return $app->redirect($app->uri(
mode => 'other_profiles',
args => { id => ($page_author_id || $app->user->id), updated => 1 },
));
}
sub first_profile_update {
my ($cb, $app, $user, $profile) = @_;
update_events_for_profile($user, $profile,
synchronous => 1, hide_timeless => 1);
}
sub rebuild_action_stream_blogs {
my ($cb, $app) = @_;
my $plugin = MT->component('ActionStreams');
my $pd_iter = MT->model('plugindata')->load_iter({
plugin => $plugin->key,
key => { like => 'configuration:blog:%' }
});
my %rebuild;
while ( my $pd = $pd_iter->() ) {
next unless $pd->data('rebuild_for_action_stream_events');
my ($blog_id) = $pd->key =~ m/:blog:(\d+)$/;
$rebuild{$blog_id} = 1;
}
for my $blog_id (keys %rebuild) {
# TODO: limit this to indexes that publish action stream data, once
# we can magically infer template content before building it
my $blog = MT->model('blog')->load( $blog_id ) or next;
# Republish all the blog's known non-virtual index fileinfos that
# have real template objects.
my $finfo_class = MT->model('fileinfo');
my $finfo_template_col = $finfo_class->driver->dbd->db_column_name(
$finfo_class->datasource, 'template_id');
my @fileinfos = $finfo_class->load({
blog_id => $blog->id,
archive_type => 'index',
virtual => [ \'IS NULL', 0 ],
}, {
join => MT->model('template')->join_on(undef,
{ id => \"= $finfo_template_col" }),
});
require MT::TheSchwartz;
require TheSchwartz::Job;
for my $fi (@fileinfos) {
my $job = TheSchwartz::Job->new();
$job->funcname('MT::Worker::Publish');
$job->uniqkey($fi->id);
$job->run_after(time + 240); # 4 minutes
MT::TheSchwartz->insert($job);
}
}
}
sub widget_recent {
my ($app, $tmpl, $widget_param) = @_;
$tmpl->param('author_id', $app->user->id);
$tmpl->param('blog_id', $app->blog->id) if $app->blog;
}
sub widget_blog_dashboard_only {
my ($page, $scope) = @_;
return if $scope eq 'dashboard:system';
return 1;
}
sub update_events {
my $mt = MT->app;
$mt->run_callbacks('pre_action_streams_task', $mt);
my $au_class = MT->model('author');
my $author_iter = $au_class->search({
status => $au_class->ACTIVE(),
}, {
join => [ $au_class->meta_pkg, 'author_id', { type => 'other_profiles' } ],
});
while (my $author = $author_iter->()) {
my $profiles = $author->other_profiles();
$mt->run_callbacks('pre_update_action_streams', $mt, $author, $profiles);
PROFILE: for my $profile (@$profiles) {
update_events_for_profile($author, $profile);
}
$mt->run_callbacks('post_update_action_streams', $mt, $author, $profiles);
}
$mt->run_callbacks('post_action_streams_task', $mt);
}
sub update_events_for_profile {
my ($author, $profile, %param) = @_;
my $type = $profile->{type};
my $streams = $profile->{streams};
return if !$streams || !%$streams;
require ActionStreams::Event;
my @event_classes = ActionStreams::Event->classes_for_type($type)
or return;
my $mt = MT->app;
$mt->run_callbacks('pre_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
EVENTCLASS: for my $event_class (@event_classes) {
next EVENTCLASS if !$streams->{$event_class->class_type};
if ($param{synchronous}) {
$event_class->update_events_safely(
author => $author,
hide_timeless => $param{hide_timeless} ? 1 : 0,
%$profile,
);
}
else {
# Defer regular updates to job workers.
require ActionStreams::Worker;
ActionStreams::Worker->make_work(
event_class => $event_class,
author => $author,
%$profile,
);
}
}
$mt->run_callbacks('post_update_action_streams_profile.' . $profile->{type},
$mt, $author, $profile);
}
1;
diff --git a/plugins/ActionStreams/tmpl/list_profileevent.tmpl b/plugins/ActionStreams/tmpl/list_profileevent.tmpl
index a9f51f5..b0b658f 100644
--- a/plugins/ActionStreams/tmpl/list_profileevent.tmpl
+++ b/plugins/ActionStreams/tmpl/list_profileevent.tmpl
@@ -1,276 +1,276 @@
<mt:setvar name="edit_author" value="1">
<mt:setvar name="list_profileevent" value="1">
-<mt:setvar name="page_title" value="<__trans phrase="Action Stream">">
+<mt:setvarblock name="page_title"><__trans phrase="Action Stream for [_1]" params="<mt:Var name="edit_author_name">"></mt:setvarblock>
<mt:setvarblock name="html_head" append="1">
<link rel="stylesheet" type="text/css" href="<mt:var name="static_uri">plugins/ActionStreams/css/action-streams.css" />
<script type="text/javascript">
<!--
var tableSelect;
function init() {
// set up table select awesomeness
tableSelect = new TC.TableSelect("profileevent-listing-table");
tableSelect.rowSelect = true;
}
TC.attachLoadEvent(init);
function finishPluginActionAll(f, action) {
var select_all = getByID('select-all-checkbox')
if (select_all) {
select_all.checked = true;
tableSelect.select(select_all);
}
return doForMarkedInThisWindow(f, '', 'profileevents', 'id', 'itemset_action',
{'action_name': action}, 'to act upon');
}
function toggleFilter() {
var filterActive = getByID("filter-title");
if (filterActive.style.display == "none") {
filterActive.style.display = "block";
getByID("filter-select").style.display = "none";
} else {
filterActive.style.display = "none";
getByID("filter-select").style.display = "block";
<mt:unless name="filter">setFilterCol('service');</mt:unless>
}
}
function setFilterCol(choice) {
var sel = getByID('filter-select');
if (!sel) return;
sel.className = "filter-" + choice;
if (choice != 'none') {
var fld = getByID('filter-col');
if (choice == 'service')
fld.selectedIndex = 0;
else if (choice == 'visible')
fld.selectedIndex = 1;
else if (choice == 'exacttag')
fld.selectedIndex = 2;
else if (choice == 'normalizedtag')
fld.selectedIndex = 3;
else if (choice == 'category_id')
fld.selectedIndex = 4;
else if (choice == 'asset_id')
fld.selectedIndex = <mt:if name="category_loop">5<mt:else>4</mt:if>;
col_span = getByID("filter-text-col");
if (fld.selectedIndex > -1 && col_span)
col_span.innerHTML = '<strong>' + fld.options[fld.selectedIndex].text + '</strong>';
}
}
function enableFilterButton(fld) {
if (fld && (fld.id == "filter-col")) {
var opt = fld.options[fld.selectedIndex];
if (opt.value == 'author_id') {
var authfld = getByID("author_id-val");
var authopt = authfld.options[authfld.selectedIndex];
if (authopt.value == "") {
getByID("filter-button").style.display = "none";
return;
}
}
}
getByID("filter-button").style.display = "inline";
}
// -->
</script>
<style type="text/css">
<!--
#filter-visible, #filter-service { display: none }
.filter-visible #filter-visible,
.filter-service #filter-service { display: inline }
#profileevent-listing-table .date { white-space: nowrap; }
#profileevent-listing-table .service { width: 8em; }
#main-content { padding-top: 5px; }
.content-nav #main-content .msg { margin-left: 0px; }
<mt:loop name="service_styles">
.service-<mt:var name="service_type"> { background-image: url(<mt:var name="service_icon">); }
</mt:loop>
// -->
</style>
</mt:setvarblock>
<mt:setvarblock name="content_nav">
<mt:include name="include/users_content_nav.tmpl">
</mt:setvarblock>
<mt:setvarblock name="system_msg">
<mt:if name="saved_deleted">
<mtapp:statusmsg
id="saved_deleted"
class="success">
<__trans phrase="The selected events were deleted.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="hidden">
<mtapp:statusmsg
id="hidden"
class="success">
<__trans phrase="The selected events were hidden.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="shown">
<mtapp:statusmsg
id="shown"
class="success">
<__trans phrase="The selected events were shown.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="all_hidden">
<mtapp:statusmsg
id="all_hidden"
class="success">
<__trans phrase="All action stream events were hidden.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="all_shown">
<mtapp:statusmsg
id="all_shown"
class="sucess">
<__trans phrase="All action stream events were shown.">
</mtapp:statusmsg>
</mt:if>
</mt:setvarblock>
<mt:setvarblock name="html_body_footer">
<mt:include name="include/display_options.tmpl">
</mt:setvarblock>
<mt:setvarblock name="action_buttons">
<a href="javascript:void(0)"
onclick="doForMarkedInThisWindow(getByID('profileevent-listing-form'), '<__trans phrase="event">', '<__trans phrase="events">', 'id', 'itemset_hide_events'); return false"
accesskey="h"
title="<__trans phrase="Hide selected events (h)">"
><__trans phrase="Hide"></a>
<a href="javascript:void(0)"
onclick="doForMarkedInThisWindow(getByID('profileevent-listing-form'), '<__trans phrase="event">', '<__trans phrase="events">', 'id', 'itemset_show_events'); return false"
accesskey="h"
title="<__trans phrase="Show selected events (h)">"
><__trans phrase="Show"></a>
</mt:setvarblock>
<mt:include name="include/header.tmpl">
<div class="listing-filter">
<div class="listing-filter-inner inner pkg">
<form id="filter-form" method="get" action="<mt:var name="mt_url">">
<input type="hidden" name="__mode" value="<mt:var name="mode">" />
<mt:if name="id">
<input type="hidden" name="id" value="<mt:var name="id" escape="url">" />
</mt:if>
<mt:if name="is_power_edit">
<input type="hidden" name="is_power_edit" value="1" />
</mt:if>
<input id="filter" type="hidden" name="filter" value="" />
<input id="filter_val" type="hidden" name="filter_val" value="" />
</form>
<form id="filter-select-form" method="get" onsubmit="return execFilter(this)">
<div class="filter">
<div id="filter-title">
<mt:if name="filter_key">
<strong>Showing only: <mt:var name="filter_label" escape="html"></strong>
<a class="filter-link" href="<mt:var name="script_url">?__mode=<mt:var name="mode">&id=<mt:var name="id" escape="url">">[ Remove filter ]</a>
<mt:else>
<mt:if name="filter">
<mt:else>
<strong>All stream actions</strong>
<a class="filter-link" href="javascript:void(0)" onclick="toggleFilter()">[ change ]</a>
</mt:if>
</mt:if>
</div>
<div id="filter-select" class="page-title" style="display: none">
Show only actions where
<select id="filter-col" name="filter" onchange="setFilterCol(this.options[this.selectedIndex].value); enableFilterButton(this)">
<!-- option value="stream">stream</option -->
<option value="service">service</option>
<option value="visible">visibility</option>
</select>
is
<span id="filter-visible">
<select id="visible-val" name="filter_val" onchange="enableFilterButton()">
<option value="hide">hidden</option>
<option value="show">shown</option>
</select>
</span>
<span id="filter-service">
<select id="service-val" name="filter_val" onchange="enableFilterButton()">
<mt:loop name="services">
<option value="<mt:var name="service_id">"><mt:var name="service_name"></option>
</mt:loop>
</select>
</span>
<span class="buttons">
<a href="javascript:void(0)"
id="filter-button"
onclick="return execFilter(getByID('filter-select-form'))"
type="submit"
>Filter</a>
<a href="javascript:void(0)"
onclick="toggleFilter(); return false"
type="submit"
>Cancel</a>
</span>
</div>
</div>
</form>
</div>
</div>
<mtapp:listing type="profileevent" default="<__trans phrase="No events could be found.">" empty_message="<__trans phrase="No events could be found.">">
<mt:if name="__first__">
<thead>
<tr>
<th class="cb"><input type="checkbox" id="select-all-checkbox" name="id-head" value="all" class="select" /></th>
<th class="status">
<img src="<mt:var name="static_uri">images/status_icons/invert-flag.gif" alt="<__trans phrase="Status">" title="<__trans phrase="Status">" width="9" height="9" />
</th>
<th class="event"><__trans phrase="Event"></th>
<th class="service"><span class="service-icon"><__trans phrase="Service"></span></th>
<th class="date"><__trans phrase="Created"></th>
<th class="view"><__trans phrase="View"></th>
</tr>
</thead>
<tbody>
</mt:if>
<tr class="<mt:if name="__odd__">odd<mt:else>even</mt:if>">
<td class="cb">
<input type="checkbox" name="id" value="<mt:var name="id">" class="select" />
</td>
<td class="status si status-<mt:if name="visible">publish<mt:else>pending</mt:if>">
<img src="<mt:var name="static_uri">images/spacer.gif" width="13" height="9" alt="<mt:if name="visible"><__trans phrase="Shown"><mt:else><__trans phrase="Hidden"></mt:if>" />
</td>
<td class="event">
<mt:var name="as_html" remove_html="1">
</td>
<td class="service">
<span class="service-icon service-<mt:var name="type" escape="html">"><mt:var name="service" escape="html"></span>
</td>
<td class="date">
<span title="<mt:var name="created_on_time_formatted">">
<mt:if name="dates_relative">
<mt:var name="created_on_relative">
<mt:else>
<mt:var name="created_on_formatted">
</mt:if>
</span>
</td>
<td class="view si status-view">
<mt:if name="url">
<a href="<mt:var name="url" escape="html">" target="<__trans phrase="_external_link_target">" title="<__trans phrase="View action link">"><img src="<mt:var name="static_uri">images/spacer.gif" alt="<__trans phrase="View action link">" width="13" height="9" /></a>
<mt:else>
 
</mt:if>
</td>
</tr>
</mtapp:listing>
<mt:include name="include/footer.tmpl">
diff --git a/plugins/ActionStreams/tmpl/other_profiles.tmpl b/plugins/ActionStreams/tmpl/other_profiles.tmpl
index af50e88..b969c59 100644
--- a/plugins/ActionStreams/tmpl/other_profiles.tmpl
+++ b/plugins/ActionStreams/tmpl/other_profiles.tmpl
@@ -1,129 +1,129 @@
<mt:setvar name="edit_author" value="1">
<mt:setvar name="other_profiles" value="1">
-<mt:setvarblock name="page_title"><__trans phrase="Other Profiles"></mt:setvarblock>
+<mt:setvarblock name="page_title"><__trans phrase="Other Profiles for [_1]" params="<mt:Var name="edit_author_name">"></mt:setvarblock>
<mt:setvarblock name="html_head" append="1">
<link rel="stylesheet" type="text/css" href="<mt:var name="static_uri">plugins/ActionStreams/css/action-streams.css" />
<style type="text/css">
.content-nav #main-content .msg { margin-left: 0px; }
#main-content {
padding-top:5px;
}
<mt:loop name="service_styles">
.service-<mt:var name="service_type"> { background-image: url(<mt:var name="service_icon">); }
</mt:loop>
</style>
<script type="text/javascript">
<!--
function verifyDelete( delete_item ){
conf = confirm( "Are you sure you want to delete " + delete_item + "?" );
if ( conf ) {
return true;
}
return false;
}
var tableSelect;
function init() {
// set up table select awesomeness
tableSelect = new TC.TableSelect("profile-listing-table");
tableSelect.rowSelect = true;
}
TC.attachLoadEvent(init);
// -->
</script>
</mt:setvarblock>
<mt:setvarblock name="system_msg">
<mt:if name="added">
<mtapp:statusmsg
id="added"
class="success">
<__trans phrase="The selected profile was added.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="removed">
<mtapp:statusmsg
id="removed"
class="success">
<__trans phrase="The selected profiles were removed.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="updated">
<mtapp:statusmsg
id="updated"
class="success">
<__trans phrase="The selected profiles were scanned for updates.">
</mtapp:statusmsg>
</mt:if>
<mt:if name="edited">
<mtapp:statusmsg
id="edited"
class="success">
<__trans phrase="The changes to the profile have been saved.">
</mtapp:statusmsg>
</mt:if>
</mt:setvarblock>
<mt:setvarblock name="content_nav">
<mt:include name="include/users_content_nav.tmpl">
</mt:setvarblock>
<mt:setvarblock name="content_header">
<ul class="action-link-list">
<li>
<a href="javascript:void(0)" onclick="return openDialog(this.form, 'dialog_add_profile', 'author_id=<mt:var name="edit_author_id">&return_args=<mt:var name="return_args" escape="url">%26author_id=<mt:var name="edit_author_id">')" class="icon-left icon-create"><__trans phrase="Add Profile"></a>
</li>
</ul>
</mt:setvarblock>
<mt:setvarblock name="action_buttons">
<a href="javascript:void(0)"
onclick="doRemoveItems(getByID('profile-listing-form'), '<__trans phrase="profile">', '<__trans phrase="profiles">', null, null, { mode: 'remove_other_profile' }); return false"
accesskey="x"
title="<__trans phrase="Delete selected profiles (x)">"
><__trans phrase="Delete"></a>
<a href="javascript:void(0)"
onclick="doForMarkedInThisWindow(getByID('profile-listing-form'), '<__trans phrase="profile">', '<__trans phrase="profiles">', 'id', 'itemset_update_profiles'); return false"
title="<__trans phrase="Scan now for new actions">"
><__trans phrase="Update Now"></a>
</mt:setvarblock>
<mt:var name="position_actions_top" value="1">
<mt:include name="include/header.tmpl">
<mtapp:listing type="profile" loop="profiles" empty_message="No profiles were found." hide_pager="1">
<mt:if __first__>
<thead>
<tr>
<th class="cb"><input type="checkbox" name="id-head" value="all" class="select" /></th>
<th class="service"><span class="service-icon"><__trans phrase="Service"></span></th>
<th class="userid"><__trans phrase="Username"></th>
<th class="view"><__trans phrase="View"></th>
</tr>
</thead>
<tbody>
</mt:if>
<tr class="<mt:if __odd__>odd<mt:else>even</mt:if>">
<td class="cb"><input type="checkbox" name="id" class="select" value="<mt:var name="edit_author_id" escape="html">:<mt:var name="type" escape="html">:<mt:var name="ident" escape="html">" /></td>
<td class="service network"><span class="service-icon service-<mt:var name="type">"><a href="javascript:void(0)" onclick="return openDialog(this.form, 'dialog_edit_profile', 'author_id=<mt:var name="edit_author_id">&profile_type=<mt:var name="type" escape="url">&profile_ident=<mt:var name="ident" escape="url">&return_args=<mt:var name="return_args" escape="url">%26author_id=<mt:var name="edit_author_id">')"><mt:var name="label" escape="html"></a></span></td>
<td class="userid"><mt:var name="ident" escape="html"></td>
<td class="view si status-view">
<a href="<mt:var name="uri" escape="html">" target="<__trans phrase="external_link_target">" title="<__trans phrase="View Profile">"><img src="<mt:var name="static_uri">images/spacer.gif" alt="<__trans phrase="View Profile">" width="13" height="9" /></a>
</td>
</tr>
<mt:if __last__>
</tbody>
</mt:if>
</mtapp:listing>
<mt:include name="include/footer.tmpl">
|
markpasc/mt-plugin-action-streams
|
3940619b74ffd362a1847f0041513ca3898818b9
|
Include user's other profiles in ASTest output BugzID: 86958
|
diff --git a/plugins/ASTest/astest.pl b/plugins/ASTest/astest.pl
index 1c3d8ad..1e5ce3a 100644
--- a/plugins/ASTest/astest.pl
+++ b/plugins/ASTest/astest.pl
@@ -1,77 +1,81 @@
package ASTest::Plugin;
use strict;
use warnings;
use base qw( MT::Plugin );
my $plugin = __PACKAGE__->new({
name => 'ASTest',
id => 'ASTest',
key => 'ASTest',
description => 'Reports general information to try to debug Action Streams',
author_name => 'Mark Paschal',
});
MT->add_plugin($plugin);
sub init_registry {
my $plugin = shift;
$plugin->registry({
applications => {
cms => {
methods => {
astest => \&astest,
},
},
},
callbacks => {
'MT::App::CMS::init_request' => sub {
return if MT->app->mode ne 'dialog_add_profile';
MT->log('ASTest: return args at init_request time are: ' . MT->app->{return_args});
},
'template_param.dialog_add_profile' => sub {
my ($cb, $mt, $param, $tmpl) = @_;
MT->log('ASTest: networks param to dialog_add_profile is ' . $param->{networks});
MT->log('ASTest: return_args at dialog_add_profile time is ' . MT->app->{return_args});
my $profserv = MT->app->registry('profile_services') || {};
MT->log('ASTest: profile_services at dialog_add_profile time (' . scalar(keys %$profserv) . ') include: ' . join(q{ }, keys %$profserv));
},
},
});
}
sub astest {
my $app = shift;
require Storable;
local $Storable::forgive_me = 1;
my $c = {
perl => {
version => $],
include_paths => [ @INC ],
},
registry => Storable::dclone({
profile_services => $app->registry('profile_services'),
action_streams => $app->registry('action_streams'),
}),
mt => {
version => $MT::VERSION,
schema => $MT::SCHEMA_VERSION,
plugins => Storable::dclone( \%MT::Plugins ),
},
+ user => {
+ profiles => $app->user->other_profiles,
+ },
+
};
require Data::Dumper;
local $Data::Dumper::Sortkeys = 1;
my $param = { astest => Data::Dumper::Dumper($c) };
$app->build_page($plugin->load_tmpl('astest.tmpl'), $param);
}
1;
|
markpasc/mt-plugin-action-streams
|
21577a6aa3b5a62b4cd8825ce82b254541d71866
|
Sort items of OtherProfiles tag by service name, not service id BugzID: 86958
|
diff --git a/plugins/ActionStreams/lib/ActionStreams/Tags.pm b/plugins/ActionStreams/lib/ActionStreams/Tags.pm
index 418dace..88c0ace 100644
--- a/plugins/ActionStreams/lib/ActionStreams/Tags.pm
+++ b/plugins/ActionStreams/lib/ActionStreams/Tags.pm
@@ -1,464 +1,467 @@
package ActionStreams::Tags;
use strict;
use MT::Util qw( offset_time_list epoch2ts ts2epoch );
use ActionStreams::Plugin;
sub stream_action {
my ($ctx, $args, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamAction in a non-action-stream context!");
return $event->as_html(
defined $args->{name} ? (name => $args->{name}) : ()
);
}
sub stream_action_id {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionURL in a non-action-stream context!");
return $event->id || '';
}
sub stream_action_var {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionVar in a non-action-stream context!");
my $var = $arg->{var} || $arg->{name}
or return $ctx->error("Used StreamActionVar without a 'name' attribute!");
return $ctx->error("Use StreamActionVar to retrieve invalid variable $var from event of type " . ref $event)
if !$event->can($var) && !$event->has_column($var);
return $event->$var();
}
sub stream_action_date {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionDate in a non-action-stream context!");
my $c_on = $event->created_on;
local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $c_on) )
if $c_on;
return $ctx->_hdlr_date($arg);
}
sub stream_action_modified_date {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionModifiedDate in a non-action-stream context!");
my $m_on = $event->modified_on || $event->created_on;
local $arg->{ts} = epoch2ts( $ctx->stash('blog'), ts2epoch(undef, $m_on) )
if $m_on;
return $ctx->_hdlr_date($arg);
}
sub stream_action_title {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionTitle in a non-action-stream context!");
return $event->title || '';
}
sub stream_action_url {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionURL in a non-action-stream context!");
return $event->url || '';
}
sub stream_action_thumbnail_url {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionThumbnailURL in a non-action-stream context!");
return $event->thumbnail || '';
}
sub stream_action_via {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionVia in a non-action-stream context!");
return $event->via || q{};
}
sub other_profile_var {
my( $ctx, $args ) = @_;
my $profile = $ctx->stash( 'other_profile' )
or return $ctx->error( 'No profile defined in ProfileVar' );
my $var = $args->{name} || 'uri';
return defined $profile->{ $var } ? $profile->{ $var } : '';
}
sub _author_ids_for_args {
my ($ctx, $args, $cond) = @_;
my @author_ids;
if (my $ids = $args->{author_ids} || $args->{author_id}) {
@author_ids = split /\s*,\s*/, $ids;
}
elsif (my $disp_names = $args->{display_names} || $args->{display_name}) {
my @names = split /\s*,\s*/, $disp_names;
my @authors = MT->model('author')->load({ nickname => \@names });
@author_ids = map { $_->id } @authors;
}
elsif (my $names = $args->{author} || $args->{authors}) {
# If arg is the special string 'all', then include all authors by returning undef instead of an empty array.
return if $names =~ m{ \A\s* all \s*\z }xmsi;
my @names = split /\s*,\s*/, $names;
my @authors = MT->model('author')->load({ name => \@names });
@author_ids = map { $_->id } @authors;
}
elsif (my $author = $ctx->stash('author')) {
@author_ids = ( $author->id );
}
elsif (my $blog = $ctx->stash('blog')) {
my @authors = MT->model('author')->load({
status => 1, # enabled
}, {
join => MT->model('permission')->join_on('author_id',
{ blog_id => $blog->id }, { unique => 1 }),
});
@author_ids = map { $_->[0]->id }
grep { $_->[1]->can_administer_blog || $_->[1]->can_create_post }
map { [ $_, $_->permissions($blog->id) ] }
@authors;
}
return \@author_ids;
}
sub action_streams {
my ($ctx, $args, $cond) = @_;
my %terms = (
class => '*',
visible => 1,
);
my $author_id = _author_ids_for_args(@_);
$terms{author_id} = $author_id if defined $author_id;
my %args = (
sort => ($args->{sort_by} || 'created_on'),
direction => ($args->{direction} || 'descend'),
);
my $app = MT->app;
undef $app unless $app->isa('MT::App');
if (my $limit = $args->{limit} || $args->{lastn}) {
$args{limit} = $limit eq 'auto' ? ( $app ? $app->param('limit') : 20 ) : $limit;
}
elsif (my $days = $args->{days}) {
my @ago = offset_time_list(time - 3600 * 24 * $days,
$ctx->stash('blog'));
my $ago = sprintf "%04d%02d%02d%02d%02d%02d",
$ago[5]+1900, $ago[4]+1, @ago[3,2,1,0];
$terms{created_on} = [ $ago ];
$args{range_incl}{created_on} = 1;
}
else {
$args{limit} = 20;
}
if (my $offset = $args->{offset}) {
if ($offset eq 'auto') {
$args{offset} = $app->param('offset')
if $app && $app->param('offset') > 0;
}
elsif ($offset =~ m/^\d+$/) {
$args{offset} = $offset;
}
}
my ($service, $stream) = @$args{qw( service stream )};
if ($service && $stream) {
$terms{class} = join q{_}, $service, $stream;
}
elsif ($service) {
$terms{class} = $service . '_%';
$args{like} = { class => 1 };
}
elsif ($stream) {
$terms{class} = '%_' . $stream;
$args{like} = { class => 1 };
}
# Make sure all classes are loaded.
require ActionStreams::Event;
for my $service (keys %{ MT->instance->registry('action_streams') || {} }) {
ActionStreams::Event->classes_for_type($service);
}
my @events = ActionStreams::Event->search(\%terms, \%args);
return $ctx->_hdlr_pass_tokens_else($args, $cond)
if !@events;
if ($args{sort} eq 'created_on') {
@events = sort { $b->created_on cmp $a->created_on || $b->id <=> $a->id } @events;
@events = reverse @events
if $args{direction} ne 'descend';
}
local $ctx->{__stash}{remaining_stream_actions} = \@events;
my $res = '';
my ($count, $total) = (0, scalar @events);
my $day_date = '';
EVENT: while (my $event = shift @events) {
my $new_day_date = _event_day($ctx, $event);
local $cond->{DateHeader} = $day_date ne $new_day_date ? 1 : 0;
local $cond->{DateFooter} = !@events ? 1
: $new_day_date ne _event_day($ctx, $events[0]) ? 1
: 0
;
$day_date = $new_day_date;
$count++;
defined (my $out = _build_about_event(
$ctx, $args, $cond,
event => $event,
count => $count,
total => $total,
)) or return;
$res .= $out;
}
return $res;
}
sub _build_about_event {
my ($ctx, $arg, $cond, %param) = @_;
my ($event, $count, $total) = @param{qw( event count total )};
local $ctx->{__stash}{stream_action} = $event;
my $author = $event->author;
local $ctx->{__stash}{author} = $event->author;
my $type = $event->class_type;
my ($service, $stream_id) = split /_/, $type, 2;
my $profile = $author->other_profiles($service);
next EVENT if !$profile;
local $ctx->{__stash}{other_profile} = $profile;
my $vars = $ctx->{__stash}{vars} ||= {};
local $vars->{action_type} = $type;
local $vars->{service_type} = $service;
local $vars->{stream_type} = $stream_id;
local $vars->{__first__} = $count == 1;
local $vars->{__last__} = $count == $total;
local $vars->{__odd__} = ($count % 2) == 1;
local $vars->{__even__} = ($count % 2) == 0;
local $vars->{__counter__} = $count;
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
defined(my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error($builder->errstr);
return $out;
}
sub stream_action_rollup {
my ($ctx, $arg, $cond) = @_;
my $event = $ctx->stash('stream_action')
or return $ctx->error("Used StreamActionRollup in a non-action-stream context!");
my $nexts = $ctx->stash('remaining_stream_actions');
return $ctx->else($arg, $cond)
if !$nexts || !@$nexts;
my $by_spec = $arg->{by} || 'date,action';
my %by = map { $_ => 1 } split /\s*,\s*/, $by_spec;
my $event_date = _event_day($ctx, $event);
my $event_class = $event->class;
my ($event_service, $event_stream) = split /_/, $event_class, 2;
my @rollup_events = ($event);
EVENT: while (@$nexts) {
my $next = $nexts->[0];
last EVENT if $by{date} && $event_date ne _event_day($ctx, $next);
last EVENT if $by{action} && $event_class ne $next->class;
last EVENT if $by{stream} && $next->class !~ m{ _ \Q$event_stream\E \z }xms;
last EVENT if $by{service} && $next->class !~ m{ \A \Q$event_service\E _ }xms;
# Eligible to roll up! Remove it from the remaining actions.
push @rollup_events, shift @$nexts;
}
return $ctx->else($arg, $cond)
if 1 >= scalar @rollup_events;
my $res;
my $count = 0;
for my $rup_event (@rollup_events) {
$count++;
defined (my $out = _build_about_event(
$ctx, $arg, $cond,
event => $rup_event,
count => $count,
total => scalar @rollup_events,
)) or return;
$res .= $arg->{glue} if $arg->{glue} && $count > 1;
$res .= $out;
}
return $res;
}
sub _event_day {
my ($ctx, $event) = @_;
return substr(epoch2ts($ctx->stash('blog'), ts2epoch(undef, $event->created_on)), 0, 8);
}
sub stream_action_tags {
my ($ctx, $args, $cond) = @_;
require MT::Entry;
my $event = $ctx->stash('stream_action');
return '' unless $event;
my $glue = $args->{glue} || '';
local $ctx->{__stash}{tag_max_count} = undef;
local $ctx->{__stash}{tag_min_count} = undef;
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
my $res = '';
my $tags = $event->get_tag_objects;
for my $tag (@$tags) {
next if $tag->is_private && !$args->{include_private};
local $ctx->{__stash}{Tag} = $tag;
local $ctx->{__stash}{tag_count} = undef;
local $ctx->{__stash}{tag_event_count} = undef; # ?
defined(my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error( $builder->errstr );
$res .= $glue if $res ne '';
$res .= $out;
}
$res;
}
sub other_profiles {
my( $ctx, $args, $cond ) = @_;
my $author_ids = _author_ids_for_args(@_);
my $author_id = shift @$author_ids
or return $ctx->error('No author specified for OtherProfiles');
my $user = MT->model('author')->load($author_id)
or return $ctx->error(MT->trans('No user [_1]', $author_id));
- my @profiles = sort { lc $a->{type} cmp lc $b->{type} }
- @{ $user->other_profiles() };
+ my @profiles = @{ $user->other_profiles() };
my $services = MT->app->registry('profile_services');
if (my $filter_type = $args->{type}) {
my $filter_except = $filter_type =~ s{ \A NOT \s+ }{}xmsi ? 1 : 0;
@profiles = grep {
my $profile = $_;
my $profile_type = $profile->{type};
my $service_type = ($services->{$profile_type} || {})->{service_type} || q{};
$filter_except ? $service_type ne $filter_type : $service_type eq $filter_type;
} @profiles;
}
+ @profiles = map { $_->[1] }
+ sort { $a->[0] cmp $b->[0] }
+ map { [ lc (($services->{ $_->{type} } || {})->{name} || q{}), $_ ] }
+ @profiles;
my $populate_icon = sub {
my ($item, $row) = @_;
my $type = $item->{type};
$row->{vars}{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $services->{$type});
};
return list(
context => $ctx,
arguments => $args,
conditions => $cond,
items => \@profiles,
stash_key => 'other_profile',
code => $populate_icon,
);
}
sub list {
my %param = @_;
my ($ctx, $args, $cond) = @param{qw( context arguments conditions )};
my ($items, $stash_key, $code) = @param{qw( items stash_key code )};
my $builder = $ctx->stash('builder');
my $tokens = $ctx->stash('tokens');
my $res = q{};
my $glue = $args->{glue};
$glue = '' unless defined $glue;
my $vars = ($ctx->{__stash}{vars} ||= {});
my ($count, $total) = (0, scalar @$items);
for my $item (@$items) {
local $ctx->{__stash}->{$stash_key} = $item;
my $row = {};
$code->($item, $row) if $code;
my $lvars = delete $row->{vars} if exists $row->{vars};
local @$vars{keys %$lvars} = values %$lvars
if $lvars;
local @{ $ctx->{__stash} }{keys %$row} = values %$row;
$count++;
my %loop_vars = (
__first__ => $count == 1,
__last__ => $count == $total,
__odd__ => $count % 2,
__even__ => !($count % 2),
__counter__ => $count,
);
local @$vars{keys %loop_vars} = values %loop_vars;
defined (my $out = $builder->build($ctx, $tokens, $cond))
or return $ctx->error($builder->errstr);
$res .= $glue if ($res ne '') && ($out ne '') && ($glue ne '');
$res .= $out;
}
return $res;
}
sub profile_services {
my( $ctx, $args, $cond ) = @_;
my $app = MT->app;
my $networks = $app->registry('profile_services');
my @network_keys = sort { lc $networks->{$a}->{name} cmp lc $networks->{$b}->{name} }
keys %$networks;
my $out = "";
my $builder = $ctx->stash( 'builder' );
my $tokens = $ctx->stash( 'tokens' );
my $vars = ($ctx->{__stash}{vars} ||= {});
if ($args->{extra}) {
# Skip output completely if it's a "core" service but we want
# extras only.
@network_keys = grep { ! $networks->{$_}->{plugin} || ($networks->{$_}->{plugin}->id ne 'actionstreams') } @network_keys;
}
my ($count, $total) = (0, scalar @network_keys);
for my $type (@network_keys) {
$count++;
my %loop_vars = (
__first__ => $count == 1,
__last__ => $count == $total,
__odd__ => $count % 2,
__even__ => !($count % 2),
__counter__ => $count,
);
local @$vars{keys %loop_vars} = values %loop_vars;
my $ndata = $networks->{$type};
local @$vars{keys %$ndata} = values %$ndata;
local $vars->{label} = $ndata->{name};
local $vars->{type} = $type;
local $vars->{icon_url} = ActionStreams::Plugin->icon_url_for_service($type, $networks->{$type});
local $ctx->{__stash}{profile_service} = $ndata;
$out .= $builder->build( $ctx, $tokens, $cond );
}
return $out;
}
1;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.