Skip to content

Instantly share code, notes, and snippets.

@ymnk
Created December 18, 2008 06:36
Show Gist options
  • Select an option

  • Save ymnk/37415 to your computer and use it in GitHub Desktop.

Select an option

Save ymnk/37415 to your computer and use it in GitHub Desktop.
/*
Copyright (c) 2008 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
import java.net.Socket
import java.io._
import scala.concurrent.ops.spawn
class IRCConnector(host:String, port:Int,
username:String, passwd:String,
channel:String) extends Connector{
val sock=new Socket(host, port)
val (in, out) =
(new BufferedReader(new InputStreamReader(sock.getInputStream, "UTF-8")),
sock.getOutputStream)
val crlf=Array(0x0d, 0x0a).map(_.asInstanceOf[Byte])
def write(text:String){
writeRaw("PRIVMSG "+channel+" :"+text)
}
private def writeRaw(msg:String){
val b=try{ msg.getBytes("UTF-8") }
catch{ case e:UnsupportedEncodingException => msg.getBytes }
out.write(b)
out.write(crlf)
out.flush
}
spawn{
def parse(msg:String)={
msg.split(" ", 0) match {
case Array(pr, c, p@_*) if pr.startsWith(":") =>
(Some(pr.substring(1)), c.toUpperCase, p.mkString(" "))
case Array(c, p@_*) => (None, c.toUpperCase, p.mkString(" "))
}
}
def loop{
if(in.ready){
val msg=in.readLine
parse(msg) match {
case (pr, "PRIVMSG", params) => {
val who = pr match{
case Some(pr) => pr.split("!")(0)
case _ => "unknown"
}
val(nick, msg) = params.split(" ", 0) match {
case Array(n) => (n, "")
case Array(n, m@_*) if m(0).startsWith(":") =>
(n, m.mkString(" ").substring(1))
case Array(n, m@_*) => (n, m.mkString(" "))
}
if(nick==channel && msg!=""){
writeToOthers(who+": "+msg)
}
}
case (pr, "PING", params) => {
writeRaw("PONG "+params)
}
case m => println(m)
}
}
else{
try{ Thread.sleep(100)}catch{case e=> }
}
loop
}
loop
}
writeRaw("PASS "+passwd)
writeRaw("NICK "+username)
writeRaw("USER "+username+" 127.0.0.1 * :"+username)
writeRaw("JOIN "+channel)
}
/*
Copyright (c) 2008 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
import scala.collection.mutable.{Set, Map}
abstract class Connector{
def write(text:String)
def writeToOthers(message:String)=MessengerHub.write(this, message)
}
object MessengerHub{
private val lastMessage=Map.empty[Connector, String]
private val connectors=Set.empty[Connector]
def += (c:Connector) { connectors += c; lastMessage += (c -> "") }
def write(ignore:Connector, message:String){
lastMessage.get(ignore) match{
case Some(`message`) =>
case _ => {
lastMessage += (ignore -> message)
connectors.foreach{ c => if(c!=ignore) c.write(message) }
}
}
}
}
/*
Copyright (c) 2008 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/**
* Skype4Java[1] is required to be compiled.
* [1] https://developer.skype.com/wiki/Java_API
*/
import com.skype.{Skype, Chat, ChatMessage, ChatMessageAdapter}
class SkypeChatConnector(chatId:String) extends Connector{
Skype.setDeamon(false)
val Array(chat) = Skype.getAllChats.filter(_.getId.toString==chatId)
var lastSkypeWriteTime:Long = -1
def write(message:String){
lastSkypeWriteTime=System.currentTimeMillis
chat.send(message)
}
val interval:Long = 3*1000
Skype.addChatMessageListener(
new ChatMessageAdapter{
override def chatMessageReceived(m:ChatMessage)=chatMessage(m)
override def chatMessageSent(m:ChatMessage)={
if(System.currentTimeMillis - lastSkypeWriteTime > interval){
chatMessage(m)
}
}
private def chatMessage(m:ChatMessage){
val c=m.getChat
if(chat==c){
val sender = m.getSender
val senderId = m.getSenderId
val senderDisplayName = m.getSenderDisplayName
m.getType.toString match {
case "SAID" => {
val content = m.getContent
writeToOthers(senderDisplayName+": "+content)
}
case "ADDEDMEMBERS" => {
writeToOthers(senderDisplayName+" joined this chat.")
}
case "LEFT" => {
writeToOthers(senderDisplayName+" left this chat.")
}
case _ =>
}
}
}
}
)
}
object ListChats {
def main(arg:Array[String]){
Skype.getAllChats.foreach { c =>
import c._
println(getId+" | "+getWindowTitle)
}
}
}
/*
Copyright (c) 2008 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
object SkypeChatTwitter {
def main(arg:Array[String]){
val chatId = arg(0) // chatid
val (username, passwd) = (arg(1), arg(2)) // Twitter id and password.
MessengerHub += new SkypeChatConnector(chatId)
MessengerHub += new TwitterConnector(username, passwd)
}
}
/*
Copyright (c) 2008 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
object SkypeChatTwitterIRC {
def main(arg:Array[String]){
val chatId = arg(0) // chatid
val (tuser, tpasswd) = (arg(1), arg(2)) // Twitter id and password.
val (host, port,
ircuser, ircpasswd,
channel) = (arg(3), arg(4).toInt, arg(5), arg(6), arg(7))
MessengerHub += new SkypeChatConnector(chatId)
MessengerHub += new TwitterConnector(tuser, tpasswd)
MessengerHub += new IRCConnector(host, port, ircuser, ircpasswd, channel)
}
}
/*
Copyright (c) 2008 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
import java.net.{Authenticator, PasswordAuthentication}
import java.net.{URL, URLEncoder, HttpURLConnection}
import scala.xml.XML
import java.text.SimpleDateFormat
import java.util.Locale
import scala.actors.Actor
import scala.actors.Actor.loop
import scala.concurrent.ops.spawn
class TwitterConnector(username:String, passwd:String) extends Connector{
def write(text:String){
def chop(text:String):String={
text match {
case e if e.length>140 => chop(text.substring(0, text.length-1))
case e => URLEncoder.encode(e, "UTF-8")
}
}
val pattern = "(http://[a-zA-Z0-9%+\\-&=?#./$()!\"$'^~@]+)".r
def tinyURL(s:String) = if(s.startsWith("http://tinyurl")) s else
io.Source.fromURL("http://tinyurl.com/api-create.php?url="+s).mkString("")
def replace(s:String, o:String, n:String) =
s.substring(0, s.indexOf(o))+n+s.substring(s.indexOf(o)+o.length)
def short(s:String)={
var source = s
try{
for(http <- pattern findAllIn source){
source = replace(source, http, tinyURL(http))
}
}
catch{ case e => println(e) }
source
}
val url = "http://twitter.com/statuses/update.xml?status="+chop(short(text))
val urlConn = new URL(url).openConnection.asInstanceOf[HttpURLConnection]
urlConn.setRequestMethod("POST")
urlConn.connect()
urlConn.getResponseCode
}
class FriendsTimeline(username:String) extends Actor{
sealed abstract class MESSAGE
case object GETTIMELINE extends MESSAGE
val url = "http://twitter.com/statuses/replies.xml"
val df = new SimpleDateFormat("EEE MMM dd HH:mm:ss +0000 yyyy", Locale.US)
var lastTime:Long = -1
val interval = 90 * 1000
def act {
this ! GETTIMELINE
loop {
react {
case GETTIMELINE => {
try{ lastTime = timeline(lastTime) }
catch{case e:java.io.IOException => }
ping(interval, GETTIMELINE)
}
}
}
}
private def timeline(_lastTime:Long)={
var lastTime=_lastTime
val urlConn = new URL(url).openConnection.asInstanceOf[HttpURLConnection]
urlConn.connect();
urlConn.getResponseCode
for (s <- XML.load(urlConn.getInputStream) \ "status" reverse ;
created_at = s \ "created_at" text ;
time = df.parse(created_at).getTime if(time>lastTime)) {
lastTime=time
var (text, user_name, screen_name) =
(s \ "text" text,
s \ "user" \ "name" text,
s \ "user" \ "screen_name" text)
if(username!=screen_name &&
text.startsWith("@"+username)){
if(_lastTime != -1){ // At first time, we will skip it.
println(created_at+" ["+user_name+"] "+
text.substring(("@"+username).length).trim)
writeToOthers(user_name+": "+
text.substring(("@"+username).length).trim)
}
}
}
lastTime
}
private def ping(sleep:Long, m:MESSAGE) {
spawn { Thread.sleep(sleep); this ! m }
}
}
private def setAutenticator(u:String, p:String){
Authenticator.setDefault(
new Authenticator {
override def getPasswordAuthentication = {
new PasswordAuthentication(u, p.toCharArray);
}
}
)
}
setAutenticator(username, passwd)
new FriendsTimeline(username).start
}
/*
Copyright (c) 2008 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
object TwitterIRC {
def main(arg:Array[String]){
val (tuser, tpasswd) = (arg(0), arg(1)) // Twitter id and password.
val (host, port,
ircuser, ircpasswd,
channel) = (arg(2), arg(3).toInt, arg(4), arg(5), arg(6))
MessengerHub += new TwitterConnector(tuser, tpasswd)
MessengerHub += new IRCConnector(host, port, ircuser, ircpasswd, channel)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment