def process_url(self, url): if isinstance(url, NSURL): url = str(url) if self._quote_url_path: url = self.quote_url_path(url) if self._force_https: url = self.http2https_url(url) return NSURL.URLWithString_(url)
def dropEvent(self, e): if op_sys == 'Darwin': fnames = [str(NSURL.URLWithString_(str(url.toString())).filePathURL().path()) for url in e.mimeData().urls()] else: fnames = e.mimeData().urls() e.accept() self.openfiles(fnames)
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)
def viewDidLoad(self): super().viewDidLoad() request = NSURLRequest.requestWithURL_cachePolicy_timeoutInterval_( NSURL.URLWithString_(self.url), NSURLRequestReloadIgnoringLocalCacheData, 3, ) self.webView.loadRequest_(request)
def startLoading(self): self.loading = True self.setTitle() delimiter = '&' if '?' in self.screensharing_url else '?' url = '%s%sfit=1' % ( self.screensharing_url, delimiter ) if self.screensharing_fit_window else self.screensharing_url url = NSURL.URLWithString_(url) request = NSURLRequest.requestWithURL_cachePolicy_timeoutInterval_( url, NSURLRequestReloadIgnoringLocalAndRemoteCacheData, 15) self.webView.mainFrame().loadRequest_(request)
def _playsoundOSX(sound): from AppKit import NSSound from Foundation import NSURL from time import sleep url = NSURL.URLWithString_(sound) nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True) if not nssound: raise IOError("Unable to load sound named: " + sound) nssound.play()
def dropEvent(self, e): for url in e.mimeData().urls(): if op_sys == 'Darwin': fname = str( NSURL.URLWithString_(str( url.toString())).filePathURL().path()) else: fname = str(url.toLocalFile()) if os.path.isfile(fname): msg.logMessage(fname, msg.DEBUG) self.openfiles([fname]) e.accept()
def __init__(self, sound): self.sound = sound if '://' not in self.sound: if not self.sound.startswith('/'): from os import getcwd self.sound = getcwd() + '/' + self.sound self.sound = 'file://' + self.sound url = NSURL.URLWithString_(self.sound) self.nssound = NSSound.alloc().initWithContentsOfURL_byReference_( url, True) if not self.nssound: raise IOError('Unable to load sound named: ' + self.sound)
def fetch_remote_image(self, url, fallback_data=None): if self.item is None: return if fallback_data is not None: self.load_remote_image(url, None, fallback_data) if url.scheme() in ('http', 'https'): path = url.path(QtCore.QUrl.FullyEncoded) if url.hasQuery(): path += '?' + url.query(QtCore.QUrl.FullyEncoded) if url.scheme() == 'https': port = 443 else: port = 80 self.tagger.xmlws.get(str(url.encodedHost()), url.port(port), str(path), partial(self.on_remote_image_fetched, url, fallback_data=fallback_data), xml=False, priority=True, important=True) elif url.scheme() == 'file': log.debug("Dropped the URL: %r", url.toString(QtCore.QUrl.RemoveUserInfo)) if sys.platform == 'darwin' and unicode( url.path()).startswith('/.file/id='): # Workaround for https://bugreports.qt.io/browse/QTBUG-40449 # OSX Urls follow the NSURL scheme and need to be converted if NSURL_IMPORTED: path = os.path.normpath( os.path.realpath( unicode( NSURL.URLWithString_(str(url.toString())). filePathURL().path()).rstrip("\0"))) log.debug('OSX NSURL path detected. Dropped File is: %r', path) else: log.error("Unable to get appropriate file path for %r", url.toString(QtCore.QUrl.RemoveUserInfo)) else: # Dropping a file from iTunes gives a path with a NULL terminator path = os.path.normpath( os.path.realpath(unicode(url.toLocalFile()).rstrip("\0"))) if path and os.path.exists(path): mime = 'image/png' if path.lower().endswith( '.png') else 'image/jpeg' with open(path, 'rb') as f: data = f.read() self.load_remote_image(url, mime, data)
def _playsoundOSX(sound): from AppKit import NSSound from Foundation import NSURL if '://' not in sound: if not sound.startswith('/'): sound = os.getcwd() + '/' + sound sound = 'file://' + sound url = NSURL.URLWithString_(sound) nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True) if not nssound: raise IOError('Unable to load sound named: ' + sound) nssound.play()
def _fetchItems(self, force=True): """Private method that fetches attributes off of the list's page, parses the HTML (with BeautifulSoup), and then creates TadaItems. This is called automatically when a user requests the 'items' of a TadaList.""" page = NSString.stringWithContentsOfURL_( NSURL.URLWithString_(self._url())) soup = BeautifulSoup(page) lis = soup.findAll('li') items = [] for li in lis: items.append( TadaItem(li.form.contents[-1].strip(), li['id'][5:], self)) self.items = items return self.items
def _fetchLists(self): """A private convenience function that uses BeautifulSoup (for parsing) and NSString (for authentication) to make combing the HTML code from the main page of lists a bit easier.""" page = NSString.stringWithContentsOfURL_( NSURL.URLWithString_("http://%s.tadalist.com/lists" % (self.username))) soup = BeautifulSoup(page) rawLists = soup.findAll('li') lists = [] for rawList in rawLists: lists.append( TadaList(rawList.a['href'], rawList.a.contents[0], self)) return lists
def drop_urls(urls, target): files = [] new_files = [] for url in urls: log.debug("Dropped the URL: %r", url.toString(QtCore.QUrl.RemoveUserInfo)) if url.scheme() == "file" or not url.scheme(): # Workaround for https://bugreports.qt.io/browse/QTBUG-40449 # OSX Urls follow the NSURL scheme and need to be converted if sys.platform == 'darwin' and unicode( url.path()).startswith('/.file/id='): if NSURL_IMPORTED: filename = os.path.normpath( os.path.realpath( unicode( NSURL.URLWithString_(str(url.toString())). filePathURL().path()).rstrip("\0"))) log.debug( 'OSX NSURL path detected. Dropped File is: %r', filename) else: log.error("Unable to get appropriate file path for %r", url.toString(QtCore.QUrl.RemoveUserInfo)) continue else: # Dropping a file from iTunes gives a filename with a NULL terminator filename = os.path.normpath( os.path.realpath( unicode(url.toLocalFile()).rstrip("\0"))) file = BaseTreeView.tagger.files.get(filename) if file: files.append(file) elif os.path.isdir(encode_filename(filename)): BaseTreeView.tagger.add_directory(filename) else: new_files.append(filename) elif url.scheme() in ("http", "https"): path = unicode(url.path()) match = re.search(r"/(release|recording)/([0-9a-z\-]{36})", path) if match: entity = match.group(1) mbid = match.group(2) if entity == "release": BaseTreeView.tagger.load_album(mbid) elif entity == "recording": BaseTreeView.tagger.load_nat(mbid) if files: BaseTreeView.tagger.move_files(files, target) if new_files: BaseTreeView.tagger.add_files(new_files, target=target)
def dropEvent(self, e): if(e.mimeData().hasUrls()): # Get image url pixUrl = e.mimeData().urls()[0] if(platform.system() == "Darwin"): pixPath = str(NSURL.URLWithString_(str(pixUrl.toString())).filePathURL().path()) else: pixPath = str(pixUrl.toLocalFile()) print("FILEPATH {}".format(pixPath)) self.setText(pixPath) self.parent.setImageFilePath(pixPath) # Display image from url updateLabelToClusterShowImage(self.parent.getImageLabel(), pixPath, self.parent.frameSize().width()*0.5, self.parent.frameSize().height()*0.5)
def showSettingsForAccount_(self, account): if account.server.settings_url is None: return query_string = "realm=%s&tab=settings&user_agent=blink" % account.id.domain if account.server.settings_url.query: query_string = "%s&%s" % (account.server.settings_url.query, query_string) url = urllib.parse.urlunparse(account.server.settings_url[:4] + (query_string, ) + account.server.settings_url[5:]) url = NSURL.URLWithString_(url) request = NSURLRequest.requestWithURL_cachePolicy_timeoutInterval_( url, NSURLRequestReloadIgnoringLocalAndRemoteCacheData, 15) self.showAccountRequest(account, request)
def dropEvent(self, evt): if evt.mimeData().hasUrls \ and not self.questioner_running \ and not self.applying_output: evt.setDropAction(QtCore.Qt.CopyAction) evt.accept() for url in evt.mimeData().urls(): if op_sys == 'Darwin': image_path = str( NSURL.URLWithString_(str( url.toString())).filePathURL().path()) else: image_path = str(url.toLocalFile()) self.load_image(image_path) else: evt.ignore()
def makeDockOtherURLEntry(self, theURL, label=None): """Returns a dictionary corresponding to a URL.""" if label is None: label_name = str(theURL) else: label_name = label ns_url = NSURL.URLWithString_(theURL).absoluteString() result = { "tile-data": { "label": label_name, "url": {"_CFURLString": ns_url, "_CFURLStringType": 15}, }, "tile-type": "url-tile", } return result
def dropEvent(self, event): if event.mimeData().hasUrls: event.setDropAction(QtCore.Qt.CopyAction) event.accept() links = [] for url in event.mimeData().urls(): if op_sys == 'Darwin': fname = str( NSURL.URLWithString_(str( url.toString())).filePathURL().path()) else: fname = str(url.toLocalFile()) #print url.toNSURL() links.append(fname) self.emit(QtCore.SIGNAL("dropped"), links)
def open_url(url): ''' Open a URL in the current users session. This works with anything that command-k would accept, such as: afp, smb, vnc, http CLI Example:: salt '*' desktop.open_url 'afp://server.local' ''' workSpace = NSWorkspace.sharedWorkspace() url = NSURL.URLWithString_(url) if url is None: log.error('Invalid URL given: %s' % url) return False status = workSpace.openURL_(url) return status
def dropEvent(self, event): for i in event.mimeData().urls(): if (sys.platform == "darwin" and (i.toLocalFile().find('/.file/id=') == 0)): try: from Foundation import NSURL except ImportError: sys.path.append( '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC' ) from Foundation import NSURL url = NSURL.URLWithString_(i.toString()).path() self.open_name(str(url)) else: if (not i.isLocalFile()): return self.open_name(i.toLocalFile()) event.accept()
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.post_data: request.setHTTPMethod_('POST') data_unicode = unicode(self.post_data) data = NSData.dataWithBytes_length_( NSString.stringWithString_(data_unicode).UTF8String(), len(data_unicode.encode('utf-8'))) request.setHTTPBody_(data) 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.get_stored_headers() 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.get_stored_headers() 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') self.connection = NSURLConnection.alloc().initWithRequest_delegate_( request, self)
def dropEvent(self, e): if e.mimeData().hasUrls: e.setDropAction(Qt.CopyAction) e.accept() self.DFiles = [] for url in e.mimeData().urls(): try: if sysname == 'darwin': from Foundation import NSURL fname = NSURL.URLWithString_( url.toString()).filePathURL().path() else: fname = url.toLocalFile() self.DFiles.append(fname) except: pass self.dealD(self.DFiles) else: event.ignore()
def dropEvent(self, event): if event.mimeData().hasUrls(): # Ensure the file is copied and not moved # from where it was dragged event.setDropAction(QtCore.Qt.CopyAction) event.accept() files = [] for url in event.mimeData().urls(): if platform_system == 'Darwin': # Workaround for OSx dragging and dropping QTBUG40449 ns_url = NSURL.URLWithString_(str(url.toString())) fname = str(ns_url.filePathURL().path()) else: fname = str(url.toLocalFile()) files.append(fname) if files: self.dropped.emit(files)
def showIncomingCall(self, session, url): self._account = session.account self.webView.setHidden_(True) self.loadingText.setHidden_(False) self.spinWheel.setHidden_(False) self.spinWheel.startAnimation_(None) self.errorText.setHidden_(True) _t = "%s <%s@%s>" % (session.remote_identity.display_name, session.remote_identity.uri.user, session.remote_identity.uri.host) self.window.setTitle_( NSLocalizedString("Incoming Call From %s", "Window title") % _t) url = NSURL.URLWithString_(url) request = NSURLRequest.requestWithURL_cachePolicy_timeoutInterval_( url, NSURLRequestReloadIgnoringLocalAndRemoteCacheData, 15) self.webView.mainFrame().loadRequest_(request) self.window.makeKeyAndOrderFront_(self)
def _set_images(self): for index, path in enumerate([ self.nudge_prefs['logo_path'], self.nudge_prefs['screenshot_path'] ]): if path in DEFAULT_IMAGES: local_png_path = join(self.nudge_path, path).replace(' ', '%20') else: local_png_path = join(path).replace(' ', '%20') foundation_nsurl_path = NSURL.URLWithString_( f'file:{local_png_path}') foundation_nsdata = NSData.dataWithContentsOfURL_( foundation_nsurl_path) foundation_nsimage = NSImage.alloc().initWithData_( foundation_nsdata) if index == 0: self.nudge.views[COMPANY_LOGO].setImage_(foundation_nsimage) else: self.nudge.views[UPDATESS].setImage_(foundation_nsimage)
def _playaudioOSX(sound, block=True): ''' Utilizes AppKit.NSSound. ''' from AppKit import NSSound from Foundation import NSURL from time import sleep if '://' not in sound: if not sound.startswith('/'): from os import getcwd sound = getcwd() + '/' + sound sound = 'file://' + sound url = NSURL.URLWithString_(sound) nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True) if not nssound: raise IOError('Unable to load sound named: ' + sound) nssound.play() if block: sleep(nssound.duration())
def play_sound(sound_file): """Plays the audio file that is at the fully qualified path `sound_file`""" system = platform.system() if system == "Windows": import winsound winsound.PlaySound(sound_file, winsound.SND_FILENAME | winsound.SND_ASYNC) elif system == "Darwin": # macOS from AppKit import NSSound from Foundation import NSURL cwd = os.getcwd() url = NSURL.URLWithString_("file://" + sound_file) NSSound.alloc().initWithContentsOfURL_byReference_(url, True).play() else: # Linux import subprocess command = ["aplay", sound_file] subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, universal_newlines=True)
def dropEvent(self, e): """ Drop files directly onto the widget File locations are stored in fname :param e: :return: """ if e.mimeData().hasUrls: e.setDropAction(QtCore.Qt.CopyAction) e.accept() # Workaround for OSx dragging and dropping for url in e.mimeData().urls(): if op_sys == 'Darwin': fname = str(NSURL.URLWithString_(str(url.toString())).filePathURL().path()) else: fname = str(url.toLocalFile()) self.fname = fname self.load_image() else: e.ignore()
def start(self): """Start the connection.""" 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) request.setHTTPMethod_(self.method) if self.method == "POST": body_unicode = unicode(self.body) body_data = NSData.dataWithBytes_length_( NSString.stringWithString_(body_unicode).UTF8String(), len(body_unicode.encode("utf-8")), ) request.setHTTPBody_(body_data) self.connection = NSURLConnection.alloc().initWithRequest_delegate_( request, self)
def _playsoundOSX(sound, block = True): ''' Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports. Probably works on OS X 10.5 and newer. Probably works with all versions of Python. Inspired by (but not copied from) Aaron's Stack Overflow answer here: http://stackoverflow.com/a/34568298/901641 I never would have tried using AppKit.NSSound without seeing his code. ''' try: from AppKit import NSSound except ImportError: logger.warning("playsound could not find a copy of AppKit - falling back to using macOS's system copy.") sys.path.append('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC') from AppKit import NSSound from Foundation import NSURL from time import sleep sound = _handlePathOSX(sound) url = NSURL.URLWithString_(sound) if not url: raise PlaysoundException('Cannot find a sound with filename: ' + sound) for i in range(5): nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True) if nssound: break else: logger.debug('Failed to load sound, although url was good... ' + sound) else: raise PlaysoundException('Could not load sound with filename, although URL was good... ' + sound) nssound.play() if block: sleep(nssound.duration())