Example #1
0
 def setupSession(self):
     if self._timeout is not None:
         self._config.setTimeoutIntervalForResource_(self._timeout)
     if self._cache is not None:
         self._config.setURLCache_(self._cache)
         self._config.setRequestCachePolicy_(self._requestCachePolicy)
     self._session = NSURLSession.sessionWithConfiguration_(self._config)
Example #2
0
File: gurl.py Project: zippyy/munki
    def start(self):
        '''Start the connection'''
        if not self.destination_path:
            self.log('No output file specified.')
            self.done = True
            return
        url = NSURL.URLWithString_(self.url)
        request = (
            NSMutableURLRequest.requestWithURL_cachePolicy_timeoutInterval_(
                url, NSURLRequestReloadIgnoringLocalCacheData,
                self.connection_timeout))
        if self.additional_headers:
            for header, value in self.additional_headers.items():
                request.setValue_forHTTPHeaderField_(value, header)
        # does the file already exist? See if we can resume a partial download
        if os.path.isfile(self.destination_path):
            stored_data = self.getStoredHeaders()
            if (self.can_resume and 'expected-length' in stored_data and
                ('last-modified' in stored_data or 'etag' in stored_data)):
                # we have a partial file and we're allowed to resume
                self.resume = True
                local_filesize = os.path.getsize(self.destination_path)
                byte_range = 'bytes=%s-' % local_filesize
                request.setValue_forHTTPHeaderField_(byte_range, 'Range')
        if self.download_only_if_changed and not self.resume:
            stored_data = self.cache_data or self.getStoredHeaders()
            if 'last-modified' in stored_data:
                request.setValue_forHTTPHeaderField_(
                    stored_data['last-modified'], 'if-modified-since')
            if 'etag' in stored_data:
                request.setValue_forHTTPHeaderField_(stored_data['etag'],
                                                     'if-none-match')
        if NSURLSESSION_AVAILABLE:
            configuration = (
                NSURLSessionConfiguration.defaultSessionConfiguration())

            # optional: ignore system http/https proxies (10.9+ only)
            if self.ignore_system_proxy is True:
                configuration.setConnectionProxyDictionary_({
                    kCFNetworkProxiesHTTPEnable:
                    False,
                    kCFNetworkProxiesHTTPSEnable:
                    False
                })

            # set minumum supported TLS protocol (defaults to TLS1)
            configuration.setTLSMinimumSupportedProtocol_(
                self.minimum_tls_protocol)

            self.session = (
                NSURLSession.sessionWithConfiguration_delegate_delegateQueue_(
                    configuration, self, None))
            self.task = self.session.dataTaskWithRequest_(request)
            self.task.resume()
        else:
            self.connection = NSURLConnection.alloc(
            ).initWithRequest_delegate_(request, self)
Example #3
0
    def send(
            self,
            request,  # type: PreparedRequest
            stream=False,  # type: bool
            timeout=None,  # type: Union[float, Tuple[float, float]]
            verify=True,  # type: bool
            cert=None,  # type: Any
            proxies=None  # type: dict
    ):
        # type: (...) -> Response

        self.configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration(
        )
        self.delegate = NSURLSessionAdapterDelegate.alloc().initWithAdapter_(
            self)
        self.delegate.credential = self.credential
        self.session = NSURLSession.sessionWithConfiguration_delegate_delegateQueue_(
            self.configuration,
            self.delegate,
            None,
        )

        nsrequest = build_request(request, timeout)
        self.verify = verify

        # TODO: Support all of this stuff.
        assert not stream
        assert not cert
        assert not proxies

        if request.method in ['PUT', 'POST'] and request.body is not None:
            # These verbs should usually be an upload task to send the correct request headers.
            task = self.session.uploadTaskWithRequest_fromData_(
                nsrequest, buffer(request.body))
        else:
            task = self.session.dataTaskWithRequest_(nsrequest)

        cookiestore = self.configuration.HTTPCookieStorage()

        task.resume()

        while not self.delegate.isDone():
            pass

        response = build_response(request, self.delegate, cookiestore)

        # if self.delegate.error is not None:
        #     raise self.delegate.error

        if self.delegate.SSLError is not None:
            code, message = self.delegate.SSLError
            raise SSLError('{}: {}'.format(code, message),
                           response=response,
                           request=request)

        return response
Example #4
0
 def _initialize_session(self):
     configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
     self._delegate = _RequestsDelegate.alloc().initWithAdapter_(self)
     self._session = (
         NSURLSession.sessionWithConfiguration_delegate_delegateQueue_(
             configuration,
             self._delegate,
             None,
         )
     )
Example #5
0
    def start(self):
        '''Start the connection'''
        if not self.destination_path:
            self.log('No output file specified.')
            self.done = True
            return
        url = NSURL.URLWithString_(self.url)
        request = (
            NSMutableURLRequest.requestWithURL_cachePolicy_timeoutInterval_(
                url, NSURLRequestReloadIgnoringLocalCacheData,
                self.connection_timeout))
        if self.additional_headers:
            for header, value in self.additional_headers.items():
                request.setValue_forHTTPHeaderField_(value, header)
        # does the file already exist? See if we can resume a partial download
        if os.path.isfile(self.destination_path):
            stored_data = self.getStoredHeaders()
            if (self.can_resume and 'expected-length' in stored_data and
                    ('last-modified' in stored_data or 'etag' in stored_data)):
                # we have a partial file and we're allowed to resume
                self.resume = True
                local_filesize = os.path.getsize(self.destination_path)
                byte_range = 'bytes=%s-' % local_filesize
                request.setValue_forHTTPHeaderField_(byte_range, 'Range')
        if self.download_only_if_changed and not self.resume:
            stored_data = self.cache_data or self.getStoredHeaders()
            if 'last-modified' in stored_data:
                request.setValue_forHTTPHeaderField_(
                    stored_data['last-modified'], 'if-modified-since')
            if 'etag' in stored_data:
                request.setValue_forHTTPHeaderField_(
                    stored_data['etag'], 'if-none-match')
        if NSURLSESSION_AVAILABLE:
            configuration = (
                NSURLSessionConfiguration.defaultSessionConfiguration())

            # optional: ignore system http/https proxies (10.9+ only)
            if self.ignore_system_proxy is True:
                configuration.setConnectionProxyDictionary_(
                    {kCFNetworkProxiesHTTPEnable: False,
                     kCFNetworkProxiesHTTPSEnable: False})

            # set minumum supported TLS protocol (defaults to TLS1)
            configuration.setTLSMinimumSupportedProtocol_(
                self.minimum_tls_protocol)

            self.session = (
                NSURLSession.sessionWithConfiguration_delegate_delegateQueue_(
                    configuration, self, None))
            self.task = self.session.dataTaskWithRequest_(request)
            self.task.resume()
        else:
            self.connection = NSURLConnection.alloc().initWithRequest_delegate_(
                request, self)
Example #6
0
 def _initialize_session(self):
     """Set up the NSURLSessionConfiguration"""
     configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
     self._delegate = RequestsNSURLSessionDelegate.alloc().initWithAdapter_(
         self)
     self._session = (
         NSURLSession.sessionWithConfiguration_delegate_delegateQueue_(
             configuration,
             self._delegate,
             None,
         ))