def __init__(self, account_name, username, api_key):
        """ Constructor for CodeBaseAPI class.

        * This class requires account_name, username, api_key parameters to be passed
            in the constructor.
        * To get these credentials, click the Settings icon in the top-right of your
            Codebase HQ page (the one that looks like a wrench) and then click 'My Profile'.
            Go to the 'API Credentials' section at the bottom of the page

        Args:
            account_name: Account name of the CodebaseHQ user
            username: Username of the CodebaseHQ user
            api_key: API Key of the CodebaseHQ user

        Raises:
            CredentialError: when any on of the input params are empty
            Exception: when there is an un-expected error
         """
        if account_name and username and api_key:
            self.__auth = self.__get_auth_data(account_name, username, api_key)
        else:
            raise CredentialError()

        self.__config = self.__get_config()
        self.__endpoints = self.__config['endpoints']
        self.__http = HttpClient(
            base_url=self.__config['base_url'],
            auth=self.__auth
        )
Example #2
0
 def get_user(self, user_id):
     try:
         hc = HttpClient(ret_type="json")
         url = "%s?user=%s&key=%s" % (settings.OPS_USER_INFO_URL, user_id,
                                      settings.OPS_KEY)
         ret = hc.get(url)
         if ret["statusCode"] == 200 and ret["data"] and ret["data"][
                 "status"] == "00":
             ret = ret["data"]["data"]
             user = User(backend=self, username=ret["loginname"])
             user.last_name = ret["usernme"]
             user.email = "*****@*****.**" % ret["loginname"]
             user.is_active = True
             if ret["privilege"] == 1:
                 user.is_super = True
                 user.role = "root"
                 user.web_role = "SU"
             else:
                 user.is_super = False
                 user.role = "www"
                 user.web_role = "U"
             user.mobile = ret["mobile"]
             user.group = ret["usergroup"]
             user._is_authenticated = True
             return user
         return None
     except User.DoesNotExist:
         return None
Example #3
0
    def _check_passwd(self, password):
        """
        Binds to the LDAP server with the user's DN and password. Raises
        AuthenticationFailed on failure.
        """
        self._user_attrs = ["username", "cn", "email", "tel", "is_active"]
        hc = HttpClient()
        hc.headers.pop("Content-Type")
        url = settings.OPS_USER_AUTH_URL
        data = urllib.urlencode({
            "user": self._username,
            "passwd": password,
            "key": settings.OPS_KEY
        })
        ret = hc.post(url, data)

        try:
            ret = json.loads(ret)
            if ret["statusCode"] == 200 and ret["data"]["login"] == 1:
                self.pk = ret["data"]["loginname"]
                self.id = self.pk
                if ret["data"]["privilege"] == 1:
                    self.is_super = True
                    self.role = "root"
                    self.web_role = "SU"
                else:
                    self.is_super = False
                    self.role = "rd"
                    self.web_role = "U"
                return
        except Exception, e:
            logger.exception(e)
            raise self.AuthenticationFailed("user/password error")
Example #4
0
File: api.py Project: redu/redupy
 def __init__(self,
              consumer_key,
              consumer_secret,
              pin=None,
              model_factory=None,
              base_url="http://redu.com.br/api/"):
     self.client = HttpClient(consumer_key, consumer_secret, pin)
     self.base_url = base_url
     self.model_factory = model_factory or ModelFactory
Example #5
0
 def __init__(self,
              userIdentifier,
              userSecret,
              projectId,
              proxySettings=None):
     self.userIdentifier = userIdentifier
     self.userSecret = userSecret
     self.projectId = projectId
     self.proxySettings = proxySettings
     self.httpClient = HttpClient(self.host, proxySettings)
     self.authClient = AuthClient(userIdentifier, userSecret, proxySettings)
     self.urlHelper = UrlV2Helper(self.projectId)
Example #6
0
    def __init__(self):
        self.default_config = DefaultConfigs()
        self.req = HttpClient()

        self.friend_list = {}

        self.client_id = '53999199'
        self.ptwebqq = ''
        self.psessionid = ''
        self.appid = 0
        self.vfwebqq = ''
        self.qrcode_path = self.default_config.conf.get("global", "qrcode_path")  # QRCode保存路径
        self.username = ''
        self.account = 0
Example #7
0
class Spider():
    def __init__(self, rooturl):
        self.rooturl = rooturl
        self.h = HttpClient()

    def gethtml(self):
        return self.h.send(self.rooturl, method='get')
Example #8
0
	def __init__(self):
		self.Logs = Logs(self)
		self.Configs = Configs(self)
		self.DataUnits = DataUnits(self)
		self.HttpClient = HttpClient(self)
		self.HttpServer = HttpServer(self)
		self.Manipulator = Manipulator(self)
Example #9
0
class Spider():
    def __init__(self, rooturl):
        self.rooturl = rooturl
        self.h = HttpClient()
    
    def gethtml(self):      
        return self.h.send(self.rooturl,method='get')
Example #10
0
class AuthClient:
    host = "api.smartling.com"
    authUri = "/auth-api/v2/authenticate"
    refreshUri = "/auth-api/v2/authenticate/refresh"
    timeJitter = 5 #seconds off server expires time

    def __init__(self, userIdentifier, userSecret, proxySettings=None):
        self.httpClient = HttpClient(self.host, proxySettings)
        self.userIdentifier = userIdentifier
        self.userSecret = userSecret
        self.accessExpiresAt = 0
        self.refreshExpiresAt = 0
        
    def request(self, uri, body):
        header = {"Content-Type": "application/json"}
        response_data, status_code = self.httpClient.getHttpResponseAndStatus(ReqMethod.POST, uri, params={}, extraHeaders=header, requestBody=body)
        apiResponse = ApiResponse(response_data, status_code)
        
        now = time.time()
        try:
            self.accessToken = apiResponse.data.accessToken
            self.refreshToken = apiResponse.data.refreshToken
            self.accessExpiresAt = now + apiResponse.data.expiresIn - self.timeJitter
            self.refreshExpiresAt = now + apiResponse.data.refreshExpiresIn - self.timeJitter
        except Exception, e:
            print e
            self.accessToken = None
Example #11
0
 def __init__(self, userIdentifier, userSecret, projectId, proxySettings=None):
     self.userIdentifier = userIdentifier
     self.userSecret = userSecret
     self.projectId = projectId
     self.proxySettings = proxySettings
     self.httpClient = HttpClient(self.host, proxySettings)
     self.authClient = AuthClient(userIdentifier, userSecret, proxySettings)
     self.urlHelper = UrlV2Helper(self.projectId)
Example #12
0
 def is_super(self):
     try:
         if not self._is_superuser:
             infourl = settings.OPS_USER_INFO_URL
             data = "user=%s&key=%s" % (self.username, settings.OPS_KEY)
             url = "%s?%s" % (infourl, data)
             hc = HttpClient(ret_type="json")
             ret = hc.get(url)
             if ret and ret["statusCode"] == 200 and ret["data"][
                     "status"] == "00" and ret["data"]["data"][
                         "privilege"] == 1:
                 self._is_superuser = True
         return self._is_superuser
     except Exception, e:
         logger.exception(e)
         self._is_superuser = False
         return self._is_superuser
Example #13
0
def apiFunction(SmallZ):
    #在此感谢图灵机器人的API
    content = ""
    httpclient = HttpClient()

    if SmallZ.parameter == "blank":
        return content

    url = "http://www.tuling123.com/openapi/api"
    #....my key in www.tuling123.com, if you want to use, sign up a new key better.
    data = {
        "key": "9423edccf74e4a5792a62fc9cc13f97f",
        "info": SmallZ.parameter
    }

    strbuffer = json.loads(httpclient.Post(url, data))
    if strbuffer["code"] == 40001:
        content = "-api " + "xx" + "未找到响应结果~试试其他的吧~"
        print "apiFunction() -> 40001"
    elif strbuffer["code"] == 40002:
        content = "-api " + "xx" + "未找到响应结果~试试其他的吧~"
    elif strbuffer["code"] == 40004:
        content = "-api " + "xx" + "小z今天累了呢,,明天再来吧~~"
    elif strbuffer["code"] == 40007:
        content = "-api " + "xx" + "未找到响应结果~试试其他的吧~"
        print "apiFunction() -> 40007"
    else:
        content_temp = strbuffer["text"]

    #Handle content_temp
    flag = 0
    for i in content_temp:
        if i == "<":
            flag = 1
        if flag == 0:
            content += i
        if i == ">":
            flag = 0

    return content
Example #14
0
def main():
    result = EchoRsp()
    try:
        echoReq = EchoReq()
        echoReq.command = "Echo"
        echoReq.header = Header()
        echoReq.foo = "hello world!"

        result = HttpClient(server_ip, server_port,
                            server_module).request(echoReq, EchoRsp)
    except Exception, e:
        result.error = -1
        result.errmsg = str(e)
Example #15
0
    def __init__(self, client):
        self.__wxclient = HttpClient(client)
        self.tip = 0
        self.deviceId = 'e000701000000000'

        self.recvqueue = asyncio.Queue()
        self.sendqueue = asyncio.Queue()
        self.blacklist = []
        self.updatequeue = asyncio.Queue()  # 更新群组信息的请求
        self.grouplist = {}  # 存储群组的联系人信息
        # 给 monitor 用
        self.retcode = '0'
        self.selector = '0'
Example #16
0
 def login(self):
     
     values = {
         'j_username': self.user.username,
         'j_password': self.user.password,
     }
     
     self.client = HttpClient(
                  url=self.urls['login'],
                  method='post',
                  values=values
              )
     
     return self.client
Example #17
0
    async def get_tile_web(self, z_zoom, x_lat, y_lon, filename):
        print('App get_tile_web', z_zoom, x_lat, y_lon)
        self.domain_rotation = (self.domain_rotation + 1) % 3
        domain_prefix = ['a', 'b', 'c'][self.domain_rotation]
        domain = domain_prefix + '.tile.openstreetmap.org'

        if not self.httpClient:
            self.httpClient = HttpClient(domain, 80)
        status, headers, body = await self.httpClient.send_request(
            'GET', '/' + z_zoom + '/' + x_lat + '/' + y_lon + '.png')

        assert b'200' in status

        return body
Example #18
0
    def uin_to_account(self, tuin):
        uin_str = str(tuin)
        if uin_str not in self.friend_list:
            try:
                logging.info("Requesting the account by uin:    " + str(tuin))
                info = json.loads(HttpClient().Get(
                    'http://s.web2.qq.com/api/get_friend_uin2?tuin={0}&type=1&vfwebqq={1}'.format(uin_str,
                                                                                                  self.vfwebqq),
                    self.default_config.conf.get("global", "connect_referer")))
                logging.debug("uin_request html:    " + str(info))
                if info['retcode'] != 0:
                    raise TypeError('uin to account result error')
                info = info['result']
                self.friend_list[uin_str] = info['account']

            except BaseException, error:
                logging.warning(error)
Example #19
0
class Tfl():
    """Representation of the Tfl Oyster site
    
    Allows you to login and access the Journey History page.
    """
    
    urls = {
        'login':          "******",
        'journeyhistory': "https://oyster.tfl.gov.uk/oyster/ppvStatement.do",
    }
    
    user
    client
    
    def __init(self, tflUser):
        self.user = tflUser
    
    def login(self):
        
        values = {
            'j_username': self.user.username,
            'j_password': self.user.password,
        }
        
        self.client = HttpClient(
                     url=self.urls['login'],
                     method='post',
                     values=values
                 )
        
        return self.client
        
    def getJourneyHistoryPage(self, dateFrom, dateTo):
        
        try:
            response = self.client.request(url=self.urls['journeyhistory'])
        except AttributeError:
            print "Tfl.getJourneyHistoryPage needs you to run the login method first"
            
        return response
Example #20
0
    ('clientid', ClientID),
    ('psessionid', PSessionID)
  ), Referer)


def SendQQMsg(uin, msg):
  SendMsg('send_buddy_msg2', uin, msg, 'to')

def SendGroupMsg(qid, msg):
  SendMsg('send_qun_msg2', qid, msg, 'group_uin')


