def showAllTasks(self): tasks = self.getTasks() if not tasks: alfred.exitWithFeedback( title="No Task Found", subtitle="if this message is wrong, please try again or clean cache(ds setting - Clean)", ) tasks = self.filterTasks(tasks, alfred.argv(2), alfred.argv(3)) feedback = alfred.Feedback() if not tasks: feedback.addItem(title="No Task Found.") count = 0 for task in tasks: count += 1 feedback.addItem( title="{}. {}".format(count, task["title"]), subtitle=task["desc"], autocomplete=" detail {}".format(task["id"]), valid=False, ) # 暂停所有任务 feedback.addItem(title="Pause All", arg="pause-all-tasks"), # 恢复所有任务 feedback.addItem(title="Resume All", arg="resume-all-tasks"), # 删除所有任务 需确认 feedback.addItem(title="Delete All", autocomplete=" delete-all", valid=False) # 删除所有错误的任务 需确认 feedback.addItem(title="Remove Erroneous Tasks", autocomplete=" remove-erroneous-tasks", valid=False), # 清理所有已完成的任务 feedback.addItem(title="Clear Completed Tasks", arg="clear-completed-tasks"), # 更多操作 feedback.addItem(title="More Actions ...", autocomplete=" more-actions", valid=False) feedback.output()
def checkAccountInfo(self): if self.isAccountInfoExists(): return alfred.exitWithFeedback( title = 'User Account or DS Host Information Missing. ', subtitle = 'To set with `ds setting auth`' )
def search(self): # 搜索字符窜 query = [] argv_pos = 2 while True: arg = alfred.argv(argv_pos) if not arg: break query.append(arg) argv_pos += 1 query = ' '.join(query) if not query: alfred.exitWithFeedback(title='Search Apps in AppShopper') params = {'search': query, 'platform': 'all', 'device': 'all'} # 搜索类型 ios mac cmd = alfred.argv(1).lower() if cmd.endswith('-ios'): params.update(platform='ios') elif cmd.endswith('-mac'): params.update(platform='mac') elif cmd.endswith('-iphone'): params.update(platform='ios', device='iphone') elif cmd.endswith('-ipad'): params.update(platform='ios', device='ipad') query_str = '?{}'.format(urllib.urlencode(params)) url = self.getUrl('search', query_str) success, data = self.fetchDataFromePage(url, False) return self.outputFeedback(success, data)
def resource(): try: res_id = int(alfred.argv(2)) data = fetchSingleResource(res_id) filter_str = alfred.argv(3) files = data['files'] if filter_str: filter_str = filter_str.upper() files = filter(lambda f: filter_str in f['format'], files) if not data: alfred.exitWithFeedback(title='没有找到相关的内容') feedback = alfred.Feedback() feedback.addItem( title = data['title'], subtitle = '{} 个文件,可使用文件类型过滤,选择此项打开资源页面'.format(len(files)), arg = 'open-url {}'.format( b64encode(getResourcePageURLByID(data['id'])) ), icon = alfred.storage.getLocalIfExists(data['img'], True) ) for f in files: f['has_emule'] = '有' if f['emule'] else '无' f['has_magnet'] = '有' if f['magnet'] else '无' subtitle = '类型: {format} 容量: {filesize} 电驴: {has_emule} 磁力链: {has_magnet}'.format(**f) feedback.addItem( title = f['filename'], subtitle = subtitle, valid = False, autocomplete = 'file {},{}'.format(data['id'], f['id']) ) feedback.addItem(item=_fb_return_top) feedback.output() except Exception, e: alfred.exitWithFeedback(item=_fb_no_found_and_return_top)
def checkAuthorization(self): if self.isAuthorized(): return alfred.exitWithFeedback( title = 'User Account or DS Host Information Missing. ', subtitle = 'To set with `ds setting auth`' )
def run(self): success, data = self.ds.fetchStatistic() if not success: alfred.exitWithFeedback(title="ERROR", subtitle=data) feedback = alfred.Feedback() # DS 信息 ds_info = alfred.cache.get("dsinfo") if ds_info: total = len(self.getTasks()) error = len(self.getErroneousTasks()) completed = len(self.getCompletedTasks()) paused = len(self.getSpecifiedStatusTask("paused")) waiting = len(self.getSpecifiedStatusTask("waiting")) downloading = len(self.getSpecifiedStatusTask("downloading")) feedback.addItem( title="Download Station v{}".format(ds_info["version_string"]), subtitle="{} task(s), {} downloading, {} waiting, {} paused, {} error, {} completed,".format( total, downloading, waiting, paused, error, completed ), ) download = dslibHumanReadable(data["speed_download"]) upload = dslibHumanReadable(data["speed_upload"]) feedback.addItem(subtitle="Total speed except for eMule", title="DL: {:8} UL: {}".format(download, upload)) if data.has_key("emule_speed_download"): download = dslibHumanReadable(data["emule_speed_download"]) upload = dslibHumanReadable(data["emule_speed_upload"]) feedback.addItem(subtitle="Total eMule speed", title="DL: {:8} UL: {}".format(download, upload)) else: feedback.addItem(title="eMule was disabled.") feedback.output()
def search(self): # 搜索字符窜 query = [] argv_pos = 2 while True: arg = alfred.argv(argv_pos) if not arg: break query.append(arg) argv_pos += 1 query = ' '.join(query) if not query: alfred.exitWithFeedback( title = 'Search Apps in AppShopper' ) params = { 'search' : query, 'platform' : 'all', 'device' : 'all' } # 搜索类型 ios mac cmd = alfred.argv(1).lower() if cmd.endswith('-ios'): params.update(platform='ios') elif cmd.endswith('-mac'): params.update(platform='mac') elif cmd.endswith('-iphone'): params.update(platform='ios', device='iphone') elif cmd.endswith('-ipad'): params.update(platform='ios', device='ipad') query_str = '?{}'.format(urllib.urlencode(params)) url = self.getUrl('search', query_str) success, data = self.fetchDataFromePage(url, False) return self.outputFeedback(success, data)
def showTaskDetail(self): task = self.getSingleTask(alfred.argv(3)) if not task: alfred.exitWithFeedback(title="ERROR", subtitle="No Task Found.") feedback = alfred.Feedback() # 任务标题 feedback.addItem( title=task["title"], subtitle=task["desc"], autocomplete=" detail {id}".format(**task), # 参数与现有相同 即无任何反应 valid=False, ) status = task["status"] # 状态为 '等待'、'下载中' 显示暂停操作 if status in ["waiting", "downloading"]: feedback.addItem(title="Pause", arg="pause-task {id}".format(**task)) # 状态为 '暂停' 显示 恢复操作 if status in ["paused"]: feedback.addItem(title="Resume", arg="resume-task {id}".format(**task)) # 状态为 '完成' 显示 清理操作 if status in ["finished"]: feedback.addItem(title="Clear", arg="delete-task {id}".format(**task)) # 实际上就是删除已完成的任务 # 只有状态不是 '完成'、'完成中'才显示 删除操作 if status not in ["finished", "finishing"]: feedback.addItem(title="Delete", autocomplete=" delete {id}".format(**task), valid=False) feedback.addItem(title="Show all", autocomplete="", valid=False) feedback.output()
def query(): tryCleanCache() w = " ".join(sys.argv[1:]).strip() try: ret = fetchData(w) if not ret: raise Exception("服务器访问失败。") # pprint(ret) if ret.get("errorCode", -1) != 0: error_msg = _error_desc.get(ret.get("errorCode", -1)) raise Exception(error_msg if error_msg else "未知错误。") is_eng = isEnglish(w) feedback = alfred.Feedback() # 有解释 basic = ret.get("basic", {}) phonetic = basic.get("phonetic", "") feedback.addItem( title="{} {}".format(w, "[{}]".format(phonetic) if phonetic else ""), subtitle="译: {}".format("; ".join(ret.get("translation", []))), arg=w, ) for e in basic.get("explains", []): feedback.addItem(title=e, autocomplete=None if is_eng else clearExplain(e), valid=False) # 网络释义 web = ret.get("web", []) if web: feedback.addItem(title="--- 网络释义 ---", valid=False) for w in web: feedback.addItem( title=w.get("key"), subtitle="; ".join(w.get("value")), valid=False, autocomplete=w.get("key") ) feedback.output() except Exception, e: alfred.exitWithFeedback(title=w, subtitle="出错了,{}".format(e), valid=False)
def read_key(): key = alfred.config.get('apikey') if key: return key else: alfred.exitWithFeedback(title="No Trakt API-Key provided", subtitle="Please add a Trakt API-Key with `trakt apikey [key]`")
def showRemarkSetting(): try: _, com_code, post_id = alfred.argv(1).split('-') except Exception, e: alfred.exitWithFeedback(title='参数格式错误。', subtitle='选择返回', valid=False, autocomplete='')
def showAllTasks(self): tasks = self.getTasks() if not tasks: alfred.exitWithFeedback(title='No Task Found', subtitle='if this message is wrong, please try again or clean cache(ds setting - Clean)') tasks = self.filterTasks(tasks, alfred.argv(2), alfred.argv(3)) feedback = alfred.Feedback() if not tasks: feedback.addItem( title = 'No Task Found.' ) count = 0 for task in tasks: count += 1 feedback.addItem( title = '{}. {}'.format(count, task['title']), subtitle = task['desc'], autocomplete = ' detail {}'.format(task['id']), valid = False ) # 暂停所有任务 feedback.addItem( title = 'Pause All', arg = 'pause-all-tasks' ), # 恢复所有任务 feedback.addItem( title = 'Resume All', arg = 'resume-all-tasks' ), # 删除所有任务 需确认 feedback.addItem( title = 'Delete All', autocomplete = ' delete-all', valid = False ) # 删除所有错误的任务 需确认 feedback.addItem( title = 'Remove Erroneous Tasks', autocomplete = ' remove-erroneous-tasks', valid = False ), # 清理所有已完成的任务 feedback.addItem( title = 'Clear Completed Tasks', arg = 'clear-completed-tasks' ), # 更多操作 feedback.addItem( title = 'More Actions ...', autocomplete = ' more-actions', valid = False ) feedback.output()
def showAllTasks(self): tasks = self.getTasks() if not tasks: alfred.exitWithFeedback(title='No Task Found', subtitle='if this message is wrong, please try again or clean cache(ds setting - Clean)') tasks = self.filterTasks(tasks, alfred.argv(2), alfred.argv(3)) feedback = alfred.Feedback() if not tasks: feedback.addItem( title = 'No Task Found.' ) count = 0 for task in tasks: count += 1 feedback.addItem( title = '{}. {}'.format(count, task['title']), subtitle = task['desc'], autocomplete = ' detail {}'.format(task['id']), valid = False ) # 暂停所有任务 feedback.addItem( title = 'Pause All', arg = 'pause-all-tasks' ), # 恢复所有任务 feedback.addItem( title = 'Resume All', arg = 'resume-all-tasks' ), # 删除所有任务 需确认 feedback.addItem( title = 'Delete All', autocomplete = ' delete-all', valid = False ) # 删除所有错误的任务 需确认 feedback.addItem( title = 'Remove Erroneous Tasks', autocomplete = ' remove-erroneous-tasks', valid = False ), # 清理所有已完成的任务 feedback.addItem( title = 'Clear Completed Tasks', arg = 'clear-completed-tasks' ), # 更多操作 feedback.addItem( title = 'More Actions ...', autocomplete = ' more-actions', valid = False ) feedback.output()
def outputiTunesPlayingSong(self): res, data = self.fetchiTunesPlaying() if not res or not data['title']: return title = '{title}' if not data['artist'] else '{artist} - {title}' title = title.format(**data) alfred.exitWithFeedback( title=title, subtitle='iTunes current playing track', autocomplete='"{title}" "{artist}"'.format(**data), valid=False)
def outputiTunesPlayingSong(self): res, data = self.fetchiTunesPlaying() if not res or not data['title']: return title = '{title}' if not data['artist'] else '{artist} - {title}' title = title.format(**data) alfred.exitWithFeedback( title = title, subtitle = 'iTunes current playing track', autocomplete = '"{title}" "{artist}"'.format(**data), valid = False )
def main(): try: device = alfred.argv(1) data = accessTabs() if not data or not data.get('values'): alfred.exitWithFeedback(title="Oops! iCloud Tabs non-existend", valid=False) if device: showTabsByDevice(device) else: showDevices() except Exception, e: alfred.exitWithFeedback(title='Oops! {}'.format(e))
def showWishList(self): username = alfred.config.get('username') if not username: alfred.exitWithFeedback( title = 'AppShopper Username Is Missing.', subtitle = 'you MUST set your AppShopper username and share it in AppShopper account setting if you want to see wish list.', autocomplete = 'setting username', valid = False ) wish_feed = self.getUrl('feed', 'user', username, 'wishlist') success, data = self.fetchDataFromFeed(wish_feed, False) no_found_msg = 'maybe you don\'t share your wifh list, you need to check "Share My Wishlist" in AppShopper Wish List page' self.outputFeedback(success, data, no_found_msg)
def showWishList(self): username = alfred.config.get('username') if not username: alfred.exitWithFeedback( title='AppShopper Username Is Missing.', subtitle= 'you MUST set your AppShopper username and share it in AppShopper account setting if you want to see wish list.', autocomplete='setting username', valid=False) wish_feed = self.getUrl('feed', 'user', username, 'wishlist') success, data = self.fetchDataFromFeed(wish_feed, False) no_found_msg = 'maybe you don\'t share your wifh list, you need to check "Share My Wishlist" in AppShopper Wish List page' self.outputFeedback(success, data, no_found_msg)
def main(): try: device = alfred.argv(1) data = accessTabs() if not data or not data.get('values'): alfred.exitWithFeedback(title="Oops! iCloud Tabs non-existend", valid=False) if device: showTabsByDevice(device) else: showDevices() except Exception, e: alfred.exitWithFeedback(title='Oops! {}'.format(e))
def main(): import alfred url = sys.argv[1] if not url: alfred.exitWithFeedback(title='UNKNOWN') rdl = RealDownloadLink() res = rdl.parse(url) feedback = alfred.Feedback() res.update({'type_desc': rdlTypeToDesc(res['type'])}) feedback.addItem( title=res['real'], subtitle='{type_desc} {filename} {filesize}'.format(**res), arg=res['real']) feedback.output()
def confimDeleteTask(self): task = self.getSingleTask(alfred.argv(3)) if not task: alfred.exitWithFeedback(title="ERROR", subtitle="task no found.") feedback = alfred.Feedback() feedback.addItem( title="Are you sure you want to delete task?", subtitle=task["title"], autocomplete=" delete {id}".format(**task), #! 同样的命令,不进行任何操作 valid=False, ) feedback.addItem(title="Yes", arg="delete-task {id}".format(**task)) feedback.addItem(title="No", autocomplete="", valid=False) #! 返回任务列表 feedback.output()
def query(): arg1 = alfred.argv(1) arg2 = alfred.argv(2) post_id = arg2 if arg2 else arg1 com_codes = arg1 if arg2 else None # 如果只有快递单号 没有公司代码 先自动检测获得公司代码 com_codes = [surmiseCompanyCode(com_codes)] if com_codes is not None else queryCompanyCodeByPostID(post_id) if not com_codes: alfred.exitWithFeedback(title='没有找到相关的快递信息') # 只有一个公司符合 直接给出结果 if len(com_codes) == 1: showSingle(com_codes[0], post_id) # 如果有多个 则列出公司列表 else: showRecommendCompany(com_codes, post_id)
def main(): import alfred url = sys.argv[1] if not url: alfred.exitWithFeedback(title='UNKNOWN') rdl = RealDownloadLink() res = rdl.parse(url) feedback = alfred.Feedback() res.update({'type_desc' : rdlTypeToDesc(res['type'])}) feedback.addItem( title = res['real'], subtitle = '{type_desc} {filename} {filesize}'.format(**res), arg = res['real'] ) feedback.output()
def run(self): arg1 = alfred.argv(1) # version or page arg2 = alfred.argv(2) # Would be the page if using a version arg3 = alfred.argv(3) # Could be a property or method only ver = None page = '' search = None # Parse args to figure out which page this is. if not arg1: return self.showDefaultList() arg1 = arg1.lower() if arg1.replace(".","").isdigit(): ver = arg1 if arg2 is not None: page = arg2.lower() if arg3 is not None: search = arg3.lower() else: page = arg1 if arg2 is not None: search = arg2.lower() # Make the URL for the all page, whether it is version specific or not. url = 'http://nodejs.org/' if ver is not None: url = url + 'docs/' + 'v0.' + ver + '/' url = url + "api/" + page + ".html" # Begin feedback loop feedback = alfred.Feedback() if not search: feedback.addItem(title='Table of Contents', subtitle=page + ' toc', arg=url + '#toc') success, data = self.getTocOfPage(url) if not success: alfred.exitWithFeedback(title=data) for item in data: if not search or (search is not None and item['name'].lower().find(search) > -1 ): feedback.addItem(title=item['name'], subtitle=item['subtitle'], arg= url + item['link']) feedback.output()
def showChannleEPG(channel): chl_title = getChannelTitle(channel) if not chl_title: alfred.exitWithFeedback(title='未找到频道信息') schedules = fetchChannelEPGToday(channel) if not schedules: alfred.exitWithFeedback(title='未找到频道的节目单') feedback = alfred.Feedback() date_str = datetime.now().strftime('%Y-%m-%d') now_time = datetime.now().strftime('%H:%M') is_faved = isChannelFaved(channel) feedback.addItem( title='{} {} 节目单 现在时间: {}'.format(chl_title, date_str, now_time), subtitle='已收藏,选择这项可以取消收藏。' if is_faved else '未收藏,选择这项可以收藏', arg='toggle-fav {}'.format(channel)) for item in schedules: feedback.addItem(title='{time} {show}'.format(**item)) feedback.output()
def outputFeedback(self, success, data, no_found_msg=''): if not success or not data: alfred.exitWithFeedback(title='No App Found', subtitle=no_found_msg) self.downloadAppIcon(data) feedback = alfred.Feedback() for app in data: icon = '' if self.enable_appiconshow: icon = self.getLocalAppIcon(app['icon']) links = '{},{}'.format(app['store'], app['link']) feedback.addItem(title=app['name'], subtitle=app['desc'], arg='open-link {}'.format(links), icon=icon if icon else '') feedback.output()
def showEPG(): channel = alfred.argv(2) if channel: return showChannleEPG(channel) favs = getFavChannels() if not favs: alfred.exitWithFeedback(title='你还没有收藏的频道') feedback = alfred.Feedback() for chl_id in favs: current, next = getCurrentAndNextProgram(chl_id) subtitle = '正在播放: {show}'.format(**current) if current else '' feedback.addItem(title=getChannelTitle(chl_id), subtitle=subtitle, arg=chl_id, autocomplete='epg {}'.format(chl_id), valid=False) feedback.output()
def query(): arg1 = alfred.argv(1) arg2 = alfred.argv(2) post_id = arg2 if arg2 else arg1 com_codes = arg1 if arg2 else None # 如果只有快递单号 没有公司代码 先自动检测获得公司代码 com_codes = [ surmiseCompanyCode(com_codes) ] if com_codes is not None else queryCompanyCodeByPostID(post_id) if not com_codes: alfred.exitWithFeedback(title='没有找到相关的快递信息') # 只有一个公司符合 直接给出结果 if len(com_codes) == 1: showSingle(com_codes[0], post_id) # 如果有多个 则列出公司列表 else: showRecommendCompany(com_codes, post_id)
def showCompanyList(): key = alfred.argv(2) companies = getCompany() if key: key = key.lower() companies = filter(lambda c: key in c['companyname'].lower() or key in c['code'], companies) if not companies: alfred.exitWithFeedback(title='没有找到相关的内容') feedback = alfred.Feedback() for com in companies: feedback.addItem( title = com['companyname'], subtitle = '代码: {} 电话: {} 官方网站: {}'.format(com['code'], com['tel'], com['comurl']), icon = getComponyLogo(com['code']), arg = 'open-url {}'.format(b64encode(com['comurl'])) ) feedback.output()
def search(self): title = alfred.argv(2) artist = alfred.argv(3) if title is None: self.outputiTunesPlayingSong() res, data = self.fetchLyricList(title, artist) if not res: alfred.exitWithFeedback( title=data, subtitle= "Format: lrc TITLE ARTIST e.g. lrc 'Heal The World' 'Michael Jackson'" ) feedback = alfred.Feedback() for lrc in data: feedback.addItem(title='{artist} - {title}'.format(**lrc), arg=lrc['id']) feedback.output()
def recent(): try: items = fetchRecentItems(alfred.argv(2)) if not items: alfred.exitWithFeedback(item=_fb_no_found) feedback = alfred.Feedback() for item in items: feedback.addItem( title = item['title'], subtitle = item['info'], icon = alfred.storage.getLocalIfExists(item['img'], True), valid = False, autocomplete = 'resource {} '.format(item['id']) ) feedback.output() except Exception, e: alfred.exitWithFeedback(item=_fb_no_found)
def showTaskDetail(self): task = self.getSingleTask(alfred.argv(3)) if not task: alfred.exitWithFeedback(title='ERROR', subtitle='No Task Found.') feedback = alfred.Feedback() # 任务标题 feedback.addItem( title = task['title'], subtitle = task['desc'], autocomplete = ' detail {id}'.format(**task), # 参数与现有相同 即无任何反应 valid = False ) status = task['status'] # 状态为 '等待'、'下载中' 显示暂停操作 if status in ['waiting', 'downloading']: feedback.addItem( title = 'Pause', arg = 'pause-task {id}'.format(**task) ) # 状态为 '暂停' 显示 恢复操作 if status in ['paused']: feedback.addItem( title = 'Resume', arg = 'resume-task {id}'.format(**task) ) # 状态为 '完成' 显示 清理操作 if status in ['finished']: feedback.addItem( title = 'Clear', arg = 'delete-task {id}'.format(**task) # 实际上就是删除已完成的任务 ) # 只有状态不是 '完成'、'完成中'才显示 删除操作 if status not in ['finished', 'finishing']: feedback.addItem( title = 'Delete', autocomplete = ' delete {id}'.format(**task), valid = False ) feedback.addItem( title = 'Show all', autocomplete = '', valid = False ) feedback.output()
def showTaskDetail(self): task = self.getSingleTask(alfred.argv(3)) if not task: alfred.exitWithFeedback(title='ERROR', subtitle='No Task Found.') feedback = alfred.Feedback() # 任务标题 feedback.addItem( title = task['title'], subtitle = task['desc'], autocomplete = ' detail {id}'.format(**task), # 参数与现有相同 即无任何反应 valid = False ) status = task['status'] # 状态为 '等待'、'下载中' 显示暂停操作 if status in ['waiting', 'downloading']: feedback.addItem( title = 'Pause', arg = 'pause-task {id}'.format(**task) ) # 状态为 '暂停' 显示 恢复操作 if status in ['paused']: feedback.addItem( title = 'Resume', arg = 'resume-task {id}'.format(**task) ) # 状态为 '完成' 显示 清理操作 if status in ['finished']: feedback.addItem( title = 'Clear', arg = 'delete-task {id}'.format(**task) # 实际上就是删除已完成的任务 ) # 只有状态不是 '完成'、'完成中'才显示 删除操作 if status not in ['finished', 'finishing']: feedback.addItem( title = 'Delete', autocomplete = ' delete {id}'.format(**task), valid = False ) feedback.addItem( title = 'Show all', autocomplete = '', valid = False ) feedback.output()
def showEPG(): channel = alfred.argv(2) if channel: return showChannleEPG(channel) favs = getFavChannels() if not favs: alfred.exitWithFeedback(title='你还没有收藏的频道') feedback = alfred.Feedback() for chl_id in favs: current, next = getCurrentAndNextProgram(chl_id) subtitle = '正在播放: {show}'.format(**current) if current else '' feedback.addItem( title = getChannelTitle(chl_id), subtitle = subtitle, arg = chl_id, autocomplete = 'epg {}'.format(chl_id), valid = False ) feedback.output()
def search(self): title = alfred.argv(2) artist = alfred.argv(3) if title is None: self.outputiTunesPlayingSong() res, data = self.fetchLyricList(title, artist) if not res: alfred.exitWithFeedback( title = data, subtitle = "Format: lrc TITLE ARTIST e.g. lrc 'Heal The World' 'Michael Jackson'" ) feedback = alfred.Feedback() for lrc in data: feedback.addItem( title = '{artist} - {title}'.format(**lrc), arg = lrc['id'] ) feedback.output()
def showCompanyList(): key = alfred.argv(2) companies = getCompany() if key: key = key.lower() companies = filter( lambda c: key in c['companyname'].lower() or key in c['code'], companies) if not companies: alfred.exitWithFeedback(title='没有找到相关的内容') feedback = alfred.Feedback() for com in companies: feedback.addItem(title=com['companyname'], subtitle='代码: {} 电话: {} 官方网站: {}'.format( com['code'], com['tel'], com['comurl']), icon=getComponyLogo(com['code']), arg='open-url {}'.format(b64encode(com['comurl']))) feedback.output()
def file(): try: ids = alfred.argv(2).split(',') res_id = int(ids[0]) file_ids = map(lambda i: int(i), ids[1:]) data = fetchSingleResource(res_id) files = filter(lambda f: int(f['id']) in file_ids, data['files']) feedback = alfred.Feedback() if not files: feedback.addItem(title='没有找到想要的内容', subtitle='这里可返回资源列表', valid=False, autocomplete='resource {} '.format(res_id), icon=alfred.storage.getLocalIfExists( data['img'], True)) elif len(files) == 1: subtitle = '类型: {format} 容量: {filesize} 这里可返回资源列表'.format( **files[0]) feedback.addItem(title=files[0]['filename'], subtitle=subtitle, valid=False, autocomplete='resource {} '.format(res_id), icon=alfred.storage.getLocalIfExists( data['img'], True)) feedback = fileDownloadFeedback(feedback, data['page'], files[0]['emule'], files[0]['magnet'], files[0]['baidu']) else: feedback.addItem(title='批处理多个文件', subtitle='{} 个文件, 这里可返回资源列表'.format(len(files)), valid=False, autocomplete='resource {}'.format(res_id), icon=alfred.storage.getLocalIfExists( data['img'], True)) emule = '\n'.join([f['emule'] for f in files]) magnet = '\n'.join([f['magnet'] for f in files]) feedback = fileDownloadFeedback(feedback, data['page'], emule, magnet) feedback.output() except Exception, e: alfred.exitWithFeedback(item=_fb_no_found())
def top(): try: items = fetchTopItems() if not items: alfred.exitWithFeedback(item=_fb_no_found) feedback = alfred.Feedback() count = 1 for item in items: feedback.addItem( title = '{:02d}. {}'.format(count, item['title']), subtitle = item['info'], icon = alfred.storage.getLocalIfExists(item['img'], True), valid = False, autocomplete = 'resource {id} '.format(**item) ) count = count + 1 feedback.output() except Exception, e: alfred.exitWithFeedback(item=_fb_no_found)
def query(): tryCleanCache() w = ' '.join(sys.argv[1:]).strip() try: ret = translate(w) is_eng = isEnglish(w) feedback = alfred.Feedback() translation = ret.get('translation', []) # 基本解释 basic = ret.get('basic', {}) phonetic = basic.get('phonetic') us_phonetic = basic.get('us-phonetic') uk_phonetic = basic.get('uk-phonetic') ph_out = [] us_phonetic and ph_out.append('美[{}]'.format(us_phonetic)) uk_phonetic and ph_out.append('英[{}]'.format(uk_phonetic)) if not ph_out and phonetic: ph_out.append('[{}]'.format(phonetic)) feedback.addItem( title = ' '.join(ph_out) if ph_out else w, subtitle = '译: {}'.format('; '.join(translation)) if translation else '', arg = w ) for e in basic.get('explains', []): feedback.addItem( title = e, autocomplete = None if is_eng else clearExplain(e), valid = False ) # 网络释义 web = ret.get('web', []) if web: feedback.addItem(title='--- 网络释义 ---', valid=False,) for w in web: feedback.addItem( title = w.get('key'), subtitle = '; '.join(w.get('value')), valid = False, autocomplete = w.get('key') ) feedback.output() except Exception, e: alfred.exitWithFeedback(title=w, subtitle='出错了,{}'.format(e), valid=False)
def query(): tryCleanCache() w = ' '.join(sys.argv[1:]).strip() try: ret = translate(w) is_eng = isEnglish(w) feedback = alfred.Feedback() translation = ret.get('translation', []) # 基本解释 basic = ret.get('basic', {}) phonetic = basic.get('phonetic') us_phonetic = basic.get('us-phonetic') uk_phonetic = basic.get('uk-phonetic') ph_out = [] us_phonetic and ph_out.append('美[{}]'.format(us_phonetic)) uk_phonetic and ph_out.append('英[{}]'.format(uk_phonetic)) if not ph_out and phonetic: ph_out.append('[{}]'.format(phonetic)) feedback.addItem(title=' '.join(ph_out) if ph_out else w, subtitle='译: {}'.format('; '.join(translation)) if translation else '', arg=w) for e in basic.get('explains', []): feedback.addItem(title=e, autocomplete=None if is_eng else clearExplain(e), valid=False) # 网络释义 web = ret.get('web', []) if web: feedback.addItem( title='--- 网络释义 ---', valid=False, ) for w in web: feedback.addItem(title=w.get('key'), subtitle='; '.join(w.get('value')), valid=False, autocomplete=w.get('key')) feedback.output() except Exception, e: alfred.exitWithFeedback(title=w, subtitle='出错了,{}'.format(e), valid=False)
def showChannleEPG(channel): chl_title = getChannelTitle(channel) if not chl_title: alfred.exitWithFeedback(title='未找到频道信息') schedules = fetchChannelEPGToday(channel) if not schedules: alfred.exitWithFeedback(title='未找到频道的节目单') feedback = alfred.Feedback() date_str = datetime.now().strftime('%Y-%m-%d') now_time = datetime.now().strftime('%H:%M') is_faved = isChannelFaved(channel) feedback.addItem( title = '{} {} 节目单 现在时间: {}'.format(chl_title, date_str, now_time), subtitle = '已收藏,选择这项可以取消收藏。' if is_faved else '未收藏,选择这项可以收藏', arg = 'toggle-fav {}'.format(channel) ) for item in schedules['epg']: feedback.addItem( title = '{time} {show}'.format(**item) ) feedback.output()
def query(): tryCleanCache() w = ' '.join(sys.argv[1:]).strip() try: ret = fetchData(w) if not ret: raise Exception('服务器访问失败。') # pprint(ret) if ret.get('errorCode', -1) != 0: error_msg = _error_desc.get(ret.get('errorCode', -1)) raise Exception(error_msg if error_msg else '未知错误。') is_eng = isEnglish(w) feedback = alfred.Feedback() # 有解释 basic = ret.get('basic', {}) phonetic = basic.get('phonetic', '') feedback.addItem( title='{} {}'.format(w, '[{}]'.format(phonetic) if phonetic else ''), subtitle='译: {}'.format('; '.join(ret.get('translation', []))), arg=w) for e in basic.get('explains', []): feedback.addItem(title=e, autocomplete=None if is_eng else clearExplain(e), valid=False) # 网络释义 web = ret.get('web', []) if web: feedback.addItem( title='--- 网络释义 ---', valid=False, ) for w in web: feedback.addItem(title=w.get('key'), subtitle='; '.join(w.get('value')), valid=False, autocomplete=w.get('key')) feedback.output() except Exception, e: alfred.exitWithFeedback(title=w, subtitle='出错了,{}'.format(e), valid=False)
def outputFeedback(self, success, data, no_found_msg=''): if not success or not data: alfred.exitWithFeedback( title = 'No App Found', subtitle = no_found_msg ) self.downloadAppIcon(data) feedback = alfred.Feedback() for app in data: icon = '' if self.enable_appiconshow: icon = self.getLocalAppIcon(app['icon']) links = '{},{}'.format(app['store'], app['link']) feedback.addItem( title = app['name'], subtitle = app['desc'], arg = 'open-link {}'.format(links), icon = icon if icon else '' ) feedback.output()
def showTabsByDevice(device_name): data = accessTabs() feedback = alfred.Feedback() for k in data['values'].keys(): d = data['values'][k]['value'] if not d['DeviceName'].lower().startswith(device_name.lower()): continue tabs_count = len(d.get('Tabs', {})) feedback.addItem(title=d['DeviceName'], subtitle='{} tabs. last modified: {}'.format( tabs_count, d['LastModified']), valid=False) for tab in d.get('Tabs', {}): feedback.addItem(title=tab['Title'], subtitle=tab['URL'], icon='icon-tabs.png', arg=tab['URL']) if feedback.isEmpty(): alfred.exitWithFeedback(title="Oops! Nothing found.", valid=False) feedback.output()
def file(): try: ids = alfred.argv(2).split(',') res_id = int(ids[0]) file_id = int(ids[1]) data = fetchSingleResource(res_id) fileinfo = filter(lambda f: int(f['id'])==file_id, data['files'])[0] feedback = alfred.Feedback() subtitle = '类型: {format} 容量: {filesize} 这里可返回资源列表'.format(**fileinfo) feedback.addItem( title = fileinfo['filename'], subtitle = subtitle, valid = False, autocomplete = 'resource {} '.format(res_id), icon = alfred.storage.getLocalIfExists(data['img'], True) ) feedback = fileDownloadFeedback(feedback, data['page'], fileinfo['emule'], fileinfo['magnet']) feedback.output() except Exception, e: alfred.exitWithFeedback(item=_fb_no_found)
def run(self): success, data = self.ds.fetchStatistic() if not success: alfred.exitWithFeedback(title = 'ERROR', subtitle = data) feedback = alfred.Feedback() # DS 信息 ds_info = alfred.cache.get('dsinfo') if ds_info: total = len(self.getTasks()) error = len(self.getErroneousTasks()) completed = len(self.getCompletedTasks()) paused = len(self.getSpecifiedStatusTask('paused')) waiting = len(self.getSpecifiedStatusTask('waiting')) downloading = len(self.getSpecifiedStatusTask('downloading')) feedback.addItem( title = 'Download Station v{}'.format(ds_info['version_string']), subtitle = '{} task(s), {} downloading, {} waiting, {} paused, {} error, {} completed,'.format( total, downloading, waiting, paused, error, completed ) ) download = dslibHumanReadable(data['speed_download']) upload = dslibHumanReadable(data['speed_upload']) feedback.addItem( subtitle = 'Total speed except for eMule', title = 'DL: {:8} UL: {}'.format(download, upload) ) if data.has_key('emule_speed_download'): download = dslibHumanReadable(data['emule_speed_download']) upload = dslibHumanReadable(data['emule_speed_upload']) feedback.addItem( subtitle = 'Total eMule speed', title = 'DL: {:8} UL: {}'.format(download, upload) ) else: feedback.addItem( title = 'eMule was disabled.' ) feedback.output()
def resource(): try: res_id = int(alfred.argv(2)) data = fetchSingleResource(res_id) files = data.get('files', []) files = filterItems(alfred.argv(3), files) if not data: alfred.exitWithFeedback(item=_fb_no_found) feedback = alfred.Feedback() feedback.addItem( title=data['title'], subtitle= '{} 个文件,可使用`文件名,格式`过滤,如:`s09` `,mp4` `s01e08,hdtv`,选择此项打开资源页面'. format(len(files)), arg='open-url {}'.format( b64encode(getResourcePageURLByID(data['id']))), icon=alfred.storage.getLocalIfExists(data['img'], True)) files_ids = [] for f in files: files_ids.append(f['id']) f.update(**parseDownloadHas(f)) subtitle = '类型: {format} 容量: {filesize} 电驴: {has_emule} 磁力链: {has_magnet} 百度盘: {has_baidu}'.format( **f) feedback.addItem( title=f['filename'], subtitle=subtitle, valid=False, autocomplete='file {},{}'.format(data['id'], f['id']), icon=alfred.storage.getLocalIfExists(data['img'], True)) if len(files_ids) > 1: feedback.addItem( title='所有文件', subtitle='对当前的所有文件进行批量处理', valid=False, autocomplete='file {},{}'.format(data['id'], ','.join(files_ids)), icon=alfred.storage.getLocalIfExists(data['img'], True)) feedback.addItem(item=_fb_return()) feedback.output() except Exception, e: alfred.exitWithFeedback(item=_fb_no_found())
def file(): try: ids = alfred.argv(2).split(',') res_id = int(ids[0]) file_ids = map(lambda i:int(i), ids[1:]) data = fetchSingleResource(res_id) files = filter(lambda f: int(f['id']) in file_ids, data['files']) feedback = alfred.Feedback() if not files: feedback.addItem( title = '没有找到想要的内容', subtitle = '这里可返回资源列表', valid = False, autocomplete = 'resource {} '.format(res_id), icon = alfred.storage.getLocalIfExists(data['img'], True) ) elif len(files) == 1: subtitle = '类型: {format} 容量: {filesize} 这里可返回资源列表'.format(**files[0]) feedback.addItem( title = files[0]['filename'], subtitle = subtitle, valid = False, autocomplete = 'resource {} '.format(res_id), icon = alfred.storage.getLocalIfExists(data['img'], True) ) feedback = fileDownloadFeedback(feedback, data['page'], files[0]['emule'], files[0]['magnet'], files[0]['baidu']) else: feedback.addItem( title = '批处理多个文件', subtitle = '{} 个文件, 这里可返回资源列表'.format(len(files)), valid = False, autocomplete = 'resource {}'.format(res_id), icon = alfred.storage.getLocalIfExists(data['img'], True) ) emule = '\n'.join( [f['emule'] for f in files] ) magnet = '\n'.join( [f['magnet'] for f in files] ) feedback = fileDownloadFeedback(feedback, data['page'], emule, magnet) feedback.output() except Exception, e: alfred.exitWithFeedback(item=_fb_no_found())
def run(self): success, data = self.ds.fetchStatistic() if not success: alfred.exitWithFeedback(title = 'ERROR', subtitle = data) feedback = alfred.Feedback() # DS 信息 ds_info = self.cache.get('dsinfo') if ds_info: total = len(self.getTasks()) error = len(self.getErroneousTasks()) completed = len(self.getCompletedTasks()) paused = len(self.getSpecifiedStatusTask('paused')) waiting = len(self.getSpecifiedStatusTask('waiting')) downloading = len(self.getSpecifiedStatusTask('downloading')) feedback.addItem( title = 'Download Station v{}'.format(ds_info['version_string']), subtitle = '{} task(s), {} downloading, {} waiting, {} paused, {} error, {} completed,'.format( total, downloading, waiting, paused, error, completed ) ) download = self.ds.humanReadable(data['speed_download']) upload = self.ds.humanReadable(data['speed_upload']) feedback.addItem( subtitle = 'Total speed except for eMule', title = 'DL: {:8} UL: {}'.format(download, upload) ) if data.has_key('emule_speed_download'): download = self.ds.humanReadable(data['emule_speed_download']) upload = self.ds.humanReadable(data['emule_speed_upload']) feedback.addItem( subtitle = 'Total eMule speed', title = 'DL: {:8} UL: {}'.format(download, upload) ) else: feedback.addItem( title = 'eMule was disabled.' ) feedback.output()
def query(): tryCleanCache() w = ' '.join(sys.argv[1:]).strip() try: ret = fetchData(w) if not ret: raise Exception('服务器访问失败。') # pprint(ret) if ret.get('errorCode', -1) != 0: error_msg = _error_desc.get(ret.get('errorCode', -1)) raise Exception(error_msg if error_msg else '未知错误。' ) is_eng = isEnglish(w) feedback = alfred.Feedback() # 有解释 basic = ret.get('basic', {}) phonetic = basic.get('phonetic', '') feedback.addItem( title = '{} {}'.format(w, '[{}]'.format(phonetic) if phonetic else ''), subtitle = '译: {}'.format('; '.join(ret.get('translation', []))), arg = w ) for e in basic.get('explains', []): feedback.addItem( title = e, autocomplete = None if is_eng else clearExplain(e), valid = False ) # 网络释义 web = ret.get('web', []) if web: feedback.addItem(title='--- 网络释义 ---', valid=False,) for w in web: feedback.addItem( title = w.get('key'), subtitle = '; '.join(w.get('value')), valid = False, autocomplete = w.get('key') ) feedback.output() except Exception, e: alfred.exitWithFeedback(title=w, subtitle='出错了,{}'.format(e), valid=False)
def showSettings(self): sub = alfred.argv(2) if sub == 'username': usr = alfred.argv(3) if alfred.argv(3) else '' old_usr = alfred.config.get('username') if alfred.config.get('username') else '' alfred.exitWithFeedback( title = 'Set AppShopper username', subtitle = 'new uername is {}, current: {}'.format(usr, old_usr), arg = 'set-username {}'.format(usr) ) feedback = alfred.Feedback() feedback.addItem( title = 'Set AppShopper Username', subtitle = 'you MUST config this if you want to see your wish list.', autocomplete = 'setting username ', valid = False ) feedback.addItem( title = 'Clean', subtitle = 'clear all cache', arg = 'clean' ) feedback.addItem( title = 'Change Country/Currency', subtitle = 'current: {}'.format( self.getContryDesc() ), autocomplete = 'change-country ', valid = False ) title = '{} App Icon Showing'.format('Enable' if not self.enable_appiconshow else 'Disable') feedback.addItem( title = title, subtitle = 'enable may take more time to fetch data.', arg = 'app-icon-showing {}'.format('enable' if not self.enable_appiconshow else 'disable') ) open_store_link = alfred.config.get('open_store_link', True) feedback.addItem( title = 'Open iTunes link or Appshopper link?', subtitle = 'current: {} link. select this item to change.'.format('iTunes' if open_store_link else 'Appshopper'), arg = 'switch-link-open-type' ) feedback.output()
def confimDeleteTask(self): task = self.getSingleTask(alfred.argv(3)) if not task: alfred.exitWithFeedback(title='ERROR', subtitle='task no found.') feedback = alfred.Feedback() feedback.addItem( title = 'Are you sure you want to delete task?', subtitle = task['title'], autocomplete = ' delete {id}'.format(**task), #! 同样的命令,不进行任何操作 valid = False ) feedback.addItem( title = 'Yes', arg = 'delete-task {id}'.format(**task) ) feedback.addItem( title = 'No', autocomplete = '', #! 返回任务列表 valid = False ) feedback.output()
def createTask(self): if not alfred.argv(3): alfred.exitWithFeedback(title='ERROR', subtitle='No TasK Found.') feedback = alfred.Feedback() tasks = util.parseURIInfo(alfred.argv(3)) if len(tasks) > 1: urls = [] for task in tasks: urls.append(task['original']) feedback.addItem( title = 'Create All', subtitle = 'find {} links'.format(len(tasks)), arg = 'create-task {}'.format(base64.b64encode(','.join(urls))) ) for task in tasks: feedback.addItem( title = task['original'], subtitle = 'Title: {filename:5} Size: {filesize}'.format(**task), arg = 'create-task {}'.format(base64.b64encode(task['original'])) ) feedback.output()
def todayFile(): try: data = json.loads(b64decode(alfred.argv(2))) res_id = os.path.basename(data['page']) feedback = alfred.Feedback() feedback.addItem( title = data['filename'], subtitle = '类别: {type} 格式: {format} 容量: {size} 日期: {date} 这里可访问资源文件列表'.format(**data), valid = False, autocomplete = 'resource {}'.format(res_id) ) feedback = fileDownloadFeedback(feedback, data['page'], data['emule'], data['magnet']) feedback.addItem( title = '返回 今日文件更新', subtitle = '', valid = False, autocomplete = 'today' ) feedback.output() except Exception, e: alfred.exitWithFeedback(item=_fb_no_found)
def todayFile(): if not isLogined(): alfred.exitWithFeedback(item=_fb_no_logined()) try: item_id = alfred.argv(2) res_id = item_id.split('-')[0] item = {} for item in fetchTodayItems(): if item.get('id') == item_id: break if not item: alfred.exitWithFeedback(item=_fb_no_found()) feedback = alfred.Feedback() feedback.addItem( title=item['filename'], subtitle= '类别: {type} 格式: {format} 容量: {filesize} 日期: {update_date} 这里可访问资源文件列表' .format(**item), valid=False, autocomplete='resource {}'.format(res_id)) feedback = fileDownloadFeedback(feedback, res_id, item['emule'], item['magnet'], item['baidu']) feedback.addItem(item=_fb_return()) feedback.output() except Exception, e: alfred.exitWithFeedback(item=_fb_no_found())
def today(): try: items = fetchTodayItems() filter_str = alfred.argv(2) if filter_str: filter_str = filter_str.upper() items = filter(lambda i: filter_str in i['format'], items) if not items: alfred.exitWithFeedback(item=_fb_no_found) feedback = alfred.Feedback() for item in items: item['has_emule'] = '有' if item['emule'] else '无' item['has_magnet'] = '有' if item['magnet'] else '无' subtitle = '类别: {type} 格式: {format} 容量: {size} 日期: {date} 电驴: {has_emule} 磁力链: {has_magnet}'.format(**item) feedback.addItem( title = item['filename'], subtitle = subtitle, valid = False, autocomplete = 'today-file {}'.format(b64encode( json.dumps(item) )) ) feedback.output() except Exception, e: alfred.exitWithFeedback(item=_fb_no_found)