Ejemplo n.º 1
0
 def __init__(self, email, pwd):
     # 对密码进行md5 hash
     self.pwd = md5(pwd).hexdigest()
     self.email = email
     self.n = Net()
     self.login()
     self.upload()
     try:
         self.reward()
     except:
         pass
Ejemplo n.º 2
0
    def __init__(self):
        super(QMainWindow, self).__init__()
        self.setupUi(self)

        self.net = Net()
        global ACCESS_TOKEN
        try:
            ACCESS_TOKEN = file('./conf.txt').readlines()[0].split(':')[-1]
        except IndexError:
            pass
        
        self.initUi()
        self.intiConnect()
Ejemplo n.º 3
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(QMainWindow, self).__init__()
        self.setupUi(self)

        self.net = Net()
        global ACCESS_TOKEN
        try:
            ACCESS_TOKEN = file('./conf.txt').readlines()[0].split(':')[-1]
        except IndexError:
            pass
        
        self.initUi()
        self.intiConnect()

    def intiConnect(self):
        self.btn_oauth.clicked.connect(self.oauth)
        self.btn_login.clicked.connect(self.login)
        self.btn_get_profile_info.clicked.connect(self.getProfileInfo)
        self.web_view.urlChanged.connect(self.urlChanged)
        self.btn_get_vistors.clicked.connect(self.getVisitors)

    def initUi(self):
        #self.le_api_key.setText(APIKEY)
        #self.le_secret.setText(SECRET)
        self.web_view.hide()
        self.lb_vip.hide()

    def oauth(self):
        self.web_view.show()
        url = QUrl('%s?client_id=%s&redirect_uri=http://graph.renren.com/oauth/login_success.html&\
response_type=token&display=popup' % (AUTHORIZATION_URI, APIKEY))
        self.web_view.load(url)
        
    def urlChanged(self, url):
        url = unicode(url.toString())
        if url.find('access_token') > 0:
            global ACCESS_TOKEN
            try:
                ACCESS_TOKEN = re.findall(r'access_token=(.*)&', url)[0]
                QMessageBox(
                    QMessageBox.Information,
                    u'授权成功',
                    u'您已成功为此程序授权!',
                    ).exec_()
                self.web_view.hide()
            except IndexError:
                ACCESS_TOKEN = ''
            file('./conf.txt', 'w').write('access_token:%s' % ACCESS_TOKEN)
                
    def login(self):
        info = self.post({'access_token':ACCESS_TOKEN, 
            'method':'users.getInfo', 'v':'1.0', 'format':'JSON'})
        self.lb_name.setText(u'姓名:%s' % info[u'name'])
        self.lb_star.setText(u'是否星级用户:%s' % info[u'star'])
        self.lb_uid.setText(u'uid:%s' % info[u'uid'])
        self.lb_sex.setText(u'性别:%s' % info[u'sex'])
        self.lb_zidou.setText(u'是否vip:%s' % info[u'zidou'])
        tiny, head = QPixmap(), QPixmap()
        head.loadFromData(self.net.get(info[u'headurl']))
        self.lb_head.setPixmap(head)
        tiny.loadFromData(self.net.get(info[u'tinyurl']))
        self.lb_tiny.setPixmap(tiny)
        if info[u'zidou']:
            self.lb_vip.setText(u'vip等级:%s' % info[u'vip'])
            self.lb_vip.show()
        
    def post(self, params):
        '''
        返回一个json格式的字典
        '''
        result = json.loads(self.net.post(API_SERVER, self._getParams(params)))
        if isinstance(result, list):
            return result[0]
        return result
        
    def _getParams(self, params):
        params['sig'] = self._getSig(params)
        return params
    
    def _getSig(self, params):
        return hashlib.md5(''.join(['%s=%s' % (x, params[x]) 
                for x in sorted(params.keys())]) + SECRET).hexdigest()
                
    def getProfileInfo(self):
        info = self.post({'access_token':ACCESS_TOKEN, 'uid':'234069719',
            'method':'users.getProfileInfo', 'v':'1.0', 'format':'JSON', 'fields':'visitors_count,blogs_count,\
albums_count,friends_count,guestbook_count,status_count,content,time'})
        self.lb_name.setText(u'访问者总数:%s' % info[u'visitors_count'])
        self.lb_star.setText(u'日志总数:%s' % info[u'blogs_count'])
        self.lb_uid.setText(u'相册总数:%s' % info[u'albums_count'])
        self.lb_sex.setText(u'好友总数:%s' % info[u'friends_count'])
        self.lb_zidou.setText(u'留言总数:%s' % info[u'guestbook_count'])
        self.lb_vip.setText(u'状态总数:%s' % info[u'status_count'])
        self.lb_vip.show()
        self.lb_head.setText(u'状态内容:%s' % info[u'status'][u'content'])
        self.lb_tiny.setText(u'状态修改的时间:%s' % info[u'status'][u'time'])
        
    def getVisitors(self):#获得某个用户最近来访的列表
        info = ''
        visitors = self.post({'access_token':ACCESS_TOKEN,
            'method':'users.getVisitors', 'v':'1.0', 'format':'JSON'})[u'visitors']
        for visitor in visitors:
            #print visitor[u'name'], visitor[u'time'], visitor[u'uid'], visitor[u'headurl']
            info += '%s, %s, %s, %s\n' % (visitor[u'name'], visitor[u'time'], visitor[u'uid'], visitor[u'headurl'])
        self.lb_tiny.setText(u'最近访问好友列表:\n%s' % info)
class RenRen(object):
    def __init__(self):
        self.params = dict(
            v='1.0',
            format='json',
            call_id=0,
            page_id=PAGE_ID
        )
        self.login_by_cookie()

    def get_access_token(self, code):
        params = dict(
            grant_type='authorization_code',
            client_id=APIKEY,
            redirect_uri=CALLBACK_URL,
            client_secret=SECRET,
            code=code
        )
        return json.loads(n.post(ACCESS_TOKEN_URI, params))

    def refresh(self, refresh_token):
        params = dict(
            grant_type='refresh_token',
            client_id=APIKEY,
            refresh_token=refresh_token,
            client_secret=SECRET
        )
        return json.loads(n.post(ACCESS_TOKEN_URI, params))

    def post_page(self, content, access_token):
        if isinstance(content, unicode):
            content = content.encode('u8')
        params = {}
        params.update(self.params)
        params.update(dict(
            access_token=access_token,
            status=content,
            method='status.set'
        ))
        ret = json.loads(n.post(API_SERVER, params))
        return ret.get('result', 0) == 1

    # 以下代码为非oauth授权用户的操作
    _net = Net()

    def login_by_cookie(self, cookie=None):
        '''刷新cookie用的'''
        import re
        if cookie is None:
            cookie = '在chrome的js控制台,输入document.cookie出来的那个字符串,写在这里,注意前后无双引号'
        try:
            c = 'Cookie', cookie
            if c not in self._net.opener.addheaders:
                self._net.opener.addheaders.append(c)
            self._net.get('http://page.renren.com/601730243/admin')
            p = re.compile("get_check:'(.*)',get_check_x:'(.*)',env")
            h = self._net.get('http://page.renren.com/%s/fdoing' % PAGE_ID)
            result = p.search(h)
            self._token = {
                'requestToken': result.group(1),
                '_rtk': result.group(2)
            }
            return self._token
        except:
            pass

    def send_msg(self, content):
        if isinstance(content, unicode):
            content = content.encode('u8')
        params = {
            'pid': PAGE_ID,
            'c': content
        }
        params.update(self._token)
        r = json.loads(self._net.post(
            'http://page.renren.com/doing/update', params))
        return r['code'] == 0
#CALLBACK_URL = 'http://localhost:8080/调试时候用的回调地址,注意修改人人应用里面的相应地方'

# 获取Authorization Code 的URI
AUTHORIZATION_URI = 'https://graph.renren.com/oauth/authorize'
# 获取Access Token 的URI
ACCESS_TOKEN_URI = 'https://graph.renren.com/oauth/token'
# 人人API Session Key 资源URI
SESSION_KEY_URI = 'https://graph.renren.com/renren_api/session_key'
# 人人API Server URI
API_SERVER = 'https://api.renren.com/restserver.do'
# 授权地址
OAUTH_URL = '{0}?client_id={1}&redirect_uri={2}&response_type=code&scope=read_user_message+admin_page+publish_feed+status_update'.format(AUTHORIZATION_URI, APIKEY, CALLBACK_URL)
# 主页id
PAGE_ID = 601730243

n = Net()


class RenRen(object):
    def __init__(self):
        self.params = dict(
            v='1.0',
            format='json',
            call_id=0,
            page_id=PAGE_ID
        )
        self.login_by_cookie()

    def get_access_token(self, code):
        params = dict(
            grant_type='authorization_code',
Ejemplo n.º 6
0
class CloudDisk(object):
    def __init__(self, email, pwd):
        # 对密码进行md5 hash
        self.pwd = md5(pwd).hexdigest()
        self.email = email
        self.n = Net()
        self.login()
        self.upload()
        try:
            self.reward()
        except:
            pass

    def login(self):
        print self.email, "login..."
        # 获取token:
        html = self.n.get(
            "https://login.360.cn/?o=sso&m=getToken&func=QHPass.loginUtils.tokenCallback&userName=%s&rand=0.6075735737103969&callback=QiUserJsonP1348367367684"
            % self.email
        )
        token = eval(re.findall(r"(\{.*\})", html)[0])["token"]

        # 登录360.cn:
        html = self.n.get(
            "https://login.360.cn/?o=sso&m=login&from=i360&rtype=data&func=QHPass.loginUtils.loginCallback&userName=%s&pwdmethod=1&password=%s&isKeepAlive=1&token=%s&captFlag=&r=1348367489870&callback=QiUserJsonP1348367367685"
            % (self.email, self.pwd, token)
        )

        # 得到用户信息和一个登录需要的s参数
        d = eval(re.findall(r"(\{.*\})", html)[0])
        self.userinfo = d["userinfo"]  # 用户信息
        self.qid = self.userinfo["qid"]

        # 由上一步得到一个s之后再登录yunpan.cn:
        self.n.get(
            "http://rd.login.yunpan.cn/?o=sso&m=setcookie&func=QHPass.loginUtils.setCookieCallback&s=%s&callback=QiUserJsonP1348374391615"
            % d["s"]
        )

        # 现在访问360主页就可以了:
        html = self.n.get("http://yunpan.360.cn/user/login?st=774")
        # 但是因为360使用了集群,所以访问上面这个网址他会自动转到另外一个网址
        self.cluster_id = re.findall(r"http://c(\d+).yunpan.360.cn", html[:1000])[0]

    def upload(self):
        print "upload files*******************"
        """上传文件"""
        # 先检查文件是否存在[这时会改变cookie],同时获取存在于cookie中的token
        self.n.post(
            "http://c%s.yunpan.360.cn/file/detectFileExists" % self.cluster_id,
            {"dir": "/", "fname[]": "upload-gorthon.txt", "ajax": 1},
        )
        # {"errno":0,"errmsg":"\u64cd\u4f5c\u6210\u529f","data":{"exists":[]}} 操作成功
        token = self.n.cookie.get("token")
        p = {
            "Filename": "upload-gorthon.txt",
            "path": "/",
            "qid": self.qid,
            "ofmt": "json",
            "method": "Sync.webUpload",
            "token": token,
            "v": "1.0.1",
            "file": open(app_path + "/upload-gorthon.txt", "rb"),
            "Upload": "Submit Query",
        }
        datagen, headers = poster.encode.multipart_encode(p)
        opener = poster.streaminghttp.register_openers()
        opener.add_handler(urllib2.HTTPCookieProcessor(self.n.cookie))
        i = 10
        while i:
            urllib2.urlopen(
                urllib2.Request("http://up%s.yunpan.360.cn/webupload" % self.cluster_id, datagen, headers)
            ).read()
            # 分享刚才上传的文件
            # 要先得到刚才那个文件的nid
            print "Upload file %s" % i
            jsn = self.n.post(
                "http://c%s.yunpan.360.cn/file/list" % self.cluster_id,
                {
                    "type": 2,
                    "order": "asc",
                    "field": "file_name",
                    "t": "0.44758130819536746",
                    "path": "/",
                    "page": 0,
                    "page_size": 300,
                    "ajax": 1,
                },
            )
            nid = re.findall(r"\{oriName: 'upload-gorthon.txt',path: '/upload-gorthon.txt',nid: '(.*?)',.*?\}", jsn)[0]
            if i > 5:  # 分享5个文件
                self.n.post(
                    "http://c%s.yunpan.360.cn/link/create" % self.cluster_id,
                    {"nid": nid, "name": "/upload-gorthon.txt", "ajax": 1},
                )
                print "file %s was shared..." % i
            # 删除刚才上传的文件
            self.n.post(
                "http://c%s.yunpan.360.cn/file/recycle/" % self.cluster_id,
                {"path[]": "/upload-gorthon.txt", "t": "0.5056146369315684"},
            )
            print "file %s was deleted..." % i
            i -= 1
        # 虽然刚才上传的文件删除了但是分享里面还存在,所以取消分享
        jsn = self.n.post(
            "http://c%s.yunpan.360.cn/link/list" % self.cluster_id,
            {"type": 2, "order": "asc", "field": "file_name", "t": "0.44638799224048853", "ajax": 1},
        )
        print "All files ware unshared..."
        nids = re.findall(r'nid":"(.*?)"', jsn)
        params = "&".join(map(lambda x: "nids[]=%s" % x, nids)) + "&ajax=1"
        self.n.post("http://c%s.yunpan.360.cn/link/cancel" % self.cluster_id, params)

    def reward(self):
        print "Get reward************************"
        """领取免费空间"""
        jsn = json.loads(
            self.n.post("http://c%s.yunpan.360.cn/user/signin/" % self.cluster_id, dict(qid=self.qid, method="signin"))
        )

        data = jsn["data"]
        print data