logging.basicConfig(filename='qq.log', level=logging.DEBUG, format='%(asctime)s  %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='[%Y-%m-%d %H:%M:%S]')


http = HttpClient()


initUrl = "https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&style=5&mibao_css=m_webqq&appid={0}&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=".format(APPID)

html = http.Get(initUrl, 'http://web2.qq.com/webqq.html')

sign = re.search(r'var g_login_sig=encodeURIComponent\("(.+?)"\);', html)

if sign is None:
  logging.error('get login sign error')
else:
  sign = sign.group(1)

logging.info('get sign : %s', sign)
Example #21
0
 def SendTelegramToDepartment(cls, _department, _stringData):
     print 'Ip:', _department.m_Ip
     print 'Port:', _department.m_Port
     httpClient = HttpClient(_department.m_Ip, int(_department.m_Port))
     httpClient.SendTelegram(_stringData)
Example #22
0
class FileApiV2:
    """ basic class implementing low-level api calls """
    host = 'api.smartling.com'
    response_as_string = False

    def __init__(self, userIdentifier, userSecret, projectId, proxySettings=None):
        self.userIdentifier = userIdentifier
        self.userSecret = userSecret
        self.projectId = projectId
        self.proxySettings = proxySettings
        self.httpClient = HttpClient(self.host, proxySettings)
        self.authClient = AuthClient(userIdentifier, userSecret, proxySettings)
        self.urlHelper = UrlV2Helper(self.projectId)

    def uploadMultipart(self, uri, params, response_as_string=False):
        if params.has_key(Params.FILE_PATH):
            params[Params.FILE] = open(params[Params.FILE_PATH], 'rb')
            del params[Params.FILE_PATH]  # no need in extra field in POST

        authHeader = self.getAuthHeader()  
        response_data, status_code = self.getHttpResponseAndStatus(ReqMethod.POST ,uri, params, MultipartPostHandler, extraHeaders = authHeader)
        response_data = response_data.strip()
        if self.response_as_string or response_as_string:
            return response_data, status_code
        return ApiResponse(response_data, status_code), status_code
  
    def getHttpResponseAndStatus(self, method, uri, params, handler=None, extraHeaders = None):
        return self.httpClient.getHttpResponseAndStatus(method, uri, params, handler, extraHeaders = extraHeaders)
  
    def getAuthHeader(self):
        token = self.authClient.getToken()
        if token is None:
            raise "Error getting token, check you credentials"
            
        return {"Authorization" : "Bearer "+ token} 
   
    def command_raw(self, method, uri, params):
        authHeader = self.getAuthHeader()
        return self.getHttpResponseAndStatus(method, uri, params, extraHeaders = authHeader)

    def command(self, method, uri, params):
        data, code = self.command_raw(method, uri, params)
        if self.response_as_string:
            return data, code
        return  ApiResponse(data, code), code

    def validateFileTypes(self, kw):
        fileTypes = kw.get("fileTypes",[])
        if type(fileTypes) != type([]) and type(fileTypes) != type(()):
            fileTypes = [fileTypes]
        for t in fileTypes: 
            if not getattr(FileTypes, t, None):
                unsupported = "\nUnsupported file type:%s\n" % t
                raise unsupported

    def checkRetrievalType(self, kw):
        if Params.RETRIEVAL_TYPE in kw and not kw[Params.RETRIEVAL_TYPE] in Params.allowedRetrievalTypes:
            raise "Not allowed value `%s` for parameter:%s try one of %s" % (kw[Params.RETRIEVAL_TYPE],
                                                                             Params.RETRIEVAL_TYPE,
                                                                             Params.allowedRetrievalTypes)

    def processDirectives(self, params, directives):
        for name, value in directives.items():
           params["smartling." + name] = value

#-----------------------------------------------------------------------------------

    def commandGet(self, fileUri, locale, directives={}, **kw):
        """ http://docs.smartling.com/pages/API/v2/FileAPI/Download-File/Single-Locale/ """
        kw[Params.FILE_URI] = fileUri
 
        self.checkRetrievalType(kw)
        self.processDirectives(kw, directives)
        url = self.urlHelper.getUrl(self.urlHelper.GET, localeId=locale)
        return self.command_raw(ReqMethod.GET, url, kw)

    def commandGetMultipleLocalesAsZip(self, fileUri, localeIds, directives={}, **kw):
        """ http://docs.smartling.com/pages/API/v2/FileAPI/Download-File/Multiple-Locales/ """
        kw[Params.FILE_URIS] = fileUri
        kw[Params.LOCALE_IDS] = localeIds
 
        self.checkRetrievalType(kw)
        self.processDirectives(kw, directives)
        
        return self.command_raw(ReqMethod.GET, self.urlHelper.getUrl(self.urlHelper.GET_MULTIPLE_LOCALES), kw)
 
    def commandGetAllLocalesZip(self, fileUri, directives={}, **kw):
         """ http://docs.smartling.com/pages/API/v2/FileAPI/Download-File/All-Locales """
         kw[Params.FILE_URI] = fileUri
  
         self.checkRetrievalType(kw)
         self.processDirectives(kw, directives)

         url = self.urlHelper.getUrl(self.urlHelper.GET_ALL_LOCALES_ZIP)
         
         return self.command_raw(ReqMethod.GET, url, kw)
        

    def commandGetAllLocalesCsv(self, fileUri, directives={}, **kw):
         """  http://docs.smartling.com/pages/API/v2/FileAPI/Download-File/All-Locales-CSV """
         kw[Params.FILE_URI] = fileUri
  
         self.checkRetrievalType(kw)
         self.processDirectives(kw, directives)

         url = self.urlHelper.getUrl(self.urlHelper.GET_ALL_LOCALES_CSV)
         return self.command_raw(ReqMethod.GET, url, kw)


    def commandGetOriginal(self, fileUri):
         """  http://docs.smartling.com/pages/API/v2/FileAPI/Download-File/Original-File/ """
         kw = {}
         kw[Params.FILE_URI] = fileUri
  
         url = self.urlHelper.getUrl(self.urlHelper.GET_ORIGINAL)
         return self.command_raw(ReqMethod.GET, url, kw)            

    def commandList(self, **kw):
        """ http://docs.smartling.com/pages/API/v2/FileAPI/List/ """
        url = self.urlHelper.getUrl(self.urlHelper.LIST_FILES)
        self.validateFileTypes(kw)
        
        return self.command(ReqMethod.GET, url, kw)
        
    def commandListFileTypes(self, **kw):
        """ http://docs.smartling.com/pages/API/v2/FileAPI/List-File-Types/ """
        return self.command(ReqMethod.GET, self.urlHelper.getUrl(self.urlHelper.LIST_FILE_TYPES), kw)

    def commandUpload(self, filePath, fileType, directives={}, **kw):
        """ http://docs.smartling.com/pages/API/v2/FileAPI/Upload-File/ """
        params = {
                Params.FILE_URI: filePath,
                Params.FILE_TYPE: fileType,
                Params.FILE_PATH: filePath
            }

        for k,v in kw.items():
            params[k] = v

        self.processDirectives(params, directives)
        
        url = self.urlHelper.getUrl(self.urlHelper.UPLOAD)
        return self.uploadMultipart(url, params)
        
    def commandProjectDetails(self):    
        """ http://docs.smartling.com/pages/API/v2/Projects/Project-Details/ """
        kw = {}
        url = self.urlHelper.getUrl(self.urlHelper.PROJECT_DETAILS)
        return self.command(ReqMethod.GET, url, kw)
        
    def commandProjects(self, accountUid):    
        """ http://docs.smartling.com/pages/API/v2/Projects/List-Projects/ """
        kw = {}
        url = self.urlHelper.getUrl(self.urlHelper.PROJECTS, accountUid = accountUid)
        return self.command(ReqMethod.GET, url, kw)
        

    def commandDelete(self, fileUri, **kw):
        """ http://docs.smartling.com/pages/API/v2/FileAPI/Delete/ """
        kw[Params.FILE_URI] = fileUri
        uri = self.urlHelper.getUrl(self.urlHelper.DELETE)

        return self.command(ReqMethod.POST, uri, kw)
        
    def commandStatus(self, fileUri):
        """ http://docs.smartling.com/pages/API/v2/FileAPI/Status/All-Locales/ """
        kw = {}
        kw[Params.FILE_URI] = fileUri
        url = self.urlHelper.getUrl(self.urlHelper.STATUS_ALL)
        return self.command(ReqMethod.GET, url, kw)
        
    def commandStatusLocale(self, fileUri, localeId):
        """ http://docs.smartling.com/pages/API/v2/FileAPI/Status/Single-Locale/ """
        kw = {}
        kw[Params.FILE_URI] = fileUri
        url = self.urlHelper.getUrl(self.urlHelper.STATUS_LOCALE, localeId = localeId)
        return self.command(ReqMethod.GET, url, kw)     
            
    def commandRename(self, fileUri, newFileUrl):
        """ http://docs.smartling.com/pages/API/v2/FileAPI/Rename/ """
        kw = {}
        kw[Params.FILE_URI] = fileUri
        kw[Params.FILE_URI_NEW] = newFileUrl
        url = self.urlHelper.getUrl(self.urlHelper.RENAME)
        return self.command(ReqMethod.POST, url, kw)

    def commandLastModified(self, fileUri, localeId, **kw):
        """ http://docs.smartling.com/pages/API/v2/FileAPI/Last-Modified/Single-Locale/ """
        kw[Params.FILE_URI] = fileUri
        url = self.urlHelper.getUrl(self.urlHelper.LAST_MODIFIED, localeId = localeId)
        return self.command(ReqMethod.GET, url, kw) 

    def commandLastModifiedAll(self, fileUri, **kw):
        """ http://docs.smartling.com/pages/API/v2/FileAPI/Last-Modified/All-Locales/ """
        kw[Params.FILE_URI] = fileUri
        url = self.urlHelper.getUrl(self.urlHelper.LAST_MODIFIED_ALL)
        return self.command(ReqMethod.GET, url, kw) 

    def commandImport(self, fileUriOriginal, filePathTranslated, fileType, localeId, directives={}, **kw):
        self.validateFileTypes({"fileTypes":fileType})
        params = {}
        params[Params.FILE_URI]  = fileUriOriginal
        params[Params.FILE_TYPE] = fileType
        params[Params.FILE_PATH] = filePathTranslated
        params["file"] = filePathTranslated + ";type=text/plain"

        for k,v in kw.items():
            params[k] = v
        
        self.processDirectives(params, directives)
        
        url = self.urlHelper.getUrl(self.urlHelper.IMPORT, localeId = localeId)
        return self.uploadMultipart(url, params)

    def commandListAuthorizedLocales(self, fileUri):
        """ http://docs.smartling.com/pages/API/v2/FileAPI/Authorize-Content/List-Authorized-Locales/ """
        kw = {}
        kw[Params.FILE_URI] = fileUri
        url = self.urlHelper.getUrl(self.urlHelper.LIST_AUTHORIZED_LOCALES)
        return self.command(ReqMethod.GET, url, kw) 

    def commandAuthorize(self, fileUri, localeIds):
        """ http://docs.smartling.com/pages/API/v2/FileAPI/Authorize-Content/Authorize/ """
        kw = {}
        kw[Params.FILE_URI] = fileUri
        kw[Params.LOCALE_IDS_BRACKET] = ",".join(localeIds)
        url = self.urlHelper.getUrl(self.urlHelper.AUTHORIZE)
        return self.command(ReqMethod.POST, url, kw)
        
    def commandUnauthorize(self, fileUri, localeIds):
        """  http://docs.smartling.com/pages/API/v2/FileAPI/Authorize-Content/Unauthorize/ """
        kw = {}
        kw[Params.FILE_URI] = fileUri
        kw[Params.LOCALE_IDS_BRACKET] = ",".join(localeIds)
        url = self.urlHelper.getUrl(self.urlHelper.UNAUTHORIZE)
        return self.command(ReqMethod.DELETE, url, kw)
        
    def commandGetTranslations(self, fileUri, filePath, localeId, directives={}, **kw):
        """  http://docs.smartling.com/pages/API/v2/FileAPI/Get-Translations/ """
        kw[Params.FILE_URI]  = fileUri
        kw[Params.FILE_PATH] = filePath
        kw["file"] = filePath + ";type=text/plain"
        
        self.processDirectives(kw, directives)

        url = self.urlHelper.getUrl(self.urlHelper.GET_TRANSLATIONS, localeId = localeId)
        return self.uploadMultipart(url, kw, response_as_string=True)       
Example #23
0
 def __init__(self, rooturl):
     self.rooturl = rooturl
     self.h = HttpClient()
class CodeBaseAPI:
    """Class to access Codebase API

    This warper for to access the CodebaseHQ API

    Attributes:
    __auth: Dict to hold codebaseHQ authentication credentials
    __config: Dict to hold codebase configuration data
    __endpoints: Dict to hold the codebase api endpoint/path data
    __http: Contains instance of the HttpClient class
    """

    def __init__(self, account_name, username, api_key):
        """ Constructor for CodeBaseAPI class.

        * This class requires account_name, username, api_key parameters to be passed
            in the constructor.
        * To get these credentials, click the Settings icon in the top-right of your
            Codebase HQ page (the one that looks like a wrench) and then click 'My Profile'.
            Go to the 'API Credentials' section at the bottom of the page

        Args:
            account_name: Account name of the CodebaseHQ user
            username: Username of the CodebaseHQ user
            api_key: API Key of the CodebaseHQ user

        Raises:
            CredentialError: when any on of the input params are empty
            Exception: when there is an un-expected error
         """
        if account_name and username and api_key:
            self.__auth = self.__get_auth_data(account_name, username, api_key)
        else:
            raise CredentialError()

        self.__config = self.__get_config()
        self.__endpoints = self.__config['endpoints']
        self.__http = HttpClient(
            base_url=self.__config['base_url'],
            auth=self.__auth
        )

    def __get_config(self):
        """ Gets the configuration data

        If there any changes in the CodebaseHQ API URL or endpoints, then
        these change the value in this dict

        Args:
            None

        Returns:
            dict containing the CodebaseHQ configuration data

        Raises:
            None
        """
        return {
            'base_url': 'https://api3.codebasehq.com',
            'endpoints': {
                'all_projects': '/projects',
                'project': '/project',
                'tickets': '/tickets'
            }
        }

    def get_all_projects(self):
        """Gets all the projects details

        * Makes an HTTP GET request to the /projects endpoint to get all project data.
        * API URL: https://api3.codebasehq.com/projects
        * [Documentation Link](https://support.codebasehq.com/kb/projects)
        
        Sample Output:
        ```
        <projects type="array">
            <project>
                <group-id type="integer" nil="true"></group-id>
                <icon type="integer">1</icon>
                <name>Codebase</name>
                <account-name>aTech Media</account-name>
                <overview></overview>
                <permalink>codebase</permalink>
                <start-page>overview</start-page>
                <status>active</status>
                <total-tickets>100</total-tickets>
                <open-tickets>36</open-tickets>
                <closed-tickets>64</closed-tickets>
            </project>
            <project>
            ...
            </project>
        </projects>
        ```
        """
        response = self.__http.get(
            endpoint=self.__endpoints['all_projects'],
            headers=self.__get_common_headers(),
        )
        return response

    def __get_common_headers(self):
        """Gets common header to be sent with the HTTP request object

        Args:
            None

        Returns:
            Dict containing custom header data

        Raises:
            None
        """
        return {
            'Content-type': "application/xml"
        }

    def __get_auth_data(self, account_name, username, api_key):
        """ Gets data for HTTP Basic Authentication

        Args:
            account_name: Account name of the CodebaseHQ user
            username: Username of the CodebaseHQ user
            api_key: API Key of the CodebaseHQ user

        Returns:
            dict containing username and password

        Raises:
            Exception: when there is an un-expected error
        """
        return {
            'username': account_name + '/' + username,
            'password': api_key
        }
Example #25
0
def createClient(self, url):
    return HttpClient(url)
Example #26
0
File: api.py Project: redu/redupy
class Redu(object):
    def __init__(self,
                 consumer_key,
                 consumer_secret,
                 pin=None,
                 model_factory=None,
                 base_url="http://redu.com.br/api/"):
        self.client = HttpClient(consumer_key, consumer_secret, pin)
        self.base_url = base_url
        self.model_factory = model_factory or ModelFactory

    def getAuthorizeUrl(self):
        return self.client.getAuthorizeUrl()

    def initClient(self, pin):
        self.client.initClient(pin)

    getMe = bind_api(path="me", mehtod="get", payload_type="user")

    getUser = bind_api(path="users/{0}", method="get", payload_type="user")

    getUserBySpace = bind_api(path="spaces/{0}/users",
                              method="get",
                              payload_type="user")

    getEnvironment = bind_api(path="environments/{0}",
                              method="get",
                              payload_type="environment")

    postEnvironment = bind_api(
        path="environments",
        method="post",
        payload_type="environment",
        payload_params=["name", "path", "initials", "description"])

    editEnvironment = bind_api(
        path="environments/{0}",
        method="put",
        send_type="environment",
        payload_params=["name", "path", "initials", "description"])

    deleteEnvironment = bind_api(path="environments/{0}", method="delete")

    getSubjectsBySpace = bind_api(path="spaces/{0}/subjects",
                                  method="get",
                                  payload_type="subject")

    getSubject = bind_api(path="subjects/{0}",
                          method="get",
                          payload_type="subject")

    getSpace = bind_api(path="spaces/{0}", method="get", payload_type="space")

    editSpace = bind_api(path="spaces/{0}",
                         method="put",
                         payload_params=['name', 'description'],
                         send_type="space")

    postSpace = bind_api(path="courses/{0}/spaces",
                         method="post",
                         payload_type='space',
                         payload_params=['name', 'description'])

    getSpaceByCourse = bind_api(path="courses/{0}/spaces",
                                method="get",
                                payload_type="space")

    deleteSpace = bind_api(path="spaces/{0}", method="delete")

    getStatus = bind_api(path="statuses/{0}",
                         method="get",
                         payload_type="status")

    getAnswers = bind_api(path="statuses/{0}/answers",
                          method="get",
                          payload_type="status")

    postAnswer = bind_api(path="statuses/{0}/answers",
                          method="post",
                          payload_type="status",
                          payload_params=["text"])

    getStatusByUser = bind_api(path="users/{0}/statuses",
                               method="get",
                               payload_type="status",
                               querry_params=["type", "page"])

    getTimelineByUser = bind_api(path="users/{0}/statuses/timeline",
                                 method="get",
                                 payload_type="status",
                                 querry_params=["type", "page"])

    postStatusUser = bind_api(path="users/{0}/statuses",
                              method="post",
                              payload_type="status",
                              payload_params=["text"])

    getTimelineBySpace = bind_api(path="spaces/{0}/statuses/timeline",
                                  method="get",
                                  payload_type="status",
                                  querry_params=["type", "page"])

    getStatusBySpace = bind_api(path="spaces/{0}/statuses",
                                method="get",
                                payload_type="status",
                                querry_params=["type", "page"])

    postStatusSpace = bind_api(path="spaces/{0}/statuses",
                               method="post",
                               payload_type="status",
                               payload_params=["text"])

    getStatusByLecture = bind_api(path="lectures/{0}/statuses",
                                  method="get",
                                  payload_type="status",
                                  querry_params=["type", "page"])

    postStatusLecture = bind_api(path="lectures/{0}/statuses",
                                 method="post",
                                 payload_type="status",
                                 payload_params=["text"])

    deleteStatus = bind_api(path="statuses/{0}", method="delete")

    getCourse = bind_api(path="courses/{0}",
                         method="get",
                         payload_type="course")

    postCourse = bind_api(
        path="environments/{0}/courses",
        method="post",
        payload_type="course",
        payload_params=["name", "path", "description", "workload"])

    editCourse = bind_api(
        path="courses/{0}",
        method="put",
        send_type="course",
        payload_params=["name", "path", "description", "workload"])

    getCoursesByEnvironment = bind_api(path="environments/{0}/courses",
                                       method="get",
                                       payload_type="course")

    deleteCourse = bind_api(path="courses/{0}", method="delete")

    getEnrollment = bind_api(path="enrollments/{0}",
                             method="get",
                             payload_type="enrollment")

    postEnrollment = bind_api(path="courses/{0}/enrollments",
                              method="post",
                              payload_type="enrollment",
                              payload_params=["email"])

    getEnrolmentsByCourse = bind_api(path="courses/{0}/enrollments",
                                     method="get",
                                     payload_type="enrollment")

    deleteEnrollment = bind_api(path="enrollments/{0}", method="delete")

    getChatsByUser = bind_api(path='users/{0}/chats',
                              method='get',
                              payload_type='chat')

    getChat = bind_api(path='chats/{0}', method='get', payload_type='chat')

    getChatMessagesByChat = bind_api(path='chats/{0}/chat_messages',
                                     method='get',
                                     payload_type='chat_message')

    getChatMessage = bind_api(path='chat_messages/{0}',
                              method='get',
                              payload_type='chat_message')
def register(mailAccount, name, password):

    # Set up
    mailUrl = "https://10minutemail.net/"
    httpClient = HttpClient()
    httpParser = ResponseParser()

    # Start the driver/browser and open Url
    driver = webdriver.Chrome()
    driver.implicitly_wait(30)
    driver.get("https://twitter.com/i/flow/signup")

    #Switch from phonenumber to email
    driver.find_element_by_xpath("//div[@role = 'button']/span").click()

    # Name
    inputField = driver.find_element_by_name("name")
    inputField.clear()
    inputField.send_keys(name)

    # Mail
    inputField = driver.find_element_by_name("email")
    inputField.clear()
    inputField.send_keys(mailAccount[0])
    time.sleep(3)

    # Go to next page
    button = driver.find_element_by_xpath(
        "//div[@role = 'button']/div/span/span")
    button.click()

    # Tick checkboxes
    # button = driver.find_elements_by_xpath("//input[@type ='checkbox']")[0]
    # button.click()
    button = driver.find_elements_by_xpath("//input[@type ='checkbox']")[1]
    button.click()
    # button = driver.find_elements_by_xpath("//input[@type ='checkbox']")[2]
    # button.click()

    # Go to next page
    button = driver.find_element_by_xpath(
        "//div[@role = 'button']/div/span/span")
    button.click()

    # Register
    button = driver.find_element_by_xpath(
        "//div[@role = 'button']/div/span/span")
    button.click()

    # Get the verification code
    links = httpParser.getInboxLinks(
        httpClient.sendRequest(mailUrl, mailAccount[1]))
    while len(links) < 2:
        links = httpParser.getInboxLinks(
            httpClient.sendRequest(mailUrl, mailAccount[1]))
        time.sleep(10)

    code = httpParser.getTwitterCode(
        httpClient.sendRequest(mailUrl + links[0], mailAccount[1]))

    # Write the code
    inputField = driver.find_element_by_name("verfication_code")
    inputField.clear()
    inputField.send_keys(code)
    time.sleep(3)

    # Go to next page
    button = driver.find_element_by_xpath(
        "//div[@role = 'button']/div/span/span")
    button.click()

    # Select a password
    inputField = driver.find_element_by_name("password")
    inputField.clear()
    inputField.send_keys(password)
    time.sleep(3)

    # Go to next page
    button = driver.find_element_by_xpath(
        "//div[@role = 'button']/div/span/span")
    button.click()
    time.sleep(3)

    # Skip selecting a picture
    button = driver.find_element_by_xpath(
        "//div[@role = 'button']/div/span/span")
    button.click()
    time.sleep(1)

    # Skip the biography
    button = driver.find_element_by_xpath(
        "//div[@role = 'button']/div/span/span")
    button.click()
    time.sleep(2)

    # Skip interests
    button = driver.find_element_by_xpath(
        "//div[@role = 'button']/div/span/span")
    button.click()
    time.sleep(3)

    # Skip following
    button = driver.find_element_by_xpath(
        "//div[@role = 'button']/div/span/span")
    button.click()
    time.sleep(2)

    # Allow notifications
    buttons = driver.find_elements_by_xpath(
        "//div[@role = 'button']/div/span/span")
    buttons[1].click()
    time.sleep(2)

    # Close getting started
    button = driver.find_element_by_xpath("//div[@aria-label = 'Close']")
    button.click()
    time.sleep(2)
Example #28
0
    ret += '\n' + stderr.strip()
  except Exception, e:
    ret += e
  ret = ret.replace('\\', '\\\\\\\\').replace('\t', '\\\\t').replace('\r', '\\\\r').replace('\n', '\\\\n')
  ret = ret.replace('"', '\\\\\\"')
  http.Post("http://d.web2.qq.com/channel/send_buddy_msg2", (
    ('r', '{{"to":{0},"face":522,"content":"[\\"{4}\\",[\\"font\\",{{\\"name\\":\\"Arial\\",\\"size\\":\\"10\\",\\"style\\":[0,0,0],\\"color\\":\\"000000\\"}}]]","msg_id":{1},"clientid":"{2}","psessionid":"{3}"}}'.format(msg['value']['from_uin'], msgId, ClientID, PSessionID, ret)),
    ('clientid', ClientID),
    ('psessionid', PSessionID)
  ), Referer)


logging.basicConfig(filename='qq.log', level=logging.DEBUG, format='%(asctime)s  %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S')


http = HttpClient()


initUrl = "https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&style=5&mibao_css=m_webqq&appid={0}&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=".format(APPID)

html = http.Get(initUrl)

sign = re.search(r'var g_login_sig=encodeURIComponent\("(.+?)"\);', html)

if sign is None:
  logging.error('get login sign error')
else:
  sign = sign.group(1)

logging.info('get sign : %s', sign)
Example #29
0
File: api.py Project: redu/redupy
 def __init__(self, consumer_key, consumer_secret,
     pin=None, model_factory=None, base_url="http://redu.com.br/api/"):
     self.client = HttpClient(consumer_key, consumer_secret, pin)
     self.base_url = base_url
     self.model_factory = model_factory or ModelFactory
Example #30
0
 def __init__(self, host, apiKey, projectId, proxySettings=None):
     self.host = host
     self.apiKey = apiKey
     self.projectId = projectId
     self.proxySettings = proxySettings
     self.httpClient = HttpClient(host, proxySettings)
Example #31
0
 def __init__(self, userIdentifier, userSecret, proxySettings=None):
     self.httpClient = HttpClient(self.host, proxySettings)
     self.userIdentifier = userIdentifier
     self.userSecret = userSecret
     self.accessExpiresAt = 0
     self.refreshExpiresAt = 0
Example #32
0
#-*- coding:utf-8 -*-

from HttpClient import HttpClient

client = HttpClient()
result = client.doRequest('User.Baseinfo', {"username": "******"})
print result
client.print_result()
Example #33
0
 def __init__(self):
     self.infourl = "http://live.win007.com/vbsxml/bfdata.js?r=007%s000"
     self.httpClient = HttpClient()
     self.tipmaxtimes = 3
     self.ballteammap = {}
     self.emails = ["*****@*****.**"]
Example #34
0
 def SendTelegramToDepartmentList(cls, _listDepartment, _stringData):
     for item in _listDepartment:
         httpClient = HttpClient(item.m_Ip,
                                 int(item.m_Port))  # FIXME 部分失败如何处理???
         httpClient.SendTelegram(_stringData)
Example #35
0
# Tests for ResponseParser class
#
#

from HttpClient import HttpClient
from ResponseParser import ResponseParser


testUrl = "https://10minutemail.net/"

testClient = HttpClient()
testParser = ResponseParser()

# testResponse = testClient.initialRequest(testUrl)
# cookie = testParser.getCookies(testResponse)
cookie = {"PHPSESSID":"e2ee08ec196ed786ada381722fd1b5a5"}
testResponse = testClient.sendRequest(testUrl, cookie)
links = testParser.getInboxLinks(testResponse)

for link in links:
    code = testParser.getTwitterCode(
        testClient.sendRequest(testUrl + link, cookie))
    print(code)


# Test getFakeAccData method
# print( testParser.getFakeAccData(testResponse))

# Test getInboxLinks method
# print( testParser.getInboxLinks(testResponse))
Example #36
0
class QQ():
    HttpClient_Ist = HttpClient()

    # ClientID = int(random.uniform(11111111, 88888888))
    ClientID = 53999199
    PTWebQQ = ''
    APPID = 0
    msgId = 0
    FriendList = {}
    GroupList = {}
    ThreadList = []
    GroupThreadList = []
    GroupWatchList = ['192795735', '314440865', '18']
    PSessionID = ''
    Referer = 'http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=2'
    # Referer = 'http://d.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2'
    # SmartQQUrl = 'http://w.qq.com/login.html'
    VFWebQQ = ''
    AdminQQ = '0'
    tulingkey = '6d7bdd3255fb1c940d265f6470b1b641'

    initTime = time.time()

    @classmethod
    def pass_time(cls):
        # global initTime
        rs = (time.time() - QQ.initTime)
        QQ.initTime = time.time()
        return str(round(rs, 3))

    # 查询QQ号,通常首次用时0.2s,以后基本不耗时
    @classmethod
    def uin_to_account(cls, tuin):
        # 如果消息的发送者的真实QQ号码不在FriendList中,则自动去取得真实的QQ号码并保存到缓存中
        # global FriendList,Referer
        if tuin not in QQ.FriendList:
            try:
                t = int(time.time()) * 1000
                print tuin, QQ.VFWebQQ, t
                print 'http://s.web2.qq.com/api/get_friend_uin2?tuin={0}&type=1&vfwebqq={1}&t={2}'.format(
                    tuin, QQ.VFWebQQ, t)
                info = json.loads(
                    cls.HttpClient_Ist.Get(
                        'http://s.web2.qq.com/api/get_friend_uin2?tuin={0}&type=1&vfwebqq={1}&t={2}'
                        .format(tuin, QQ.VFWebQQ, t), QQ.Referer))
                logging.info("Get uin to account info:" + str(info))
                print u'真实QQ:' + str(info)
                if info['retcode'] != 0:
                    print u'询问真实QQ号出错'
                    raise ValueError, info
                info = info['result']
                QQ.FriendList[tuin] = info['account']
                print u'获得真实QQ号码:' + str(info['account'])

            except Exception as e:
                logging.error(e)

        logging.info(u"Now FriendList:" + str(QQ.FriendList))
        return QQ.FriendList[tuin]

    def getQQnumber(self):
        return self.qqLogin.getqq()

    @classmethod
    def msg_handler(cls, msgObj):
        for msg in msgObj:
            msgType = msg['poll_type']

            # QQ私聊消息
            if msgType == 'message' or msgType == 'sess_message':  # 私聊 or 临时对话
                txt = combine_msg(msg['value']['content'])
                tuin = msg['value']['from_uin']  #普通消息QQ号加密后
                msg_id = msg['value']['msg_id2']
                from_account = QQ.uin_to_account(tuin)

                # print "{0}:{1}".format(from_account, txt)
                targetThread = QQ.thread_exist(from_account)
                if targetThread:
                    targetThread.push(txt, msg_id)
                else:
                    try:
                        service_type = 0
                        isSess = 0
                        group_sig = ''
                        if msgType == 'sess_message':
                            isSess = 1
                            service_type = msg['value']['service_type']
                            myid = msg['value']['id']
                            ts = time.time()
                            while ts < 1000000000000:
                                ts = ts * 10
                            ts = int(ts)
                            info = json.loads(
                                QQ.HttpClient_Ist.Get(
                                    'http://d.web2.qq.com/channel/get_c2cmsg_sig2?id={0}&to_uin={1}&clientid={2}&psessionid={3}&service_type={4}&t={5}'
                                    .format(myid, tuin, QQ.ClientID,
                                            QQ.PSessionID, service_type, ts),
                                    QQ.Referer))
                            logging.info("Get group sig:" + str(info))
                            if info['retcode'] != 0:
                                raise ValueError, info
                            info = info['result']
                            group_sig = info['value']
                        tmpThread = QQ.pmchat_thread(tuin, isSess, group_sig,
                                                     service_type)
                        tmpThread.start()
                        QQ.ThreadList.append(tmpThread)
                        tmpThread.push(txt, msg_id)
                    except Exception, e:
                        logging.info("error" + str(e))

                        # print "{0}:{1}".format(self.FriendList.get(tuin, 0), txt)

                        # if FriendList.get(tuin, 0) == AdminQQ:#如果消息的发送者与AdminQQ不相同, 则忽略本条消息不往下继续执行
                        #     if txt[0] == '#':
                        #         thread.start_new_thread(self.runCommand, (tuin, txt[1:].strip(), msgId))
                        #         msgId += 1

                        # if txt[0:4] == 'exit':
                        #     logging.info(self.Get('http://d.web2.qq.com/channel/logout2?ids=&clientid={0}&psessionid={1}'.format(self.ClientID, self.PSessionID), Referer))
                        #     exit(0)

            # 群消息
            if msgType == 'group_message':
                # global GroupList, GroupWatchList
                txt = combine_msg(msg['value']['content'])
                guin = msg['value']['from_uin']
                gid = msg['value']['info_seq']
                tuin = msg['value']['send_uin']
                seq = msg['value']['seq']
                QQ.GroupList[guin] = gid
                if str(gid) in QQ.GroupWatchList:
                    g_exist = QQ.group_thread_exist(gid)
                    if g_exist:
                        print u'群线程存在'
                        g_exist.handle(tuin, txt, seq)
                        # g_exist.get_group_list()
                    else:
                        tmpThread = QQ.group_thread(guin)
                        tmpThread.start()
                        QQ.GroupThreadList.append(tmpThread)
                        # tmpThread.get_group_list()
                        tmpThread.handle(tuin, txt, seq)
                        logging.info("群线程已生成")
                        print u'群线已+生成'
                else:
                    logging.info(str(gid) + "群有动态,但是没有被监控")

                    # from_account = uin_to_account(tuin)
                    # print "{0}:{1}".format(from_account, txt)
            if msgType == 'discu_message':
                print u'开始讨论组回复'
                txt = combine_msg(msg['value']['content'])
                guin = msg['value']['from_uin']
                gid = msg['value']['info_seq']
                tuin = msg['value']['send_uin']
                seq = msg['value']['seq']
                QQ.GroupList[guin] = gid
                if str(gid) in QQ.GroupWatchList:
                    g_exist = QQ.discu_thread_exist(gid)
                    if g_exist:
                        print u'群线程存在'
                        g_exist.handle(tuin, txt, seq)
                    else:
                        tmpThread = QQ.discu_thread(guin)
                        tmpThread.start()
                        QQ.GroupThreadList.append(tmpThread)
                        tmpThread.handle(tuin, txt, seq)
                        logging.info("群线程已生成")
                        print u'群线已生成'
                else:
                    logging.info(str(gid) + "群有动态,但是没有被监控")
                pass
            if msgType == 'sys_g_msg':
                if msg['value']['type'] == 'group_request_join':
                    print u'申请加群'
                    from_uin = msg['value']['from_uin']
                    request_uin = msg['value']['request_uin']
                    gcode = msg['value']['gcode']
                    t = QQ.group_check_thread(guin=from_uin, gcode=gcode)
                    t.request_member(request_uin)
                    t.start()
                    print u'监听成员线程已经生成'
                    # 轮询加入uin

                pass
            # QQ号在另一个地方登陆, 被挤下线
            if msgType == 'kick_message':
                logging.error(msg['value']['reason'])
                raise Exception, msg['value'][
                    'reason']  # 抛出异常, 重新启动WebQQ, 需重新扫描QRCode来完成登陆
Example #37
0
class ApiV2:
    """ basic class implementing low-level api calls """
    host = 'api.smartling.com'
    response_as_string = False

    def __init__(self, userIdentifier, userSecret, proxySettings=None):
        self.userIdentifier = userIdentifier
        self.userSecret = userSecret
        self.proxySettings = proxySettings
        self.httpClient = HttpClient(self.host, proxySettings)
        self.authClient = AuthClient(userIdentifier, userSecret, proxySettings)

    def uploadMultipart(self, uri, params, response_as_string=False):
        if params.has_key(Params.FILE_PATH):
            params[Params.FILE] = open(params[Params.FILE_PATH], 'rb')
            del params[Params.FILE_PATH]  # no need in extra field in POST

        authHeader = self.getAuthHeader()  
        response_data, status_code = self.getHttpResponseAndStatus(ReqMethod.POST ,uri, params, MultipartPostHandler, extraHeaders = authHeader)
        response_data = response_data.strip()
        if self.response_as_string or response_as_string:
            return response_data, status_code
        return ApiResponse(response_data, status_code), status_code

    def getHttpResponseAndStatus(self, method, uri, params, handler=None, extraHeaders = None):
        return self.httpClient.getHttpResponseAndStatus(method, uri, params, handler, extraHeaders = extraHeaders)

    def getAuthHeader(self):
        token = self.authClient.getToken()
        if token is None:
            raise "Error getting token, check you credentials"

        return {"Authorization" : "Bearer "+ token} 

    def command_raw(self, method, uri, params):
        authHeader = self.getAuthHeader()
        return self.getHttpResponseAndStatus(method, uri, params, extraHeaders = authHeader)

    def command(self, method, uri, params):
        data, code = self.command_raw(method, uri, params)
        if self.response_as_string:
            return data, code
        return  ApiResponse(data, code), code

    def validateFileTypes(self, kw):
        fileTypes = kw.get("fileTypes",[])
        if type(fileTypes) != type([]) and type(fileTypes) != type(()):
            fileTypes = [fileTypes]
        for t in fileTypes: 
            if not getattr(FileTypes, t, None):
                unsupported = "\nUnsupported file type:%s\n" % t
                raise unsupported

    def checkRetrievalType(self, kw):
        if Params.RETRIEVAL_TYPE in kw and not kw[Params.RETRIEVAL_TYPE] in Params.allowedRetrievalTypes:
            raise "Not allowed value `%s` for parameter:%s try one of %s" % (kw[Params.RETRIEVAL_TYPE],
                                                                             Params.RETRIEVAL_TYPE,
                                                                             Params.allowedRetrievalTypes)

    def processDirectives(self, params, directives):
        for name, value in directives.items():
           params["smartling." + name] = value
Example #38
0
 def __init__(self, userIdentifier, userSecret, proxySettings=None):
     self.userIdentifier = userIdentifier
     self.userSecret = userSecret
     self.proxySettings = proxySettings
     self.httpClient = HttpClient(self.host, proxySettings)
     self.authClient = AuthClient(userIdentifier, userSecret, proxySettings)
Example #39
0
class FileApiBase:
    """ basic class implementing low-level api calls """
    response_as_string = False

    def __init__(self, host, apiKey, projectId, proxySettings=None):
        self.host = host
        self.apiKey = apiKey
        self.projectId = projectId
        self.proxySettings = proxySettings
        self.httpClient = HttpClient(host, proxySettings)

    def addApiKeys(self, params):
        params[Params.API_KEY] = self.apiKey
        params[Params.PROJECT_ID] = self.projectId

    def uploadMultipart(self, uri, params):
        self.addApiKeys(params)
        params[Params.FILE] = open(params[Params.FILE_PATH], 'rb')
        del params[Params.FILE_PATH]  # no need in extra field in POST
        response_data, status_code = self.getHttpResponseAndStatus(
            ReqMethod.POST, uri, params, MultipartPostHandler)
        response_data = response_data.strip()
        if self.response_as_string:
            return response_data, status_code
        return ApiResponse(response_data, status_code), status_code

    def getHttpResponseAndStatus(self, method, uri, params, handler=None):
        return self.httpClient.getHttpResponseAndStatus(
            method, uri, params, handler)

    def command_raw(self, method, uri, params):
        self.addApiKeys(params)
        return self.getHttpResponseAndStatus(method, uri, params)

    def command(self, method, uri, params):
        data, code = self.command_raw(method, uri, params)
        if self.response_as_string:
            return data, code
        return ApiResponse(data, code), code

    # commands

    def commandUpload(self, uploadData):
        params = {
            Params.FILE_URI: uploadData.uri or uploadData.name,
            Params.FILE_TYPE: uploadData.type,
            Params.FILE_PATH: uploadData.path + uploadData.name
        }
        if (uploadData.approveContent):
            params[Params.APPROVED] = uploadData.approveContent

        if (uploadData.callbackUrl):
            params[Params.CALLBACK_URL] = uploadData.callbackUrl

        if (uploadData.directives):
            for index, directive in enumerate(uploadData.directives):
                params[directive.sl_prefix + directive.name] = directive.value

        if (uploadData.localesToApprove):
            for index, locale in enumerate(uploadData.localesToApprove):
                params['{0}[{1}]'.format(Params.LOCALES_TO_APPROVE,
                                         index)] = locale

        return self.uploadMultipart(Uri.UPLOAD, params)

    def commandList(self, **kw):
        return self.command(ReqMethod.POST, Uri.LIST, kw)

    def commandLastModified(self, fileUri, locale=None, **kw):
        kw[Params.FILE_URI] = fileUri
        if locale is not None:
            kw[Params.LOCALE] = locale
        return self.command(ReqMethod.GET, Uri.LAST_MODIFIED, kw)

    def commandGet(self, fileUri, locale, **kw):
        kw[Params.FILE_URI] = fileUri
        kw[Params.LOCALE] = locale
        if Params.RETRIEVAL_TYPE in kw and not kw[
                Params.RETRIEVAL_TYPE] in Params.allowedRetrievalTypes:
            raise "Not allowed value `%s` for parameter:%s try one of %s" % (
                kw[Params.RETRIEVAL_TYPE], Params.RETRIEVAL_TYPE,
                Params.allowedRetrievalTypes)

        return self.command_raw(ReqMethod.POST, Uri.GET, kw)

    def commandDelete(self, fileUri, **kw):
        kw[Params.FILE_URI] = fileUri

        return self.command(ReqMethod.POST, Uri.DELETE, kw)

    def commandImport(self, uploadData, locale, **kw):
        kw[Params.FILE_URI] = uploadData.uri
        kw[Params.FILE_TYPE] = uploadData.type
        kw[Params.FILE_PATH] = uploadData.path + uploadData.name
        kw["file"] = uploadData.path + uploadData.name + ";type=text/plain"
        kw[Params.LOCALE] = locale
        self.addApiKeys(kw)

        return self.uploadMultipart(Uri.IMPORT, kw)

    def commandStatus(self, fileUri, locale, **kw):
        kw[Params.FILE_URI] = fileUri
        kw[Params.LOCALE] = locale

        return self.command(ReqMethod.POST, Uri.STATUS, kw)

    def commandRename(self, fileUri, newUri, **kw):
        kw[Params.FILE_URI] = fileUri
        kw[Params.FILE_URI_NEW] = newUri

        return self.command(ReqMethod.POST, Uri.RENAME, kw)
Example #40
0
class FileApiBase:
    """ basic class implementing low-level api calls """

    response_as_string = False

    def __init__(self, host, apiKey, projectId, proxySettings=None):
        self.host = host
        self.apiKey = apiKey
        self.projectId = projectId
        self.proxySettings = proxySettings
        self.httpClient = HttpClient(host, proxySettings)

    def addApiKeys(self, params):
        params[Params.API_KEY] = self.apiKey
        params[Params.PROJECT_ID] = self.projectId

    def uploadMultipart(self, uri, params):
        self.addApiKeys(params)
        params[Params.FILE] = open(params[Params.FILE_PATH], "rb")
        del params[Params.FILE_PATH]  # no need in extra field in POST
        response_data, status_code = self.getHttpResponseAndStatus(ReqMethod.POST, uri, params, MultipartPostHandler)
        response_data = response_data.strip()
        if self.response_as_string:
            return response_data, status_code
        return ApiResponse(response_data, status_code), status_code

    def getHttpResponseAndStatus(self, method, uri, params, handler=None):
        return self.httpClient.getHttpResponseAndStatus(method, uri, params, handler)

    def command_raw(self, method, uri, params):
        self.addApiKeys(params)
        return self.getHttpResponseAndStatus(method, uri, params)

    def command(self, method, uri, params):
        data, code = self.command_raw(method, uri, params)
        if self.response_as_string:
            return data, code
        return ApiResponse(data, code), code

    # commands

    def commandUpload(self, uploadData):
        params = {
            Params.FILE_URI: uploadData.uri or uploadData.name,
            Params.FILE_TYPE: uploadData.type,
            Params.FILE_PATH: uploadData.path + uploadData.name,
        }
        if uploadData.approveContent:
            params[Params.APPROVED] = uploadData.approveContent

        if uploadData.callbackUrl:
            params[Params.CALLBACK_URL] = uploadData.callbackUrl

        if uploadData.directives:
            for index, directive in enumerate(uploadData.directives):
                params[directive.sl_prefix + directive.name] = directive.value

        if uploadData.localesToApprove:
            for index, locale in enumerate(uploadData.localesToApprove):
                params["{0}[{1}]".format(Params.LOCALES_TO_APPROVE, index)] = locale

        return self.uploadMultipart(Uri.UPLOAD, params)

    def commandList(self, **kw):
        return self.command(ReqMethod.POST, Uri.LIST, kw)

    def commandLastModified(self, fileUri, locale=None, **kw):
        kw[Params.FILE_URI] = fileUri
        if locale is not None:
            kw[Params.LOCALE] = locale
        return self.command(ReqMethod.GET, Uri.LAST_MODIFIED, kw)

    def commandGet(self, fileUri, locale, **kw):
        kw[Params.FILE_URI] = fileUri
        kw[Params.LOCALE] = locale
        if Params.RETRIEVAL_TYPE in kw and not kw[Params.RETRIEVAL_TYPE] in Params.allowedRetrievalTypes:
            raise "Not allowed value `%s` for parameter:%s try one of %s" % (
                kw[Params.RETRIEVAL_TYPE],
                Params.RETRIEVAL_TYPE,
                Params.allowedRetrievalTypes,
            )

        return self.command_raw(ReqMethod.POST, Uri.GET, kw)

    def commandDelete(self, fileUri, **kw):
        kw[Params.FILE_URI] = fileUri

        return self.command(ReqMethod.POST, Uri.DELETE, kw)

    def commandImport(self, uploadData, locale, **kw):
        kw[Params.FILE_URI] = uploadData.uri
        kw[Params.FILE_TYPE] = uploadData.type
        kw[Params.FILE_PATH] = uploadData.path + uploadData.name
        kw["file"] = uploadData.path + uploadData.name + ";type=text/plain"
        kw[Params.LOCALE] = locale
        self.addApiKeys(kw)

        return self.uploadMultipart(Uri.IMPORT, kw)

    def commandStatus(self, fileUri, locale, **kw):
        kw[Params.FILE_URI] = fileUri
        kw[Params.LOCALE] = locale

        return self.command(ReqMethod.POST, Uri.STATUS, kw)

    def commandRename(self, fileUri, newUri, **kw):
        kw[Params.FILE_URI] = fileUri
        kw[Params.FILE_URI_NEW] = newUri

        return self.command(ReqMethod.POST, Uri.RENAME, kw)
Example #41
0
 def __init__(self, host, apiKey, projectId, proxySettings=None):
     self.host = host
     self.apiKey = apiKey
     self.projectId = projectId
     self.proxySettings = proxySettings
     self.httpClient = HttpClient(host, proxySettings)
Example #42
0
File: api.py Project: redu/redupy
class Redu(object):

    def __init__(self, consumer_key, consumer_secret,
        pin=None, model_factory=None, base_url="http://redu.com.br/api/"):
        self.client = HttpClient(consumer_key, consumer_secret, pin)
        self.base_url = base_url
        self.model_factory = model_factory or ModelFactory

    def getAuthorizeUrl(self):
        return self.client.getAuthorizeUrl()

    def initClient(self, pin):
        self.client.initClient(pin)

    getMe = bind_api(path="me", mehtod="get", payload_type="user")

    getUser = bind_api(path="users/{0}", method="get", payload_type="user")

    getUserBySpace = bind_api(path="spaces/{0}/users", method="get",
        payload_type="user")

    getEnvironment = bind_api(path="environments/{0}", method="get",
        payload_type="environment")

    postEnvironment = bind_api(path="environments", method="post",
        payload_type="environment", payload_params=["name", "path", "initials",
        "description"])

    editEnvironment = bind_api(path="environments/{0}", method="put",
        send_type="environment", payload_params=["name", "path", "initials",
        "description"])

    deleteEnvironment = bind_api(path="environments/{0}", method="delete")

    getSubjectsBySpace = bind_api(path="spaces/{0}/subjects", method="get",
        payload_type="subject")

    getSubject = bind_api(path="subjects/{0}", method="get",
        payload_type="subject")

    getSpace = bind_api(path="spaces/{0}", method="get",
        payload_type="space")

    editSpace = bind_api(path="spaces/{0}", method="put",
        payload_params=['name', 'description'], send_type="space")

    postSpace = bind_api(path="courses/{0}/spaces", method="post",
        payload_type='space', payload_params=['name', 'description'])

    getSpaceByCourse = bind_api(path="courses/{0}/spaces", method="get",
        payload_type="space")

    deleteSpace = bind_api(path="spaces/{0}", method="delete")

    getStatus = bind_api(path="statuses/{0}", method="get",
        payload_type="status")

    getAnswers = bind_api(path="statuses/{0}/answers", method="get",
        payload_type="status")

    postAnswer = bind_api(path="statuses/{0}/answers", method="post",
        payload_type="status", payload_params=["text"])

    getStatusByUser = bind_api(path="users/{0}/statuses", method="get",
        payload_type="status", querry_params=["type", "page"])

    getTimelineByUser = bind_api(path="users/{0}/statuses/timeline",
        method="get", payload_type="status", querry_params=["type", "page"])

    postStatusUser = bind_api(path="users/{0}/statuses", method="post",
        payload_type="status", payload_params=["text"])

    getTimelineBySpace = bind_api(path="spaces/{0}/statuses/timeline",
        method="get", payload_type="status", querry_params=["type", "page"])

    getStatusBySpace = bind_api(path="spaces/{0}/statuses", method="get",
        payload_type="status", querry_params=["type", "page"])

    postStatusSpace = bind_api(path="spaces/{0}/statuses", method="post",
        payload_type="status", payload_params=["text"])

    getStatusByLecture = bind_api(path="lectures/{0}/statuses", method="get",
        payload_type="status", querry_params=["type", "page"])

    postStatusLecture = bind_api(path="lectures/{0}/statuses", method="post",
        payload_type="status", payload_params=["text"])

    deleteStatus = bind_api(path="statuses/{0}", method="delete")

    getCourse = bind_api(path="courses/{0}", method="get",
        payload_type="course")

    postCourse = bind_api(path="environments/{0}/courses", method="post",
        payload_type="course", payload_params=["name", "path", "description",
        "workload"])

    editCourse = bind_api(path="courses/{0}", method="put", send_type="course",
        payload_params=["name", "path", "description", "workload"])

    getCoursesByEnvironment = bind_api(path="environments/{0}/courses", method="get",
        payload_type="course")

    deleteCourse = bind_api(path="courses/{0}", method="delete")

    getEnrollment = bind_api(path="enrollments/{0}", method="get",
        payload_type="enrollment")

    postEnrollment = bind_api(path="courses/{0}/enrollments", method="post",
        payload_type="enrollment", payload_params=["email"])

    getEnrolmentsByCourse = bind_api(path="courses/{0}/enrollments",
        method="get", payload_type="enrollment")

    deleteEnrollment = bind_api(path="enrollments/{0}", method="delete")

    getChatsByUser = bind_api(path='users/{0}/chats', method='get',
        payload_type='chat')

    getChat = bind_api(path='chats/{0}', method='get', payload_type='chat')

    getChatMessagesByChat = bind_api(path='chats/{0}/chat_messages', method='get',
        payload_type='chat_message')

    getChatMessage = bind_api(path='chat_messages/{0}', method='get',
        payload_type='chat_message')
Example #43
0
class QiuTanSpider(object):
    def __init__(self):
        self.infourl = "http://live.win007.com/vbsxml/bfdata.js?r=007%s000"
        self.httpClient = HttpClient()
        self.tipmaxtimes = 3
        self.ballteammap = {}
        self.emails = ["*****@*****.**"]

    def getInfo(self):
        try:
            r = self.httpClient.request(self.infourl % int(time.time()),
                                        Method.GET,
                                        headers=self.getHeader(),
                                        formats="text",
                                        encoding="gbk")
            rlist = r.split("\r\n")
            strs = ""
            for i in rlist:
                if i.startswith("A"):
                    j = i.split("^")
                    if len(j) < 15:
                        continue
                    league = j[2]
                    teama = j[5]
                    teamb = j[8]
                    begintime = j[11]
                    scorea = j[14]
                    scoreb = j[15]
                    if self.caldifftime(begintime) and (int(scorea) +
                                                        int(scoreb)) >= 3:
                        count = self.add(teama + teamb)
                        if count < 2:
                            nowtime = time.strftime("%Y-%m-%d %H:%M:%S",
                                                    time.localtime())
                            strs = strs + "无界面服务:北京时间%s,%s联赛:%s队和%s队在开始比赛30分钟前进球数大于等于3\n" % (
                                nowtime, league, teama, teamb)
            if strs != "":
                self.writefile(strs)
                EmailUtil().send(strs, self.emails)
        except Exception as e:
            self.AutoCloseMessageBoxW("代码异常:" + str(e), 5)

    def getHeader(self):
        return {
            "Host":
            "live.win007.com",
            "Referer":
            "http://live.win007.com/",
            "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
        }

    def caldifftime(self, time2):
        nowtimestamp = int(time.time())
        now = time.localtime()
        format_time = time.strftime("%Y-%m-%d %H:%M:%S", now)
        timestr = format_time.split(" ")[0] + " " + time2
        ts = time.strptime(timestr, "%Y-%m-%d %H:%M")
        ts = int(time.mktime(ts))
        if (nowtimestamp - ts) > 0 and (nowtimestamp - ts) < 1800:
            return True
        else:
            return False

    def begin(self):
        while True:
            self.getInfo()
            time.sleep(60)

    def get(self, teamname):
        return self.ballteammap.get(teamname)

    def set(self, teamname, count):
        self.ballteammap[teamname] = count

    def add(self, teamname):
        count = self.get(teamname)
        if count is None:
            self.set(teamname, 1)
            return 1
        else:
            count = count + 1
            self.set(teamname, count)
            return count

    def test(self):
        MessageBox = ctypes.windll.user32.MessageBoxW
        MessageBox(None, 'Hello', 'Window title', 0)

    def worker(self, title, close_until_seconds):
        time.sleep(close_until_seconds)
        wd = ctypes.windll.user32.FindWindowW(0, title)
        ctypes.windll.user32.SendMessageW(wd, 0x0010, 0, 0)
        return

    def AutoCloseMessageBoxW(self, text, close_until_seconds):
        t = threading.Thread(target=self.worker,
                             args=("分数提醒", close_until_seconds))
        t.start()
        ctypes.windll.user32.MessageBoxW(0, text, "分数提醒", 0)

    def writefile(self, text):
        f = open("./历史提醒.txt", "a+")
        f.write(text)
        f.flush()
        f.close()
Example #44
0
import sys
import datetime
import time
import threading
import logging
import urllib
from HttpClient import HttpClient

reload(sys)
sys.setdefaultencoding("utf-8")

# CONFIGURATION FIELD
checkFrequency = 180
#check every k seconds
# STOP EDITING HERE
HttpClient_Ist = HttpClient()
UIN = 0
skey = ''
Referer = 'http://user.qzone.qq.com/'
QzoneLoginUrl = 'http://xui.ptlogin2.qq.com/cgi-bin/xlogin?proxy_url=http%3A//qzs.qq.com/qzone/v6/portal/proxy.html&daid=5&pt_qzone_sig=1&hide_title_bar=1&low_login=0&qlogin_auto_login=1&no_verifyimg=1&link_target=blank&appid=549000912&style=22&target=self&s_url=http%3A%2F%2Fqzs.qq.com%2Fqzone%2Fv5%2Floginsucc.html%3Fpara%3Dizone&pt_qr_app=%E6%89%8B%E6%9C%BAQQ%E7%A9%BA%E9%97%B4&pt_qr_link=http%3A//z.qzone.com/download.html&self_regurl=http%3A//qzs.qq.com/qzone/v6/reg/index.html&pt_qr_help_link=http%3A//z.qzone.com/download.html'

initTime = time.time()

logging.basicConfig(
    filename='log.log',
    level=logging.DEBUG,
    format=
    '%(asctime)s  %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    datefmt='%a, %d %b %Y %H:%M:%S')

Example #45
0
from HttpClient import HttpClient
import urllib
import random

url_login = '******'
url_downcode = 'https://ssl.ptlogin2.qq.com/ptqrshow?appid=501004106&e=0&l=M&s=5&d=72&v=4&t=%s' % (time.time()/10**10)
url_checkcode = 'https://ssl.ptlogin2.qq.com/ptqrlogin?webqq_type=10&remember_uin=1&login2qq=1&aid=501004106&'\
'u1=http%3A%2F%2Fw.qq.com%2Fproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&'\
'dumy=&fp=loginerroralert&mibao_css=m_webqq&t=undefined&g=1&js_type=0&js_ver=10158&login_sig=&'\
'pt_randsalt=0'

ClientID=53999199
PSessionID = ''
Referer = 'http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=2'

Client = HttpClient()

tulingkey = '6d7bdd3255fb1c940d265f6470b1b641'
FriendList = {}
ThreadList = []
def uin_to_account(tuin):
    # 如果消息的发送者的真实QQ号码不在FriendList中,则自动去取得真实的QQ号码并保存到缓存中
    if tuin not in FriendList:
        try:
            t=int(time.time())*1000
            # print 'http://s.web2.qq.com/api/get_friend_uin2?tuin={0}&type=1&vfwebqq={1}&t={2}'.format(tuin, QQ.VFWebQQ,t)
            info = json.loads(Client.Get(
                'http://s.web2.qq.com/api/get_friend_uin2?tuin={0}&type=1&vfwebqq={1}&t={2}'.format(tuin, VFWebQQ, t),
                Referer))
            # info = json.loads(session.get(
            #     'http://s.web2.qq.com/api/get_friend_uin2?tuin={0}&type=1&vfwebqq={1}&t={2}'.format(tuin, VFWebQQ, t),