Created
September 16, 2011 08:49
-
-
Save naoya/1221598 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
http = require 'http' | |
sys = require 'sys' | |
EventEmitter = require('events').EventEmitter | |
mongodb = require 'mongodb' | |
class Twitter extends EventEmitter | |
constructor: (path, name, pass) -> | |
@path = path | |
@name = name | |
@pass = pass | |
header: -> | |
username = @name | |
password = @pass | |
auth = 'Basic ' + new Buffer(username + ':' + password).toString 'base64' | |
header = Authorization: auth | |
fetch: -> | |
self = this | |
opt = | |
host: 'stream.twitter.com' | |
port: 80 | |
path: @path | |
headers: @.header() | |
method: 'POST' | |
req = http.request opt, (res) -> | |
if res.statusCode isnt 200 | |
console.log res.statusCode | |
buf = '' | |
res.setEncoding 'utf8' | |
res.on 'data', (chunk) -> | |
buf += chunk | |
if buf.match /\r/ | |
try | |
tweet = JSON.parse buf | |
self.emit 'incoming', tweet | |
catch err | |
console.log err | |
buf = '' | |
req.end() | |
class Mongo extends EventEmitter | |
constructor: (dbname) -> | |
@db = new mongodb.Db(dbname, new mongodb.Server("127.0.0.1", 27017, {})) | |
open: (cname) -> | |
self = this | |
@db.open (err, client) -> | |
if err then throw err | |
client.collection cname, (err, collection) -> | |
if err then throw err | |
self.on 'insert', (data) -> | |
collection.insert data, (err, docs) -> | |
if err then throw err | |
# cb docs | |
## main | |
db = new Mongo 'mydb' | |
db.open 'tweet' | |
tw = new Twitter '/1/statuses/filter.json?follow=xxxxxxxxxx', "xxxxxxxx", "xxxxxxxxx" | |
tw.on 'incoming', (tweet) -> | |
console.log tweet.text | |
tw.on 'incoming', (tweet) -> | |
db.emit 'insert', tweet | |
do tw.fetch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment