Commit 150a1abe authored by mmn's avatar mmn

MSN probably doesn't work, and we don't like it anyway

parent 7028c16d
<?php
/**
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2009, StatusNet, Inc.
*
* Send and receive notices using the MSN network
*
* PHP version 5
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category IM
* @package StatusNet
* @author Luke Fitzgerald <lw.fitzgerald@googlemail.com>
* @copyright 2010 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
* @link http://status.net/
*/
if (!defined('STATUSNET')) {
// This check helps protect against security problems;
// your code file can't be executed directly from the web.
exit(1);
}
// We bundle the phpmsnclass library...
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/phpmsnclass');
/**
* Plugin for MSN
*
* @category Plugin
* @package StatusNet
* @author Luke Fitzgerald <lw.fitzgerald@googlemail.com>
* @copyright 2010 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
* @link http://status.net/
*/
class MsnPlugin extends ImPlugin {
public $user = null;
public $password = null;
public $nickname = null;
public $transport = 'msn';
/**
* Get the internationalized/translated display name of this IM service
*
* @return string Name of service
*/
public function getDisplayName() {
// TRANS: Display name of the MSN instant messaging service.
return _m('MSN');
}
/**
* Normalize a screenname for comparison
*
* @param string $screenname screenname to normalize
* @return string an equivalent screenname in normalized form
*/
public function normalize($screenname) {
$screenname = str_replace(" ","", $screenname);
return strtolower($screenname);
}
/**
* Get the screenname of the daemon that sends and receives messages
*
* @return string Screenname
*/
public function daemonScreenname() {
return $this->user;
}
/**
* Validate (ensure the validity of) a screenname
*
* @param string $screenname screenname to validate
* @return boolean
*/
public function validate($screenname) {
return Validate::email($screenname, common_config('email', 'check_domain'));
}
/**
* Load related modules when needed
*
* @param string $cls Name of the class to be loaded
* @return boolean hook value; true means continue processing, false means stop.
*/
public function onAutoload($cls) {
$dir = dirname(__FILE__);
switch ($cls) {
case 'MSN':
require_once(INSTALLDIR.'/plugins/Msn/extlib/phpmsnclass/msn.class.php');
return false;
}
return parent::onAutoload($cls);
}
/*
* Start manager on daemon start
*
* @return boolean
*/
public function onStartImDaemonIoManagers(&$classes) {
parent::onStartImDaemonIoManagers($classes);
$classes[] = new MsnManager($this); // handles sending/receiving
return true;
}
/**
* Ensure the database table is present
*
*/
public function onCheckSchema() {
$schema = Schema::get();
// For storing messages while sessions become ready
$schema->ensureTable('msn_waiting_message', Msn_waiting_message::schemaGet());
return true;
}
/**
* Get a microid URI for the given screenname
*
* @param string $screenname
* @return string microid URI
*/
public function microiduri($screenname) {
return 'msnim:' . $screenname;
}
/**
* Send a message to a given screenname
*
* @param string $screenname Screenname to send to
* @param string $body Text to send
* @return boolean success value
*/
public function sendMessage($screenname, $body) {
$this->enqueueOutgoingRaw(array('to' => $screenname, 'message' => $body));
return true;
}
/**
* Accept a queued input message.
*
* @param array $data Data
* @return true if processing completed, false if message should be reprocessed
*/
public function receiveRawMessage($data) {
$this->handleIncoming($data['sender'], $data['message']);
return true;
}
/**
* Initialize plugin
*
* @return boolean
*/
public function initialize() {
if (!isset($this->user)) {
// TRANS: Exception thrown when configuration for the MSN plugin is incomplete.
throw new Exception(_m('Must specify a user.'));
}
if (!isset($this->password)) {
// TRANS: Exception thrown when configuration for the MSN plugin is incomplete.
throw new Exception(_m('Must specify a password.'));
}
if (!isset($this->nickname)) {
// TRANS: Exception thrown when configuration for the MSN plugin is incomplete.
throw new Exception(_m('Must specify a nickname.'));
}
return true;
}
/**
* Get plugin information
*
* @param array $versions array to insert information into
* @return void
*/
public function onPluginVersion(&$versions) {
$versions[] = array(
'name' => 'MSN',
'version' => GNUSOCIAL_VERSION,
'author' => 'Luke Fitzgerald',
'homepage' => 'http://status.net/wiki/Plugin:MSN',
'rawdescription' =>
// TRANS: Plugin description.
_m('The MSN plugin allows users to send and receive notices over the MSN network.')
);
return true;
}
}
The MSN plugin allows users to send and receive notices over the MSN network.
Required PHP extensions:
curl pcre mhash mcrypt bcmath
Installation
============
add "addPlugin('msn',
array('setting'=>'value', 'setting2'=>'value2', ...);"
to the bottom of your config.php
scripts/imdaemon.php included with StatusNet must be running. It will be started
by the plugin along with their other daemons when you run
scripts/startdaemons.sh. See the StatusNet README for more about queuing and
daemons.
Settings
========
user*: username (screenname) to use when logging into MSN
password*: password for that user
nickname*: nickname for the bot
* required
default values are in (parenthesis)
Example
=======
addPlugin('msn', array(
'user' => '...',
'password' => '...',
'nickname' => '...'
));
<?php
/**
* Table Definition for msn_waiting_message
*/
require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
class Msn_waiting_message extends Managed_DataObject {
public $__table = 'msn_waiting_message'; // table name
public $id; // int primary_key not_null auto_increment
public $screenname; // varchar(255) not_null
public $message; // text not_null
public $claimed; // datetime()
public $created; // datetime() not_null
public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
public static function schemaDef()
{
return array(
'fields' => array(
'id' => array('type' => 'serial', 'not null' => true, 'description' => 'Unique ID for entry'),
'screenname' => array('type' => 'varchar', 'length' => 255, 'description' => 'from screenname'),
'message' => array('type' => 'text', 'not null' => true, 'description' => 'MSN message text'),
'claimed' => array('type' => 'datetime', 'description' => 'date this irc message was claimed'),
'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
),
'primary key' => array('id'),
'indexes' => array(
'msn_waiting_message_prioritise_idx' => array('screenname'),
),
);
}
/**
* @param string $screenname screenname or array of screennames to pull from
* If not specified, checks all queues in the system.
*/
public static function top($screenname = null) {
$wm = new Msn_waiting_message();
if ($screenname) {
if (is_array($screenname)) {
// @fixme use safer escaping
$list = implode("','", array_map('addslashes', $screenname));
$wm->whereAdd("screenname in ('$list')");
} else {
$wm->screenname = $screenname;
}
}
$wm->orderBy('created');
$wm->whereAdd('claimed is null');
$wm->limit(1);
$cnt = $wm->find(true);
if ($cnt) {
// XXX: potential race condition
// can we force it to only update if claimed is still null
// (or old)?
common_log(LOG_INFO, 'claiming msn waiting message id = ' . $wm->id);
$orig = clone($wm);
$wm->claimed = common_sql_now();
$result = $wm->update($orig);
if ($result) {
common_log(LOG_INFO, 'claim succeeded.');
return $wm;
} else {
common_log(LOG_INFO, 'claim failed.');
}
}
$wm = null;
return null;
}
/**
* Release a claimed item.
*/
public function releaseClaim() {
// DB_DataObject doesn't let us save nulls right now
$sql = sprintf("UPDATE msn_waiting_message SET claimed=NULL WHERE id=%d", $this->id);
$this->query($sql);
$this->claimed = null;
$this->encache();
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
#!/usr/bin/php
<?php
global $msn;
function ChildSignalFunction($signal)
{
global $msn;
switch($signal)
{
case SIGTRAP:
case SIGTERM:
case SIGHUP:
if(is_object($msn)) $msn->End();
return;
}
}
// network:
// 1: WLM/MSN
// 2: LCS
// 4: Mobile Phones
// 32: Yahoo!
function getNetworkName($network)
{
switch ($network)
{
case 1:
return 'WLM/MSN';
case 2:
return 'LCS';
case 4:
return 'Mobile Phones';
case 32:
return 'Yahoo!';
}
return "Unknown ($network)";
}
require_once('config.php');
include_once('msn.class.php');
$msn = new MSN(array(
'user' => 'xxx@hotmail.com',
'password' => 'mypassword',
'alias' => 'myalias',
'psm' => 'psm',
// 'PhotoSticker' => 'msntitle.jpg',
'debug'=> true,
/* 'Emotions' => array(
'aaa' => 'emotion.gif'
),*/
));
$fp=fopen(MSN_CLASS_LOG_DIR.DIRECTORY_SEPARATOR.'msnbot.pid', 'wt');
if($fp)
{
fputs($fp,posix_getpid());
fclose($fp);
}
declare(ticks = 1);
$msn->Run();
$msn->log_message("done!");
@unlink(dirname($_SERVER['argv'][0]).DIRECTORY_SEPARATOR.'log'.DIRECTORY_SEPARATOR.'msnbot.pid');
<?php
/*
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2008, 2009, StatusNet, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
/**
* MSN background connection manager for MSN-using queue handlers,
* allowing them to send outgoing messages on the right connection.
*
* Input is handled during socket select loop, keepalive pings during idle.
* Any incoming messages will be handled.
*
* In a multi-site queuedaemon.php run, one connection will be instantiated
* for each site being handled by the current process that has MSN enabled.
*/
class MsnManager extends ImManager {
public $conn = null;
protected $lastPing = null;
protected $pingInterval;
/**
* Initialise connection to server.
*
* @return boolean true on success
*/
public function start($master) {
if (parent::start($master)) {
$this->requeue_waiting_messages();
$this->connect();
return true;
} else {
return false;
}
}
/**
* Return any open sockets that the run loop should listen
* for input on.
*
* @return array Array of socket resources
*/
public function getSockets() {
$this->connect();
if ($this->conn) {
return $this->conn->getSockets();
} else {
return array();
}
}
/**
* Idle processing for io manager's execution loop.
* Send keepalive pings to server.
*
* @return void
*/
public function idle($timeout = 0) {
if (empty($this->lastPing) || time() - $this->lastPing > $this->pingInterval) {
$this->send_ping();
}
}
/**
* Message pump is triggered on socket input, so we only need an idle()
* call often enough to trigger our outgoing pings.
*/
public function timeout() {
return $this->pingInterval;
}
/**
* Process MSN events that have come in over the wire.
*
* @param resource $socket Socket ready
* @return void
*/
public function handleInput($socket) {
common_log(LOG_DEBUG, 'Servicing the MSN queue.');
$this->stats('msn_process');
$this->conn->receive();
}
/**
* Initiate connection
*
* @return void
*/
public function connect() {
if (!$this->conn) {
$this->conn = new MSN(
array(
'user' => $this->plugin->user,
'password' => $this->plugin->password,
'alias' => $this->plugin->nickname,
// TRANS: MSN bot status message.
'psm' => _m('Send me a message to post a notice'),
'debug' => false
)
);
$this->conn->registerHandler('IMin', array($this, 'handle_msn_message'));
$this->conn->registerHandler('SessionReady', array($this, 'handle_session_ready'));
$this->conn->registerHandler('Pong', array($this, 'update_ping_time'));
$this->conn->registerHandler('ConnectFailed', array($this, 'handle_connect_failed'));
$this->conn->registerHandler('Reconnect', array($this, 'handle_reconnect'));
$this->conn->signon();
$this->lastPing = time();
}
return $this->conn;
}
/**
* Called by the idle process to send a ping
* when necessary
*
* @return void
*/
protected function send_ping() {
$this->connect();
if (!$this->conn) {
return false;
}
$this->conn->sendPing();
$this->lastPing = time();
$this->pingInterval = 50;
return true;
}
/**
* Update the time till the next ping
*
* @param $data Time till next ping
* @return void
*/
public function update_ping_time($data) {
$this->pingInterval = $data;
}
/**
* Called via a callback when a message is received
*
* Passes it back to the queuing system
*
* @param array $data Data
* @return boolean
*/
public function handle_msn_message($data) {
$this->plugin->enqueueIncomingRaw($data);
return true;
}
/**
* Called via a callback when a session becomes ready
*
* @param array $data Data
*/
public function handle_session_ready($data) {
$sessionFailed = false;
$wm = Msn_waiting_message::top($data['to']);
while ($wm != NULL) {
if ($sessionFailed) {
$this->plugin->sendMessage($wm->screenname, $wm->message);
$sessionFailed = true;
} elseif (!$this->conn->sendMessage($wm->screenname, $wm->message, $ignore)) {
$this->plugin->sendMessage($wm->screenname, $wm->message);
}
$wm->delete();
$wm = Msn_waiting_message::top($data['to']);
}
}
/**
* Requeue messages from the waiting table so we try
* to send them again
*
* @return void
*/
protected function requeue_waiting_messages() {
$wm = Msn_waiting_message::top();
while ($wm != NULL) {
$this->plugin->sendMessage($wm->screenname, $wm->message);
$wm->delete();
$wm = Msn_waiting_message::top();
}
}
/**
* Called by callback to log failure during connect
*
* @param string $message error message reported
* @return void
*/
public function handle_connect_failed($message) {
common_log(LOG_NOTICE, 'MSN connect failed, retrying: ' . $message);
}
/**
* Called by callback to log reconnection
*
* @param void $data Not used (there to keep callback happy)
* @return void
*/
public function handle_reconnect($data) {
common_log(LOG_NOTICE, 'MSN reconnecting');
// Requeue messages waiting in the DB
$this->requeue_waiting_messages();
}
/**
* Enters a message into the database for sending via a callback
* when the session is established
*
* @param string $to Intended recipient
* @param string $message Message
*/
protected function enqueue_waiting_message($to, $message) {
$wm = new Msn_waiting_message();
$wm->screenname = $to;
$wm->message = $message;
$wm->created = common_sql_now();
$result = $wm->insert();
if (!$result) {
common_log_db_error($wm, 'INSERT', __FILE__);
// TRANS: Server exception thrown when a message to be sent through MSN cannot be added to the database queue.
throw new ServerException(_m('Database error inserting queue item.'));
}
return true;
}
/**
* Send a message using the daemon
*
* @param $data Message data
* @return boolean true on success
*/
public function send_raw_message($data) {
$this->connect();
if (!$this->conn) {
return false;
}
$waitForSession = false;
if (!$this->conn->sendMessage($data['to'], $data['message'], $waitForSession)) {
if ($waitForSession) {
$this->enqueue_waiting_message($data['to'], $data['message']);
} else {
return false;
}
}
// Sending a command updates the time till next ping
$this->lastPing = time();
$this->pingInterval = 50;
return true;
}
}
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy