GReader分享到人人脚本 2

Posted by Linuxtty on 二月 17, 2010

有时候在GReader阅读的时候想分享点文章到人人,使用GReader的Send-to功能感觉颇麻烦(要不就是俺弄的Send-to设置不好),要登录到分享页,再点击次确定才完成分享。

想到之前 @shellex 猫写的 用GAE同步twitter到人人网状态 的python脚本,是否可以借用来做些修改来实现GReader分享到人人的目的?

于是乎年前几天无聊,兼python都快忘完了,就动手丰衣足食写脚本。首先是RSS解析的库,Google了下,找到了 feedparser 这个RSS解析库,官网也列出了一部分使用方法,可以满足基本需要了。

解析好RSS后剩下的功能和 @shellex 的脚本就差不多了。登录+发送状态。

其实这脚本写了两个版本,先写了个本地的,后面又改成GAE的版本=,=折腾。(一开始就弄个GAE的不就好了嘛-___-#)主要之前也写过一个类似的“登录+发送状态”的机器人,只要把RSS解析弄好就可以使用了,想着偷懒呢。

代码有一块注释没删掉,是写本地版本的时候用的登录代码。貌似在GAE上用不了。不知道是不是urllib2的缘故。Cookie和cookielib还要区分下-_____-!!

脚本同时参考了梦.:如此短暂用GAE同步twitter到人人网状态

脚本后面有过修改,就是先检查最新的分享条目,再登录人人更新,要不每次都登录多少感觉不爽。

下面丢代码:

 #!/usr/bin/env python
#coding=utf8
#
import feedparser
import urllib,urllib2,cookielib
import time
import Cookie
#from setting import app
#GAE Modules
from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
usr = '帐号'
passwd = '密码'
source = '[GReader分享] '
greader_url = "http://www.google.com/reader/public/atom/user%2F10398641251604775002%2Fstate%2Fcom.google%2Fbroadcast"
cookie_buf = Cookie.SimpleCookie();

class LastItemRecord(db.Model):
    id = db.StringProperty(multiline=True)
def make_cookie_header(cookie):
    ret = ''
    for v in cookie.values():
        ret += '%s=%s;' % (v.key, v.value)
    return ret
def do_redirect(url, cookie):
    result = urlfetch.fetch(
    url=url,
    headers={
    'Cookie':make_cookie_header(cookie),
    'Content-Type': 'application/x-www-form-urlencoded',
    'user-agent':'Mozilla/5.0 (Linux; U; Linux i686; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.4.2.80 Safari/525.13',},
    method=urlfetch.GET,
    follow_redirects = False,
    )
    return result
#短链接,is.gd/
def shorturl(url):
    surl = "http://is.gd/api.php?longurl=%s" %(url)
    slink = urlfetch.fetch(
    url=surl,
    method=urlfetch.GET,
    )
    result = slink.content
    return result
#格式化
def format(title,link):
    if len(link) < 60:
        status = u"[GReader分享] "+title+" "+shorturl(link)
    else:
        status = u"[GReader分享] "+title+" "+link
        #statu = status.encode('utf8')
    return status

def send_status(status,cookie):
    status_url = 'http://status.renren.com/doing/update.do'
    status_data = urllib.urlencode(
    {
    'c':status,
    'raw':status,
    'isAtHome':0,
    })
    result = urlfetch.fetch(
    url=status_url,
    headers={
        'Cookie':make_cookie_header(cookie),
        'Content-Type': 'application/x-www-form-urlencoded',
        'user-agent':'Mozilla/5.0 (Linux; U; Linux i686; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.4.2.80 Safari/525.13',
        'Referer': 'http://status.renren.com/ajaxproxy.htm'
    },
    method=urlfetch.POST,
    payload=status_data,
    )
    return 0
#def login2renren(usr,passwd):
#    verify_url = 'http://passport.renren.com/PLogin.do'
#    cookie = cookielib.CookieJar()
#    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
#    urllib2.install_opener(opener)
#    verify_data = urllib.urlencode(
#        {
#            'domain':’renren.com’,
#            'email':usr,
#            'password':passwd,
#            'origURL':’http://home.renren.com/Home.do’,
#        }
#    )
#    signin = opener.open(verify_url,verify_data)
#    print 'login'
def login2renren(usr,passwd):
    verify_url = 'http://passport.renren.com/PLogin.do'
    verify_data= urllib.urlencode(
    {
        'domain':'renren.com',
        'email':  usr,
        'password': passwd,
        'origURL':'http://home.renren.com/Home.do',
    })
    result = urlfetch.fetch(
    url=verify_url,
    headers={
        'Cookie':make_cookie_header(cookie_buf),
        'Content-Type': 'application/x-www-form-urlencoded',
        'user-agent':'Mozilla/5.0 (Linux; U; Linux i686; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.4.2.80 Safari/525.13',},
    method=urlfetch.POST,
    payload=verify_data,
    follow_redirects = False,
    )
    return result

class sync(webapp.RequestHandler):
    def get(self):
        global cookie_buf
        rss = feedparser.parse(greader_url)
        entries = rss.entries[:]
        i=0
        last_item_record = None
        #print entries[0].id
        last_item_records = db.GqlQuery('SELECT * FROM LastItemRecord')
        if last_item_records.count() == 0:
            last_item_record = LastItemRecord()
            last_item_record.put()
            last_item_record = last_item_records[0]
        if entries[0].id.encode('utf8')!=last_item_record.id:
        #login to renren
            result = login2renren(usr,passwd)
            cookie_buf = Cookie.SimpleCookie(result.headers.get('set-cookie', ''))
            callback_url = result.headers.get('location','xx');
            result = do_redirect(callback_url, cookie_buf)
            cookie_buf = Cookie.SimpleCookie(result.headers.get('set-cookie', ''))
            while i!=5 and entries[i].id.encode('utf8')!=last_item_record.id:
                status = format(entries[i].title,entries[i].link)
                send_status(status.encode('utf8'),cookie_buf)
                time.sleep(3)
                i+=1
                last_item_record.id = entries[0].id
                db.put(last_item_record)
application = webapp.WSGIApplication([('/md5sum', sync)],debug=True)

if __name__ == "__main__":
    run_wsgi_app(application)

app.yaml 限制只有管理员才能访问/md5sum

application: read2rr
version: 5
runtime: python
api_version: 1

handlers:
- url: /md5sum
script: read2rr.py
login: admin

cron.yaml 每15分钟触发一次。

cron:
- description: read2rr
url: /md5sum
schedule: every 15 minutes
Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. WindyWinter Mozilla Firefox Windows 星期四, 18 二 2010 00:37:07 UTC

    Google Reader Share的Feed支持Pubhubsubbub协议,如果你参考的是《基于PubSubHubbub的Feed实时同步到Twitter服务》,就不用设置cron了,而且是实时同步。

    [回复]

  2. flyingkk Mozilla Firefox Windows 星期六, 20 三 2010 18:21:38 UTC

    贴上来的代码没作缩进,没学过python的搞不定……

    [回复]

Comments