def handle_screenshot_candidate(self, f): """Given a candidate file, handle it if it's a screenshot.""" # The file could be anything. Only act if it's a screenshot. if not utils.is_screenshot(f): log.debug('%s is missing or not a screenshot.' % f) return # Do not act on files that are too old (so we don't swallow old files # that are not new screenshots). now = time.time() filename_time = utils.timestamp_from_filename( f) # Parse time out of filename. if (now - os.path.getctime(f) > TIME_THRESHOLD or not filename_time or now - filename_time > TIME_THRESHOLD): log.debug('Ignoring %s, too old.' % f) return # Create target dir if needed. if not os.path.isdir(SHARE_DIR): log.debug('Creating share dir %s' % SHARE_DIR) os.makedirs(SHARE_DIR) # Determine target filename in share directory. log.debug('Moving %s to %s' % (f, SHARE_DIR)) if utils.get_pref('randomize'): # Randomize file names? ext = os.path.splitext(f)[1] while True: shared_name = utils.randname() + ext target_file = os.path.join(SHARE_DIR, shared_name) if not os.path.exists(target_file): log.debug('New file name is: %s' % shared_name) break else: shared_name = os.path.basename(f) target_file = os.path.join(SHARE_DIR, shared_name) # Move/copy file there. if (utils.get_pref('retinascale') and utils.resampleRetinaImage(f, target_file)): if not utils.get_pref('copyonly'): os.unlink(f) else: if utils.get_pref('copyonly'): shutil.copy(f, target_file) else: shutil.move(f, target_file) # Create shared URL. url = utils.share_url(urllib.quote(shared_name)) log.debug('Share URL is %s' % url) log.debug('Copying to clipboard.') utils.pbcopy(url) # Notify user. notify('Screenshot shared!', 'Your URL is: %s\n\n' 'Click here to view file.' % url, context=target_file, callback=self.notify_callback)
def handle_screenshot_candidate(self, f): """Given a candidate file, handle it if it's a screenshot.""" # The file could be anything. Only act if it's a screenshot. if not utils.is_screenshot(f): log.debug('%s is missing or not a screenshot.' % f) return # Do not act on files that are too old (so we don't swallow old files # that are not new screenshots). now = time.time() filename_time = utils.timestamp_from_filename(f) # Parse time out of filename. if (now - os.path.getctime(f) > TIME_THRESHOLD or not filename_time or now - filename_time > TIME_THRESHOLD): log.debug('Ignoring %s, too old.' % f) return # Create target dir if needed. if not os.path.isdir(SHARE_DIR): log.debug('Creating share dir %s' % SHARE_DIR) os.makedirs(SHARE_DIR) # Determine target filename in share directory. log.debug('Moving %s to %s' % (f, SHARE_DIR)) if utils.get_pref('randomize'): # Randomize file names? ext = os.path.splitext(f)[1] while True: shared_name = utils.randname() + ext target_file = os.path.join(SHARE_DIR, shared_name) if not os.path.exists(target_file): log.debug('New file name is: %s' % shared_name) break else: shared_name = os.path.basename(f) target_file = os.path.join(SHARE_DIR, shared_name) # Move/copy file there. if (utils.get_pref('retinascale') and utils.resampleRetinaImage(f, target_file)): if not utils.get_pref('copyonly'): os.unlink(f) else: if utils.get_pref('copyonly'): shutil.copy(f, target_file) else: shutil.move(f, target_file) # Create shared URL. url = utils.share_url(urllib.quote(shared_name)) log.debug('Share URL is %s' % url) log.debug('Copying to clipboard.') utils.pbcopy(url) # Notify user. notify('Screenshot shared!', 'Your URL is: %s\n\n' 'Click here to view file.' % url, context=target_file, callback=self.notify_callback)
def updateDisplay(self): """Update window display from settings.""" self.randomize.setState_(get_pref('randomize')) self.copyonly.setState_(get_pref('copyonly')) self.launchAtStartup.setState_(get_pref('launchAtStartup')) dropboxdir = detect_dropbox_folder() self.dropboxdir.setStringValue_(dropboxdir or u'None. Install Dropbox?') self.dropboxid.setStringValue_(get_pref('dropboxid'))
def updateDisplay(self): """Update window display from settings.""" self.randomize.setState_(get_pref('randomize')) self.copyonly.setState_(get_pref('copyonly')) self.launchAtStartup.setState_(get_pref('launchAtStartup')) dropboxdir = detect_dropbox_folder() self.dropboxdir.setStringValue_( dropboxdir or u'None. Install Dropbox?') self.dropboxid.setStringValue_(get_pref('dropboxid'))
def set_defaults(): """ Perform some sanity checks on our preferences and set defaults for those that aren't set. """ for key, val in DEFAULTS.items(): get_pref(key, default=val, setdefault=True) # Add or remove startup item. should_start = get_pref('launchAtStartup') if bool(item_in_login_items()) != should_start: launch_at_startup(should_start)
def set_defaults(): """ Perform some sanity checks on our preferences and set defaults for those that aren't set. """ for key, val in DEFAULTS.items(): get_pref(key, default=val, setdefault=True) # Add or remove startup item. should_start = get_pref("launchAtStartup") if bool(item_in_login_items()) != should_start: launch_at_startup(should_start)
def updateDisplay(self): """Update window display from settings.""" self.launchAtStartup.setState_(get_pref("launchAtStartup")) self.iconset.selectCellWithTag_(1 if get_pref("iconset") == "grayscale" else 0) self.copyonly.setState_(get_pref("copyonly")) self.copyonly.setState_(get_pref("retinascale")) share_format = get_pref("share_format") if share_format == "long": # Default. self.url_select.selectCellWithTag_(0) elif share_format == "short": # Custom. self.url_select.selectCellWithTag_(1)
def on_moved(self, event): """ Catch move event: OS X creates a temp file, then moves it to its final name. """ f = event.dest_path # The moved file could be anything. Only act if it's a screenshot. if not utils.is_screenshot(f): return # Create target dir if needed. if not os.path.isdir(SHARE_DIR): log.debug('Creating share dir %s' % SHARE_DIR) os.makedirs(SHARE_DIR) # Move image file to target dir. log.debug('Moving %s to %s' % (f, SHARE_DIR)) if utils.get_pref('randomize'): # Randomize file names? ext = os.path.splitext(f)[1] while True: shared_name = utils.randname() + ext target_file = os.path.join(SHARE_DIR, shared_name) if not os.path.exists(target_file): log.debug('New file name is: %s' % shared_name) if utils.get_pref('copyonly'): shutil.copy(f, target_file) else: shutil.move(f, target_file) break else: shared_name = os.path.basename(f) shutil.move(f, SHARE_DIR) target_file = os.path.join(SHARE_DIR, shared_name) # Create shared URL url = urlparse.urljoin( SHARE_URL.format(dropboxid=utils.get_pref('dropboxid')), urllib.quote(shared_name)) logging.debug('Share URL is %s' % url) logging.debug('Copying to clipboard.') utils.pbcopy(url) # Notify user. growl = Growler.alloc().init() growl.setCallback(self.notify_callback) growl.notify('Screenshot shared!', 'Your URL is: %s\n\n' 'Click here to view file.' % url, context=target_file)
def updateDisplay(self): """Update window display from settings.""" self.launchAtStartup.setState_(get_pref('launchAtStartup')) self.autoupdate.setState_(get_pref('autoupdate')) self.randomize.setState_(get_pref('randomize')) self.copyonly.setState_(get_pref('copyonly')) self.retinascale.setState_(get_pref('retinascale')) dropboxdir = detect_dropbox_folder() self.dropboxdir.setStringValue_( dropboxdir or u'None. Install Dropbox?') self.dropboxid.setStringValue_(get_pref('dropboxid')) customurl = get_pref('customurl') example_filename = (EXAMPLE_FILENAME_SHORT if get_pref('randomize') else EXAMPLE_FILENAME_LONG) if not customurl: # Default. self.url_select.selectCellWithTag_(0) self.url_text.setEnabled_(False) self.url_text.setStringValue_('') self.url_example.setStringValue_(share_url(example_filename, url='')) else: # Custom. self.url_select.selectCellWithTag_(1) self.url_text.setEnabled_(True) self.url_text.setStringValue_(customurl) self.url_example.setStringValue_(share_url(example_filename, url=customurl))
def updateDisplay(self): """Update window display from settings.""" self.launchAtStartup.setState_(get_pref('launchAtStartup')) self.autoupdate.setState_(get_pref('autoupdate')) self.randomize.setState_(get_pref('randomize')) self.copyonly.setState_(get_pref('copyonly')) self.retinascale.setState_(get_pref('retinascale')) dropboxdir = detect_dropbox_folder() self.dropboxdir.setStringValue_(dropboxdir or u'None. Install Dropbox?') self.dropboxid.setStringValue_(get_pref('dropboxid')) customurl = get_pref('customurl') example_filename = (EXAMPLE_FILENAME_SHORT if get_pref('randomize') else EXAMPLE_FILENAME_LONG) if not customurl: # Default. self.url_select.selectCellWithTag_(0) self.url_text.setEnabled_(False) self.url_text.setStringValue_('') self.url_example.setStringValue_( share_url(example_filename, url='')) else: # Custom. self.url_select.selectCellWithTag_(1) self.url_text.setEnabled_(True) self.url_text.setStringValue_(customurl) self.url_example.setStringValue_( share_url(example_filename, url=customurl))
def handle_screenshot_candidate(self, f): """Given a candidate file, handle it if it's a screenshot.""" # Do not act on files that are too old (so we don't swallow files # that are not new screenshots). if os.path.getctime(f) - time.time() > TIME_THRESHOLD: return # The file could be anything. Only act if it's a screenshot. if not utils.is_screenshot(f): return # Create target dir if needed. if not os.path.isdir(SHARE_DIR): log.debug('Creating share dir %s' % SHARE_DIR) os.makedirs(SHARE_DIR) # Move image file to target dir. log.debug('Moving %s to %s' % (f, SHARE_DIR)) if utils.get_pref('randomize'): # Randomize file names? ext = os.path.splitext(f)[1] while True: shared_name = utils.randname() + ext target_file = os.path.join(SHARE_DIR, shared_name) if not os.path.exists(target_file): log.debug('New file name is: %s' % shared_name) if utils.get_pref('copyonly'): shutil.copy(f, target_file) else: shutil.move(f, target_file) break else: shared_name = os.path.basename(f) shutil.move(f, SHARE_DIR) target_file = os.path.join(SHARE_DIR, shared_name) # Create shared URL url = utils.share_url(urllib.quote(shared_name)) logging.debug('Share URL is %s' % url) logging.debug('Copying to clipboard.') utils.pbcopy(url) # Notify user. growl = Growler.alloc().init() growl.setCallback(self.notify_callback) growl.notify('Screenshot shared!', 'Your URL is: %s\n\n' 'Click here to view file.' % url, context=target_file)
def saveSettings_(self, sender): """Save changed settings.""" set_pref('launchAtStartup', bool(self.launchAtStartup.state())) launch_at_startup(bool(self.launchAtStartup.state())) set_pref('autoupdate', bool(self.autoupdate.state())) upshot = NSApplication.sharedApplication().delegate() upshot.updater.sparkle.setAutomaticallyChecksForUpdates_( bool(self.autoupdate.state())) set_pref('randomize', bool(self.randomize.state())) set_pref('copyonly', bool(self.copyonly.state())) set_pref('retinascale', bool(self.retinascale.state())) try: set_pref('dropboxid', int(self.dropboxid.stringValue())) except ValueError: pass # Custom URL settings. example_filename = (EXAMPLE_FILENAME_SHORT if get_pref('randomize') else EXAMPLE_FILENAME_LONG) if self.url_select.selectedCell().tag() == 0: # Default self.url_text.setStringValue_('') self.url_text.setEnabled_(False) self.url_example.setStringValue_( share_url(example_filename, url='')) set_pref('customurl', '') else: # Custom self.url_text.setEnabled_(True) self.url_example.setStringValue_( share_url(example_filename, url=self.url_text.stringValue())) set_pref('customurl', self.url_text.stringValue())
def applicationDidFinishLaunching_(self, notification): if not DROPBOX_DIR: # Oh-oh. alert( 'Unable to detect Dropbox folder', 'UpShot requires Dropbox, for now. Please install it, then ' 'try again.', ['OK']) self.quit_(self) if not os.path.exists(PUBLIC_DIR): # No public folder? pressed = alert( 'Unable to detect Public Dropbox folder', 'UpShot requires a Dropbox Public folder. You seem to have ' 'Dropbox, but no Public folder.\n\n' 'Since October 2012, Dropbox will only create a public ' 'folder for you if you opt in to it.\n\n' 'Please do so before using UpShot.', ['Learn How to Create a Dropbox Public Folder', 'Quit UpShot']) if pressed == NSAlertFirstButtonReturn: # Open Dropboc opt-in sw = NSWorkspace.sharedWorkspace() sw.openURL_(NSURL.URLWithString_(DROPBOX_PUBLIC_INFO)) self.quit_(self) self.build_menu() # Go do something useful. if utils.get_pref('dropboxid'): self.startListening_() else: self.stopListening_() DropboxDetect.DropboxDetectWindowController.showWindow()
def applicationDidFinishLaunching_(self, notification): if not DROPBOX_DIR: # Oh-oh. alert('Unable to detect Dropbox folder', 'UpShot requires Dropbox, for now. Please install it, then ' 'try again.', ['OK']) self.quit_(self) if not os.path.exists(PUBLIC_DIR): # No public folder? pressed = alert( 'Unable to detect Public Dropbox folder', 'UpShot requires a Dropbox Public folder. You seem to have ' 'Dropbox, but no Public folder.\n\n' 'Since October 2012, Dropbox will only create a public ' 'folder for you if you opt in to it.\n\n' 'Please do so before using UpShot.', ['Learn How to Create a Dropbox Public Folder', 'Quit UpShot']) if pressed == NSAlertFirstButtonReturn: # Open Dropboc opt-in sw = NSWorkspace.sharedWorkspace() sw.openURL_(NSURL.URLWithString_(DROPBOX_PUBLIC_INFO)) self.quit_(self) self.build_menu() # Go do something useful. if utils.get_pref('dropboxid'): self.startListening_() else: self.stopListening_() DropboxDetect.DropboxDetectWindowController.showWindow()
def saveSettings_(self, sender): """Save changed settings.""" set_pref('launchAtStartup', bool(self.launchAtStartup.state())) launch_at_startup(bool(self.launchAtStartup.state())) set_pref('autoupdate', bool(self.autoupdate.state())) upshot = NSApplication.sharedApplication().delegate() upshot.updater.sparkle.setAutomaticallyChecksForUpdates_( bool(self.autoupdate.state())) set_pref('randomize', bool(self.randomize.state())) set_pref('copyonly', bool(self.copyonly.state())) set_pref('retinascale', bool(self.retinascale.state())) try: set_pref('dropboxid', int(self.dropboxid.stringValue())) except ValueError: pass # Custom URL settings. example_filename = (EXAMPLE_FILENAME_SHORT if get_pref('randomize') else EXAMPLE_FILENAME_LONG) if self.url_select.selectedCell().tag() == 0: # Default self.url_text.setStringValue_('') self.url_text.setEnabled_(False) self.url_example.setStringValue_(share_url(example_filename, url='')) set_pref('customurl', '') else: # Custom self.url_text.setEnabled_(True) self.url_example.setStringValue_( share_url(example_filename, url=self.url_text.stringValue())) set_pref('customurl', self.url_text.stringValue())
def updateDisplay(self): """Update window display from settings.""" self.launchAtStartup.setState_(get_pref('launchAtStartup')) self.notification_sound.setState_(get_pref('notification_sound')) self.notification_growl.setState_(get_pref('notification_growl')) # self.iconset.selectCellWithTag_( # 1 if get_pref('iconset') == 'grayscale' else 0) self.randomize.setState_(get_pref('randomize')) self.copyonly.setState_(get_pref('copyonly')) self.retinascale.setState_(get_pref('retinascale')) # dropboxdir = detect_dropbox_folder() # self.dropboxdir.setStringValue_( # dropboxdir or u'None. Install Dropbox?') # self.dropboxid.setStringValue_(get_pref('dropboxid')) # customurl = get_pref('customurl') # if not customurl: # Default. # self.upload_url.selectCellWithTag_(0) # # self.url_text.setEnabled_(False) # # self.url_text.setStringValue_('') # # self.url_example.setStringValue_(share_url(EXAMPLE_FILENAME, # # url='')) # else: # Custom. # self.upload_url.selectCellWithTag_(1) # self.url_text.setEnabled_(True) # self.url_text.setStringValue_(customurl) # self.url_example.setStringValue_(share_url(EXAMPLE_FILENAME, # url=customurl)) self.upload_url.setStringValue_(get_pref('upload_url'))
def build_menu(self): """Build the OS X status bar menu.""" # Create the statusbar item statusbar = NSStatusBar.systemStatusBar() self.statusitem = statusbar.statusItemWithLength_(NSVariableStatusItemLength) # Set statusbar icon and color/grayscale mode. for tag, img in self.image_paths.items(): self.images[tag] = NSImage.alloc().initByReferencingFile_(img) self.images[tag].setTemplate_(utils.get_pref('iconset') == 'grayscale') self.statusitem.setImage_(self.images['icon16']) self.statusitem.setHighlightMode_(1) self.statusitem.setToolTip_('Upshot Screenshot Sharing') # Build menu. self.menu = NSMenu.alloc().init() m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Browse Screenshots', 'openShareDir:', '') self.menu.addItem_(m) self.menuitems['opensharedir'] = m self.menu.addItem_(NSMenuItem.separatorItem()) m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Start Screenshot Sharing', 'startListening:', '') m.setHidden_(True) # Sharing is on by default. self.menu.addItem_(m) self.menuitems['start'] = m m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Pause Screenshot Sharing', 'stopListening:', '') self.menu.addItem_(m) self.menuitems['stop'] = m m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Preferences...', 'openPreferences:', '') self.menu.addItem_(m) self.menuitems['preferences'] = m self.menu.addItem_(NSMenuItem.separatorItem()) # m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( # 'Open UpShot Project Website', 'website:', '') # self.menu.addItem_(m) # self.menuitems['website'] = m m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('About UpShot', 'about:', '') self.menu.addItem_(m) self.menuitems['about'] = m self.menu.addItem_(NSMenuItem.separatorItem()) m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit UpShot', 'quit:', '') self.menu.addItem_(m) self.menuitems['quit'] = m self.statusitem.setMenu_(self.menu)
def handle_screenshot_candidate(self, f): """Given a candidate file, handle it if it's a screenshot.""" # Do not act on files that are too old (so we don't swallow old files # that are not new screenshots). if os.path.getctime(f) - time.time() > TIME_THRESHOLD: return # The file could be anything. Only act if it's a screenshot. if not utils.is_screenshot(f): return utils.get_pref('retinascale') and utils.resampleRetinaImage(f, f) with open(f, "rb") as image_file: from lib.phabricator import Phabricator PHAB = Phabricator() # This will use your ~/.arcrc file import base64 encoded_string = base64.b64encode(image_file.read()) result = PHAB.file.upload(data_base64=encoded_string) phid = result.response result = PHAB.file.info(phid=phid) url = result['uri'] object_name = result['objectName'] if utils.get_pref('share_format') == 'long': share_url = url elif utils.get_pref('share_format') == 'short': share_url = object_name logging.debug('Copying to clipboard.') utils.pbcopy(share_url) # Notify user. growl = Growler.alloc().init() growl.setCallback(self.notify_callback) growl.notify( 'Screenshot shared!', '{%s}@%s\n' % (object_name, url), context=url )
def update_menu(self): """Update status bar menu based on app status.""" if self.statusitem is None: return # Apply iconset self.images['icon16'].setTemplate_( utils.get_pref('iconset') == 'grayscale') running = (self.observer is not None) self.statusitem.setImage_(self.images['icon16' if running else 'icon16-off'])
def update_menu(self): """Update status bar menu based on app status.""" if self.statusitem is None: return # Apply iconset self.images['icon16'].setTemplate_( utils.get_pref('iconset') == 'grayscale') running = (self.observer is not None) self.statusitem.setImage_( self.images['icon16' if running else 'icon16-off'])
def update_menu(self): """Update status bar menu based on app status.""" if self.statusitem is None: return # Apply iconset self.images['icon16'].setTemplate_( utils.get_pref('iconset') == 'grayscale') running = (self.observer is not None) self.statusitem.setImage_( self.images['icon16' if running else 'icon16-off']) if utils.get_pref('dropboxid'): # Runnable. self.menuitems['stop'].setHidden_(not running) self.menuitems['start'].setHidden_(running) self.menuitems['needpref'].setHidden_(True) else: # Need settings. self.menuitems['start'].setHidden_(True) self.menuitems['stop'].setHidden_(True) self.menuitems['needpref'].setHidden_(False)
def update_menu(self): """Update status bar menu based on app status.""" if self.statusitem is None: return # Apply iconset self.images['icon16'].setTemplate_( utils.get_pref('iconset') == 'grayscale') running = (self.observer is not None) self.statusitem.setImage_(self.images['icon16' if running else 'icon16-off']) if utils.get_pref('dropboxid'): # Runnable. self.menuitems['stop'].setHidden_(not running) self.menuitems['start'].setHidden_(running) self.menuitems['needpref'].setHidden_(True) else: # Need settings. self.menuitems['start'].setHidden_(True) self.menuitems['stop'].setHidden_(True) self.menuitems['needpref'].setHidden_(False)
def handle_screenshot_candidate(self, f): """Given a candidate file, handle it if it's a screenshot.""" # Do not act on files that are too old (so we don't swallow old files # that are not new screenshots). if os.path.getctime(f) - time.time() > TIME_THRESHOLD: return # The file could be anything. Only act if it's a screenshot. if not utils.is_screenshot(f): return utils.get_pref('retinascale') and utils.resampleRetinaImage(f, f) with open(f, "rb") as image_file: from lib.phabricator import Phabricator PHAB = Phabricator() # This will use your ~/.arcrc file import base64 encoded_string = base64.b64encode(image_file.read()) result = PHAB.file.upload(data_base64=encoded_string) phid = result.response result = PHAB.file.info(phid=phid) url = result['uri'] object_name = result['objectName'] logging.debug('Copying to clipboard.') utils.pbcopy(url) # Notify user. growl = Growler.alloc().init() growl.setCallback(self.notify_callback) growl.notify('Screenshot shared!', 'Your URL is: %s\n' 'PHID is: %s\n' 'FILE is: %s\n' 'Click here to view file.' % (url, phid, object_name), context=f)
def applicationDidFinishLaunching_(self, notification): if not DROPBOX_DIR: # Oh-oh. alert('Unable to detect Dropbox folder', 'UpShot requires Dropbox, for now. Please install it, then ' 'try again.', ['OK']) self.terminate_(self) self.build_menu() # Go do something useful. if utils.get_pref('dropboxid'): self.startListening_() else: self.stopListening_() DropboxDetect.DropboxDetectWindowController.showWindow()
def applicationDidFinishLaunching_(self, notification): if not DROPBOX_DIR: # Oh-oh. alert( 'Unable to detect Dropbox folder', 'UpShot requires Dropbox, for now. Please install it, then ' 'try again.', ['OK']) self.terminate_(self) self.build_menu() # Go do something useful. if utils.get_pref('dropboxid'): self.startListening_() else: self.stopListening_() DropboxDetect.DropboxDetectWindowController.showWindow()
def updateDisplay(self): """Update window display from settings.""" self.launchAtStartup.setState_(get_pref("launchAtStartup")) self.iconset.selectCellWithTag_(1 if get_pref("iconset") == "grayscale" else 0) self.randomize.setState_(get_pref("randomize")) self.copyonly.setState_(get_pref("copyonly")) dropboxdir = detect_dropbox_folder() self.dropboxdir.setStringValue_(dropboxdir or u"None. Install Dropbox?") self.dropboxid.setStringValue_(get_pref("dropboxid")) customurl = get_pref("customurl") if not customurl: # Default. self.url_select.selectCellWithTag_(0) self.url_text.setEnabled_(False) self.url_text.setStringValue_("") self.url_example.setStringValue_(share_url(EXAMPLE_FILENAME, url="")) else: # Custom. self.url_select.selectCellWithTag_(1) self.url_text.setEnabled_(True) self.url_text.setStringValue_(customurl) self.url_example.setStringValue_(share_url(EXAMPLE_FILENAME, url=customurl))
def handle_screenshot_candidate(self, f): """Given a candidate file, handle it if it's a screenshot.""" # Do not act on files that are too old (so we don't swallow old files # that are not new screenshots). log.debug('Handling the screenshot candidate...') # sleep for a bit to let the file system catch up # else `is_screenshot` might be wrong time.sleep(0.5) if os.path.getctime(f) - time.time() > TIME_THRESHOLD: log.debug('Time threshhold exceeded.') return # The file could be anything. Only act if it's a screenshot. if not utils.is_screenshot(f): log.debug('Does not look like a screenshot.') return # Create target dir if needed. if not os.path.isdir(SHARE_DIR): log.debug('Creating share dir %s' % SHARE_DIR) os.makedirs(SHARE_DIR) # Determine target filename in share directory. log.debug('Moving %s to %s' % (f, SHARE_DIR)) if utils.get_pref('randomize'): # Randomize file names? ext = os.path.splitext(f)[1] while True: shared_name = utils.randname() + ext target_file = os.path.join(SHARE_DIR, shared_name) if not os.path.exists(target_file): log.debug('New file name is: %s' % shared_name) break else: shared_name = os.path.basename(f) target_file = os.path.join(SHARE_DIR, shared_name) # We repurpose the "copyonly" setting. # True: Move screenshot to SHARE_DIR and leave it there # False: Remove all screenshots from the filesystem after upload # Move/copy file there. if (utils.get_pref('retinascale') and utils.resampleRetinaImage(f, target_file)): os.unlink(f) else: shutil.move(f, target_file) try: # Actually upload the file to our custom url if not utils.get_pref('upload_url'): log.debug('No Upload URL defined: {0}'.format(utils.get_pref('upload_url'))) raise Exception('No Upload URL defined.') content = base64.b64encode(open(target_file).read()) payload = {'image': content} headers = {'Content-Type': 'application/json'} r = requests.post(utils.get_pref('upload_url'), data=json.dumps(payload), headers=headers) log.debug('Response raw content:') log.debug(r.content) url = r.json()['link'] log.debug('Share URL is %s' % url) log.debug('Copying to clipboard.') utils.pbcopy(url) # Remove old file if not utils.get_pref('copyonly'): os.unlink(target_file) # Notify user of success if utils.get_pref('notification_growl'): growl = Growler.alloc().init() growl.setCallback(self.notify_callback) growl.notify('Success! Screenshot uploaded.', '%s\n\n' % url, context=target_file) if utils.get_pref('notification_sound'): return_code = subprocess.call(["afplay", NOTIFICATION_SOUND]) log.debug('Playing notification sound: {0}'.format(return_code)) except Exception, e: # Notify user of error log.debug('EXCEPTION %s' % str(e)) message = str(e) growl = Growler.alloc().init() growl.setCallback(self.notify_callback) growl.notify('Error uploading screenshot!', message, context=target_file)
def build_menu(self): """Build the OS X status bar menu.""" # Create the statusbar item statusbar = NSStatusBar.systemStatusBar() self.statusitem = statusbar.statusItemWithLength_( NSVariableStatusItemLength) # Set statusbar icon and color/grayscale mode. for tag, img in self.image_paths.items(): self.images[tag] = NSImage.alloc().initByReferencingFile_(img) self.images[tag].setTemplate_( utils.get_pref('iconset') == 'grayscale') self.statusitem.setImage_(self.images['icon16']) self.statusitem.setHighlightMode_(1) self.statusitem.setToolTip_('Upshot Screenshot Sharing') # Build menu. self.menu = NSMenu.alloc().init() m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Browse Screenshots', 'openShareDir:', '') self.menu.addItem_(m) self.menuitems['opensharedir'] = m self.menu.addItem_(NSMenuItem.separatorItem()) m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Start Screenshot Sharing', 'startListening:', '') m.setHidden_(True) # Sharing is on by default. self.menu.addItem_(m) self.menuitems['start'] = m m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Pause Screenshot Sharing', 'stopListening:', '') self.menu.addItem_(m) self.menuitems['stop'] = m m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Preferences...', 'openPreferences:', '') self.menu.addItem_(m) self.menuitems['preferences'] = m self.menu.addItem_(NSMenuItem.separatorItem()) # m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( # 'Open UpShot Project Website', 'website:', '') # self.menu.addItem_(m) # self.menuitems['website'] = m m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'About UpShot', 'about:', '') self.menu.addItem_(m) self.menuitems['about'] = m self.menu.addItem_(NSMenuItem.separatorItem()) m = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Quit UpShot', 'quit:', '') self.menu.addItem_(m) self.menuitems['quit'] = m self.statusitem.setMenu_(self.menu)
from AppKit import * from PyObjCTools import AppHelper from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer import DropboxDetect import Preferences from lib import utils from lib.notifications import Growler from lib.windows import alert SCREENSHOT_DIR = utils.get_pref( domain='com.apple.screencapture', key='location', default=os.path.join(os.environ['HOME'], 'Desktop')) DROPBOX_DIR = utils.detect_dropbox_folder() SHARE_DIR = os.path.join(DROPBOX_DIR or '', 'Public', 'Screenshots') HOMEPAGE_URL = 'http://github.com/fwenzel/upshot' SHARE_URL = 'http://dl.dropbox.com/u/{dropboxid}/Screenshots/' # Set up logging LOG_LEVEL = logging.DEBUG logging.basicConfig(level=LOG_LEVEL) log = logging.getLogger('upshot') # Local settings try:
import os import time from AppKit import * from PyObjCTools import AppHelper from watchdog.events import FileCreatedEvent, FileMovedEvent, FileSystemEventHandler from watchdog.observers import Observer import Preferences from lib import utils from lib.notifications import Growler from lib.windows import alert SCREENSHOT_DIR = utils.get_pref(domain='com.apple.screencapture', key='location', default=os.path.join(os.environ['HOME'], 'Desktop')) DROPBOX_DIR = utils.detect_dropbox_folder() PUBLIC_DIR = os.path.join(DROPBOX_DIR or '', 'Public') SHARE_DIR = os.path.join(PUBLIC_DIR, 'Screenshots') HOMEPAGE_URL = 'http://upshot.it' DROPBOX_PUBLIC_INFO = 'https://www.dropbox.com/help/16' TIME_THRESHOLD = 15 # How many seconds after creation do we handle a file? # Set up logging LOG_LEVEL = logging.DEBUG logging.basicConfig(level=LOG_LEVEL) log = logging.getLogger('upshot')