def _send_notify(pushbulletapi, message):
    http_handler = HTTPSConnection("api.pushbullet.com")
    
    if not pushbulletapi:
        pushbulletapi = autosub.PUSHBULLETAPI

    mydata = {'type': 'note'.encode('utf-8'),
            'title': 'Auto-Sub'.encode('utf-8'),
            'body': message.encode('utf-8') }

    try:
        http_handler.request('POST', '/v2/pushes', body=json.dumps(mydata),
                            headers={'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % pushbulletapi})  
    except:
        log.error("Pushbullet: notification failed.")
        return False  

    response = http_handler.getresponse()
    request_status = response.status

    if request_status == 200:
            log.info("Pushbullet: notification sent.")
            return True
    elif request_status == 401: 
            log.error("Pushbullet: No valid access token provided")
            return False
    elif request_status == 403:
            log.error("Pushbullet: The access token is not valid for that request")
            return False
    else:
            log.error("Pushbullet: notification failed with error")
            return False
예제 #2
0
 def test_no_content_length(self):
     # "The presence of a message-body in a request is signaled by the
     # inclusion of a Content-Length or Transfer-Encoding header field in
     # the request's message-headers."
     # 
     # Send a message with neither header and no body. Even though
     # the request is of method POST, this should be OK because we set
     # request.process_request_body to False for our handler.
     if self.scheme == "https":
         c = HTTPSConnection('%s:%s' % (self.interface(), self.PORT))
     else:
         c = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
     c.request("POST", "/no_body")
     response = c.getresponse()
     self.body = response.fp.read()
     self.status = str(response.status)
     self.assertStatus(200)
     self.assertBody('Hello world!')
     
     # Now send a message that has no Content-Length, but does send a body.
     # Verify that CP times out the socket and responds
     # with 411 Length Required.
     if self.scheme == "https":
         c = HTTPSConnection('%s:%s' % (self.interface(), self.PORT))
     else:
         c = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
     c.request("POST", "/")
     response = c.getresponse()
     self.body = response.fp.read()
     self.status = str(response.status)
     self.assertStatus(411)
예제 #3
0
파일: CMSWeb.py 프로젝트: dmitrijus/cms-bot
class CMSWeb (object):
  def __init__ (self):
    self.URL_CMSWEB_BASE='cmsweb.cern.ch'
    self.URL_PHEDEX_BLOCKREPLICAS='/phedex/datasvc/json/prod/blockreplicas'
    self.URL_DBS_DATASETS='/dbs/prod/global/DBSReader/datasets'
    self.URL_DBS_FILES='/dbs/prod/global/DBSReader/files'
    self.URL_DBS_RUNS='/dbs/prod/global/DBSReader/runs'
    self.URL_DBS_BLOCKS='/dbs/prod/global/DBSReader/blocks'
    self.conn = HTTPSConnection(self.URL_CMSWEB_BASE, cert_file='/tmp/x509up_u{0}'.format(getuid()),  timeout=30)
    self.reply_cache = {}
    self.last_result = ""
    self.errors = 0

  def __del__(self): self.conn.close ()

  def get_cmsweb_data(self, url):
    self.last_result = url
    if url in self.reply_cache: return True, self.reply_cache[url]
    msg =""
    try:
      self.conn.request('GET', url)
      msg = self.conn.getresponse()
      if msg.status!=200:
        self.errors = self.errors + 1
        print 'Result: {0} {1}: {2}'.format(msg.status, msg.reason, url)
        return False, {}
      self.reply_cache[url]=json.loads(msg.read())
      return True, self.reply_cache[url]
    except Exception, e:
      print "Error:", e, url
      self.errors = self.errors + 1
      return False, {}
예제 #4
0
    def notify(self, message, event, module=None):
        if not mylar.PROWL_ENABLED:
            return

        if module is None:
            module = ''
        module += '[NOTIFIER]'

        http_handler = HTTPSConnection("api.prowlapp.com")
                                                
        data = {'apikey': mylar.PROWL_KEYS,
                'application': 'Mylar',
                'event': event,
                'description': message.encode("utf-8"),
                'priority': mylar.PROWL_PRIORITY }

        http_handler.request("POST",
                                "/publicapi/add",
                                headers = {'Content-type': "application/x-www-form-urlencoded"},
                                body = urlencode(data))
        response = http_handler.getresponse()
        request_status = response.status

        if request_status == 200:
                logger.info(module + ' Prowl notifications sent.')
                return True
        elif request_status == 401: 
                logger.info(module + ' Prowl auth failed: %s' % response.reason)
                return False
        else:
                logger.info(module + ' Prowl notification failed.')
                return False
예제 #5
0
def send(token, title, **kwargs):
    """
    Site: https://boxcar.io/
    API: http://help.boxcar.io/knowledgebase/topics/48115-boxcar-api
    Desc: Best app for system administrators
    """
    headers = {
        "Content-type": "application/x-www-form-urlencoded",
        "User-Agent": "DBMail/%s" % get_version(),
    }

    data = {
        "user_credentials": token,
        "notification[title]": from_unicode(title),
        "notification[sound]": "notifier-2"
    }

    for k, v in kwargs.items():
        data['notification[%s]' % k] = from_unicode(v)

    http = HTTPSConnection(kwargs.pop("api_url", "new.boxcar.io"))
    http.request(
        "POST", "/api/notifications",
        headers=headers,
        body=urlencode(data))
    response = http.getresponse()

    if response.status != 201:
        raise BoxcarError(response.reason)
    return True
예제 #6
0
def _send_notify(pushalotapi, message):
    http_handler = HTTPSConnection("pushalot.com")
    
    if not pushalotapi:
        pushalotapi = autosub.PUSHALOTAPI

    data = {'AuthorizationToken': pushalotapi,
            'Title': "Auto-Sub",
            'Body': message.encode('utf-8') }
    
    try:
        http_handler.request("POST",
                                "/api/sendmessage",
                                headers = {'Content-type': "application/x-www-form-urlencoded"},
                                body = urlencode(data))
    except:
        log.error("Pushalot: notification failed.")
        return False
    
    response = http_handler.getresponse()
    request_status = response.status

    if request_status == 200:
            log.info("Pushalot: notification sent.")
            return True
    elif request_status == 410: 
            log.error("Pushalot: Auth failed %s" % response.reason)
            return False
    else:
            log.error("Pushalot: notification failed.")
            return False
예제 #7
0
def USCWebGISGeocoder(address, locality, region, zipcode, apiKey):
  uscwebgisUrl = "/Services/Geocode/WebService/GeocoderWebServiceHttpNonParsed_V02_96.aspx?"
  queryParams = {
    'zip' : zipcode,
    'apiKey' : apiKey,
    'version' : '2.96',
    'format' : 'csv',
  }

  if not address is None:
    queryParams['streetAddress'] = address

  if not locality is None:
    queryParams['city'] = locality

  if not region is None:
    queryParams['state'] = region

  requestUrl = uscwebgisUrl + urlencode(queryParams)


  conn = HTTPSConnection('webgis.usc.edu')
  geocodeRequest = conn.request('GET', requestUrl)
  response = conn.getresponse()
  if response.status != 200:
    raise LocationNotFoundError('Status code was not 200')

  parsedData = response.read().split(',')
  if parsedData[2] != "200":
    raise LocationNotFoundError('results contained error')

  return (float(parsedData[3]) , float(parsedData[4]))
예제 #8
0
파일: pushalot.py 프로젝트: afctim/SiCKRAGE
    def _sendPushalot(self, pushalot_authorizationtoken=None, event=None, message=None, force=False):

        if not sickrage.srCore.srConfig.USE_PUSHALOT and not force:
            return False

        sickrage.srCore.srLogger.debug("Pushalot event: " + event)
        sickrage.srCore.srLogger.debug("Pushalot message: " + message)
        sickrage.srCore.srLogger.debug("Pushalot api: " + pushalot_authorizationtoken)

        http_handler = HTTPSConnection("pushalot.com")

        data = {'AuthorizationToken': pushalot_authorizationtoken,
                'Title': event.encode('utf-8'),
                'Body': message.encode('utf-8')}

        try:
            http_handler.request("POST",
                                 "/api/sendmessage",
                                 headers={'Content-type': "application/x-www-form-urlencoded"},
                                 body=urlencode(data))
        except (SSLError, HTTPException, socket.error):
            sickrage.srCore.srLogger.error("Pushalot notification failed.")
            return False
        response = http_handler.getresponse()
        request_status = response.status

        if request_status == 200:
            sickrage.srCore.srLogger.debug("Pushalot notifications sent.")
            return True
        elif request_status == 410:
            sickrage.srCore.srLogger.error("Pushalot auth failed: %s" % response.reason)
            return False
        else:
            sickrage.srCore.srLogger.error("Pushalot notification failed.")
            return False
예제 #9
0
 def _load_token(cls):
     """
     Загружает новый токен.
     @return: string
     """
     logger.debug("loading token")
     logger.warning("looks like you do not have token in your settings_local.py yet")
     logger.warning("please get an auth code from %s", cls._get_auth_url())
     logger.warning("it is better to set TOKEN variable on settings_local.py but you can just put in it here")
     logger.warning("see README for more information")
     auth_code = raw_input()
     logger.debug("auth code is %s", auth_code)
     connection = HTTPSConnection("oauth.yandex.ru")
     body = urlencode(
         {
             "grant_type": "authorization_code",
             "client_id": CLIENT_ID,
             "client_secret": CLIENT_SECRET,
             "code": auth_code,
         }
     )
     connection.request("POST", "/token", body)
     response = connection.getresponse().read()
     result = json.loads(response)
     token = result["access_token"]
     logger.debug("token loaded: %s", token)
     return token
예제 #10
0
파일: views.py 프로젝트: We-Neusoft/We
def signin(request):
    result = {'nav_dreamspark': 'active'}

    if request.method == 'POST':
        form = SigninForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            domain = form.cleaned_data['domain']
            password = form.cleaned_data['password']

            user = authenticate(username=username, domain=domain, password=password)

            if user:
                try:
                    onthehub = HTTPSConnection('e5.onthehub.com')
                    onthehub.request('GET', '/WebStore/Security/AuthenticateUser.aspx?account=' + DREAMSPARK_ACCOUNT + '&username='******'&key=' + DREAMSPARK_KEY + '&academic_statuses=' + ('students' if domain == '@nou.com.cn' else 'faculty,staff') + '&email=' + user.email + '&last_name=' + user.last_name + '&first_name=' + user.first_name)
                    response = onthehub.getresponse()
                    if response.status == 200:
                        return HttpResponseRedirect(response.read())
                    else:
                        result['error'] = '与 DreamSpark 通信异常,请稍后重试'
                except:
                    result['error'] = '与 DreamSpark 通信超时,请稍后重试'
            else:
                result['error'] = '邮箱地址或密码错误,请重新输入'

    result.update(csrf(request))

    return render_to_response('dreamspark/signin.html', result)
    def assertions(self):

        # Write the cert to disk
        with open('https-forwarder-test-cert', 'w') as f:
            f.write(self.ext_inputs['ssl_cert'])

        ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
        ssl_context.verify_mode = ssl.CERT_REQUIRED
        ssl_context.load_verify_locations('https-forwarder-test-cert')

        for i in range(40):
            sleep(10)

            try:
                http = HTTPSConnection(
                        self.outputs['ip_ip'], context=ssl_context)

                # If the certificate isn't the one we provided
                # this step will fail...
                http.request('GET', '/')
                text = http.getresponse().read()

                self.assertEqual(
                        self.outputs['vm_name'],
                        text.strip())
            except (ssl.SSLError, AssertionError) as e:
                print('attempt {}/40: {}'.format(i, e))
            else:
                break
        else:
            self.fail('tried too many times to get the page')
예제 #12
0
    def oauth_callback(self, params):

        if 'code' not in params:
            return None

        conn = HTTPSConnection("accounts.google.com")
        body = tools.encode_params({
            "grant_type":"authorization_code",
            "code":params['code'],
            "client_id":secrets.GMAIL_CLIENT_ID,
            "client_secret":secrets.GMAIL_CLIENT_SECRET,
            "redirect_uri":secrets.BASE_REDIRECT_URL + "gmail",
        })
        headers = {
            "Content-Type":"application/x-www-form-urlencoded",
        }
        conn.request("POST", "/o/oauth2/token", body, headers)

        resp = conn.getresponse()
        try:
            self.token = json.loads(resp.read())['access_token']
            self.is_auth = True
        except (KeyError, ValueError):
            return None

        conn.close()

        conn = HTTPSConnection("www.googleapis.com")
        conn.request("GET","/oauth2/v1/tokeninfo?alt=json&access_token="+self.token,"",{})
        resp = conn.getresponse()
        self.username = json.loads(resp.read())['email']
예제 #13
0
파일: nessus.py 프로젝트: maaren/pynessus
    def _request(self, method, target, params, headers=None):
        """
        Send an HTTP request.
        Params:
            method(string): HTTP method (i.e. GET, POST, PUT, DELETE, HEAD)
            target(string): target path (i.e. /schedule/new)
            params(string): HTTP parameters
            headers(array): HTTP headers
        Returns:
            Response body if successful, None otherwise.
        """
        try:
            if self._connection is None:
                self._connection = HTTPSConnection(self._url, self._port)
            self._connection.request(method, target, params, self._headers if headers is None else headers)
        except CannotSendRequest:
            self._connection = HTTPSConnection(self._url, self._port)
            self.login(self._user)
            self._request(method, target, params, self._headers)
        except ImproperConnectionState:
            self._connection = HTTPSConnection(self._url, self._port)
            self.login(self._user)
            self._request(method, target, params, self._headers)
        response = self._connection.getresponse()

        return response.read()
예제 #14
0
    def notify(self, message, event):
        if not headphones.CONFIG.PUSHBULLET_ENABLED:
            return

        http_handler = HTTPSConnection("api.pushbullet.com")

        data = {"type": "note", "title": "Headphones", "body": message.encode("utf-8")}

        http_handler.request(
            "POST",
            "/v2/pushes",
            headers={
                "Content-type": "application/json",
                "Authorization": "Basic %s" % base64.b64encode(headphones.CONFIG.PUSHBULLET_APIKEY + ":"),
            },
            body=json.dumps(data),
        )
        response = http_handler.getresponse()
        request_status = response.status
        logger.debug(u"PushBullet response status: %r" % request_status)
        logger.debug(u"PushBullet response headers: %r" % response.getheaders())
        logger.debug(u"PushBullet response body: %r" % response.read())

        if request_status == 200:
            logger.info(u"PushBullet notifications sent.")
            return True
        elif request_status >= 400 and request_status < 500:
            logger.info(u"PushBullet request failed: %s" % response.reason)
            return False
        else:
            logger.info(u"PushBullet notification failed serverside.")
            return False
예제 #15
0
    def notify(self, message, event):
        if not headphones.PUSHBULLET_ENABLED:
            return

        http_handler = HTTPSConnection("api.pushbullet.com")
                                                
        data = {'device_iden': headphones.PUSHBULLET_DEVICEID,
                'type': "note",
                'title': "Headphones",
                'body': message.encode("utf-8") }

        http_handler.request("POST",
                                "/api/pushes",
                                headers = {'Content-type': "application/x-www-form-urlencoded",
                                            'Authorization' : 'Basic %s' % base64.b64encode(headphones.PUSHBULLET_APIKEY + ":") },
                                body = urlencode(data))
        response = http_handler.getresponse()
        request_status = response.status
        logger.debug(u"PushBullet response status: %r" % request_status)
        logger.debug(u"PushBullet response headers: %r" % response.getheaders())
        logger.debug(u"PushBullet response body: %r" % response.read())

        if request_status == 200:
                logger.info(u"PushBullet notifications sent.")
                return True
        elif request_status >= 400 and request_status < 500: 
                logger.info(u"PushBullet request failed: %s" % response.reason)
                return False
        else:
                logger.info(u"PushBullet notification failed serverside.")
                return False
예제 #16
0
파일: base.py 프로젝트: radaniba/jcvi
def pushover(message, token, user, title="JCVI: Job Monitor", \
        priority=0, timestamp=None):
    """
    pushover.net python API

    <https://pushover.net/faq#library-python>
    """
    assert -1 <= priority <= 2, \
            "Priority should be an int() between -1 and 2"

    if timestamp == None:
        from time import time
        timestamp = int(time())

    retry, expire = (300, 3600) if priority == 2 \
            else (None, None)

    conn = HTTPSConnection("api.pushover.net:443")
    conn.request("POST", "/1/messages.json",
      urlencode({
          "token": token,
          "user": user,
          "message": message,
          "title": title,
          "priority": priority,
          "timestamp": timestamp,
          "retry": retry,
          "expire": expire,
      }), { "Content-type": "application/x-www-form-urlencoded" })
    conn.getresponse()
예제 #17
0
    def notify(self, message="", data={}, listener=None):
        if self.isDisabled():
            return

        http_handler = HTTPSConnection("api.prowlapp.com")

        data = {
            "apikey": self.conf("api_key"),
            "application": self.default_title,
            "description": toUnicode(message),
            "priority": self.conf("priority"),
        }

        http_handler.request(
            "POST",
            "/publicapi/add",
            headers={"Content-type": "application/x-www-form-urlencoded"},
            body=tryUrlencode(data),
        )
        response = http_handler.getresponse()
        request_status = response.status

        if request_status == 200:
            log.info("Prowl notifications sent.")
            return True
        elif request_status == 401:
            log.error("Prowl auth failed: %s", response.reason)
            return False
        else:
            log.error("Prowl notification failed.")
            return False
예제 #18
0
    def _get_signin_token(self, creds):
        """
        GET the generated Signin Token from the federation endpoint

        :param creds: credentials to pass to the federation endpoint
        :type creds: dict
        :return: signin token returned by the federation endpoint
        :rtype: str
        """
        host = 'signin.aws.amazon.com'
        req_path = 'https://signin.aws.amazon.com/federation' \
                   '?Action=getSigninToken' \
                   '&Session=%s' % quote_plus(json.dumps(creds))
        logger.debug('HTTPS GET request to %s: %s', host, req_path)
        conn = HTTPSConnection(host, 443)
        conn.request('GET', req_path)
        resp = conn.getresponse()
        logger.debug('Response: HTTP %s %s', resp.status, resp.reason)
        logger.debug('Headers: %s', resp.getheaders())
        body = resp.read()
        logger.debug('Body: %s', body.strip())
        if resp.status != 200:
            logger.critical('AWS Federation endpoint responded HTTP %s %s: %s',
                            resp.status, resp.reason, body)
            raise RuntimeError('Error obtaining console signin credentials.')
        try:
            b = json.loads(body)['SigninToken']
        except Exception:
            logger.critical(
                'AWS Federation endpoint returned an invalid response: %s',
                body
            )
            raise RuntimeError('Invalid response from AWS Federation endpoint.')
        return b
예제 #19
0
    def notify(self, message, event):
        if not headphones.PUSHOVER_ENABLED:
            return

        http_handler = HTTPSConnection("api.pushover.net")
                                                
        data = {'token': self.application_token, 
                'user': headphones.PUSHOVER_KEYS,
                'title': event,
                'message': message.encode("utf-8"),
                'priority': headphones.PUSHOVER_PRIORITY }

        http_handler.request("POST",
                                "/1/messages.json",
                                headers = {'Content-type': "application/x-www-form-urlencoded"},
                                body = urlencode(data))
        response = http_handler.getresponse()
        request_status = response.status
        logger.debug(u"Pushover response status: %r" % request_status)
        logger.debug(u"Pushover response headers: %r" % response.getheaders())
        logger.debug(u"Pushover response body: %r" % response.read())

        if request_status == 200:
                logger.info(u"Pushover notifications sent.")
                return True
        elif request_status >= 400 and request_status < 500: 
                logger.info(u"Pushover request failed: %s" % response.reason)
                return False
        else:
                logger.info(u"Pushover notification failed.")
                return False
예제 #20
0
def getRemoteDBModifiedTS():
    """
    Performs a HEAD request to get the Last-Modified date-time
    of a database dump file and parses it into a UNIX timestamp.
    """
    debug_msg = 'Unable to get timestamp of remote database dump - {0}'
    logging.info("Getting timestamp of database dump at '%s'", HOST + PATH)
    try:
        # Removing the scheme from the URL
        conn = HTTPSConnection(HOST[8:], timeout=TIMEOUT)
        conn.request('HEAD', PATH)
    except gaierror as e:
        logging.debug(
            debug_msg.format(
                "Cannot connect to '%s', error: %s"),
            HOST + PATH, e)
        exit(1)

    rsp = conn.getresponse()

    if rsp.status != 200:
        logging.debug(
            debug_msg.format('Server responded with: %d %s'), rsp.status,
            rsp.reason)
        exit(1)

    last_modified = rsp.getheader('last-modified', None)
    if last_modified is None:
        logging.debug(debug_msg.format(
            'Response doesnt include Last-Modified Header'))
        exit(1)

    last_m_dt = datetime.strptime(
        last_modified.split(', ')[1], '%d %b %Y %H:%M:%S %Z')
    return timegm(last_m_dt.timetuple())
예제 #21
0
    def notify(self, message = '', data = {}, listener = None):

        http_handler = HTTPSConnection("api.pushover.net:443")

        data = {
            'user': self.conf('user_key'),
            'token': self.app_token,
            'message': toUnicode(message),
            'priority': self.conf('priority')
        }

        http_handler.request('POST',
            "/1/messages.json",
            headers = {'Content-type': 'application/x-www-form-urlencoded'},
            body = tryUrlencode(data)
        )

        response = http_handler.getresponse()
        request_status = response.status

        if request_status == 200:
            log.info('Pushover notifications sent.')
            return True
        elif request_status == 401:
            log.error('Pushover auth failed: %s', response.reason)
            return False
        else:
            log.error('Pushover notification failed.')
            return False
예제 #22
0
    def notify(self, message, event):
        if not headphones.CONFIG.PROWL_ENABLED:
            return

        http_handler = HTTPSConnection("api.prowlapp.com")

        data = {'apikey': headphones.CONFIG.PROWL_KEYS,
                'application': 'Headphones',
                'event': event,
                'description': message.encode("utf-8"),
                'priority': headphones.CONFIG.PROWL_PRIORITY}

        http_handler.request("POST",
                             "/publicapi/add",
                             headers={
                                 'Content-type':
                                     "application/x-www-form-urlencoded"},
                             body=urlencode(data))
        response = http_handler.getresponse()
        request_status = response.status

        if request_status == 200:
            logger.info(u"Prowl notifications sent.")
            return True
        elif request_status == 401:
            logger.info(u"Prowl auth failed: %s" % response.reason)
            return False
        else:
            logger.info(u"Prowl notification failed.")
            return False
예제 #23
0
파일: notifiers.py 프로젝트: nekoserv/mylar
    def notify(self, message, event):
        if not mylar.PUSHOVER_ENABLED:
            return

        http_handler = HTTPSConnection("api.pushover.net:443")

        data = {
            "token": mylar.PUSHOVER_APIKEY,
            "user": mylar.PUSHOVER_USERKEY,
            "message": message.encode("utf-8"),
            "title": event,
            "priority": mylar.PUSHOVER_PRIORITY,
        }

        http_handler.request(
            "POST",
            "/1/messages.json",
            body=urlencode(data),
            headers={"Content-type": "application/x-www-form-urlencoded"},
        )
        response = http_handler.getresponse()
        request_status = response.status

        if request_status == 200:
            logger.info(u"Pushover notifications sent.")
            return True
        elif request_status == 401:
            logger.info(u"Pushover auth failed: %s" % response.reason)
            return False
        else:
            logger.info(u"Pushover notification failed.")
            return False
예제 #24
0
    def notify(self, message, event, module=None):
        if not mylar.PUSHOVER_ENABLED:
            return
        if module is None:
            module = ''
        module += '[NOTIFIER]'

        http_handler = HTTPSConnection("api.pushover.net:443")
                                                
        data = {'token': mylar.PUSHOVER_APIKEY,
                'user': mylar.PUSHOVER_USERKEY,
                'message': message.encode("utf-8"),
                'title': event,
                'priority': mylar.PUSHOVER_PRIORITY }

        http_handler.request("POST",
                                "/1/messages.json",
                                body = urlencode(data),
                                headers = {'Content-type': "application/x-www-form-urlencoded"}
                                )
        response = http_handler.getresponse()
        request_status = response.status

        if request_status == 200:
                logger.info(module + ' Pushover notifications sent.')
                return True
        elif request_status == 401:
                logger.info(module + 'Pushover auth failed: %s' % response.reason)
                return False
        else:
                logger.info(module + ' Pushover notification failed.')
                return False
예제 #25
0
파일: notifiers.py 프로젝트: nekoserv/mylar
    def notify(self, message, event):
        if not mylar.PROWL_ENABLED:
            return

        http_handler = HTTPSConnection("api.prowlapp.com")

        data = {
            "apikey": mylar.PROWL_KEYS,
            "application": "Mylar",
            "event": event,
            "description": message.encode("utf-8"),
            "priority": mylar.PROWL_PRIORITY,
        }

        http_handler.request(
            "POST",
            "/publicapi/add",
            headers={"Content-type": "application/x-www-form-urlencoded"},
            body=urlencode(data),
        )
        response = http_handler.getresponse()
        request_status = response.status

        if request_status == 200:
            logger.info(u"Prowl notifications sent.")
            return True
        elif request_status == 401:
            logger.info(u"Prowl auth failed: %s" % response.reason)
            return False
        else:
            logger.info(u"Prowl notification failed.")
            return False
예제 #26
0
def send(hook_url, message, **kwargs):
    headers = {
        "Content-type": "application/json"
    }

    http_key = kwargs.pop("http_key", None)
    if not http_key and hasattr(settings, 'HTTP_KEY'):
        http_key = settings.HTTP_KEY
    headers["Authorization"] = "key={}".format(http_key)

    kwargs["msg"] = message

    up = urlparse(hook_url)
    if up.scheme == 'https':
        http = HTTPSConnection(up.netloc)
    else:
        http = HTTPConnection(up.netloc)

    http.request(
        "POST", up.path,
        headers=headers,
        body=dumps(kwargs))
    response = http.getresponse()

    if response.status != 200:
        raise HTTPError(response.reason)
    return True
예제 #27
0
    def notify(self, message = '', data = {}):
        if self.isDisabled(): return

        http_handler = HTTPSConnection('api.prowlapp.com')

        data = {
            'apikey': self.conf('api_key'),
            'application': self.default_title,
            'description': toUnicode(message),
            'priority': self.conf('priority'),
        }

        http_handler.request('POST',
            '/publicapi/add',
            headers = {'Content-type': 'application/x-www-form-urlencoded'},
            body = urlencode(data)
        )
        response = http_handler.getresponse()
        request_status = response.status

        if request_status == 200:
            log.info('Prowl notifications sent.')
            return True
        elif request_status == 401:
            log.error('Prowl auth failed: %s' % response.reason)
            return False
        else:
            log.error('Prowl notification failed.')
            return False
예제 #28
0
    def _probe_geonode_wms(self, raw_url):
        url = urlsplit(raw_url)

        if url.scheme == 'https':
            conn = HTTPSConnection(url.hostname, url.port)
        else:
            conn = HTTPConnection(url.hostname, url.port)
        conn.request('GET', '/api/ows_endpoints/', '', {})
        response = conn.getresponse()
        content = response.read()
        status = response.status
        content_type = response.getheader("Content-Type", "text/plain")

        # NEW-style OWS Enabled GeoNode
        if status == 200 and 'application/json' == content_type:
            try:
                _json_obj = json.loads(content)
                if 'data' in _json_obj:
                    data = _json_obj['data']
                    for ows_endpoint in data:
                        if 'OGC:OWS' == ows_endpoint['type']:
                            return ows_endpoint['url'] + '?' + url.query
            except BaseException:
                pass

        # OLD-style not OWS Enabled GeoNode
        _url = "%s://%s/geoserver/ows" % (url.scheme, url.netloc)
        return _url
예제 #29
0
파일: __init__.py 프로젝트: Epi10/pyngdom
    def request(self, method, endpoint, headers=None, **params):

        url = "https://api.pingdom.com/api/{version}/{endpoint}".format(
            **dict(
                username=self.username, password=self.password,
                version=self.version, endpoint=endpoint
            )
        )

        if headers is None:
            headers = dict()

        if 'Account-Email' not in headers:
            headers['Account-Email'] = self.account
        if 'App-Key' not in headers:
            headers['App-Key'] = self.apikey
        if 'Content-Type' not in headers:
            headers['Content-Type'] = 'application/json'
        if 'Authorization' not in headers:
            headers['Authorization'] = 'Basic %s' % base64.encodestring(
                "{username}:{password}".format(username=self.username, password=self.password)
            )

        conn = HTTPSConnection('api.pingdom.com', context=ctx)
        conn.request(
            method,
            "/api/{version}/{endpoint}".format(version=self.version, endpoint=endpoint),
            headers=headers
        )

        response = conn.getresponse()
        body = response.read()
        return json.loads(body)
예제 #30
0
 def connect(self):
     """
     Override the connect() function to intercept calls to certain
     host/ports.
     
     If no app at host/port has been registered for interception then 
     a normal HTTPSConnection is made.
     """
     if debuglevel:
         sys.stderr.write('connect: %s, %s\n' % (self.host, self.port,))
                          
     try:
         (app, script_name) = self.get_app(self.host, self.port)
         if app:
             if debuglevel:
                 sys.stderr.write('INTERCEPTING call to %s:%s\n' % \
                                  (self.host, self.port,))
             self.sock = wsgi_fake_socket(app, self.host, self.port,
                                          script_name)
         else:
             HTTPSConnection.connect(self)
             
     except Exception, e:
         if debuglevel:              # intercept & print out tracebacks
             traceback.print_exc()
         raise
예제 #31
0
 def fetch_response(self, request):
     """Executes request and fetchs service response"""
     connection = HTTPSConnection(self.SERVER_URL)
     connection.request(request.method.upper(), request.to_url())
     return connection.getresponse().read()