def delete(*args, **kwargs): headers = { 'X-Access-Token': appconfig.get('provider_config', 'access-token'), 'X-Client-ID': appconfig.get('provider_config', 'client-id') } resp = requests.delete(*args, headers=headers, **kwargs) return resp.status_code == 204
def get_item(category, item_id): """ Returns item with id `item_id` belonging to category `category` from your Bucket List. If item is not present, the function returns None Args: category: Category to which item belongs. type -> BucketlistCategory item_id: Id of the item that is to be fetched. type -> str Returns: Returns item with id `item_id` stored in your Bucket List. type -> BucketlistItem """ assert type(category) == BucketlistCategory assert type(item_id) == str folder_path = appconfig.get('provider_config', 'data-dir') localfs_api.validate_init(folder_path) if not localfs_api.category_exists(folder_path, category.name): raise BucketlistError("Category {} does not exists.".format( category.name)) task = localfs_api.get_item(folder_path, category.name, item_id) if task is None: return None return BucketlistItem(task['id'], task['message'], task['completed'])
def mark_as_complete(category, item): """ Marks an item `item` belonging to category `category` as complete in your Bucket List. Args: category: Category to which message should belong. type -> BucketlistCategory item: Item to be marked as complete. type -> BucketlistItem Returns: Returns updated item `item` in your Bucket List. type -> BucketlistItem """ assert type(category) == BucketlistCategory assert type(item) == BucketlistItem folder_path = appconfig.get('provider_config', 'data-dir') localfs_api.validate_init(folder_path) if not localfs_api.category_exists(folder_path, category.name): raise BucketlistError("Category {} does not exists.".format( category.name)) task = localfs_api.update_item(folder_path, category.name, item.id, completed=True) return BucketlistItem(task['id'], task['message'], task['completed'])
def add_item(category, item): """ Adds item `item` to category `category` in your Bucket List. Args: category: Category to which message should belong. type -> BucketlistCategory item: Item to be stored in Bucket List under category `category`. type -> BucketlistItem Returns: Returns item saved in your Bucket List. type -> BucketlistItem """ assert type(category) == BucketlistCategory assert type(item) == BucketlistItem folder_path = appconfig.get('provider_config', 'data-dir') localfs_api.validate_init(folder_path) if not localfs_api.category_exists(folder_path, category.name): localfs_api.create_category(folder_path, category.name) item_id = localfs_api.create_item(folder_path, category.name, item.message) return BucketlistItem(item_id, item.message, False)
def get_items(category, completed=False): """ Gets all items from your Bucket List that belongs to category `category`. Args: category: Category. type -> BucketlistCategory Keyword Args: completed: if True -> fetches all completed items from Bucket List other wise fetches Pending items Returns: Returns list of items that saved in your Bucket List. type -> List<BucketlistItem> """ assert type(category) == BucketlistCategory folder_path = appconfig.get('provider_config', 'data-dir') localfs_api.validate_init(folder_path) if not localfs_api.category_exists(folder_path, category.name): raise BucketlistError("Category {} does not exit.".format( category.name)) items = localfs_api.get_items(folder_path, category.name, completed=completed) return [ BucketlistItem(i['id'], i['message'], completed) for i in items ]
def add_item(category, item): """ Adds item `item` to category `category` in your Bucket List. Args: category: Category to which message should belong. type -> BucketlistCategory item: Item to be stored in Bucket List under category `category`. type -> BucketlistItem Returns: Returns item saved in your Bucket List. type -> BucketlistItem """ assert type(category) == BucketlistCategory assert type(item) == BucketlistItem folder_name = appconfig.get('provider_config', 'folder-name') folder = wunderlist_api.get_folder(folder_name) try: wlist = wunderlist_api.get_list(folder, category.name) except BucketlistError: wlist = wunderlist_api.create_list(folder, category.name) task = wunderlist_api.create_task(wlist, item.message) return BucketlistItem(str(task['id']), task['title'], task['completed'])
def execute(argv=None, settings=None): if argv is None: argv = sys.argv[1:] if len(argv) == 0: print("usage: bucket-list <command> <args supported by commands>") print( "\ncommands:", "\n add: The add command adds a new item in your bucket", "\n list for a category.", "\n backup: The backup command takes a local backup of all", "\n your items from your provider.", "\n clean: The clean command deletes all the data under", "\n bucket-list and or created by bucket-list from", "\n your current provider.", "\n config: The config command is used get and set various", "\n configuration values and customizations.", "\n init: The init command reads the preferred provider name", "\n and initialises it." "\n mark: The mark command marks an item in your bucket", "\n list as completed.", "\n restore: The restore command takes your local backup", "\n (create from backup command) and create corresponding", "\n items in your current provider.", "\n view: The view command lists all items in your bucket", "\n list for a category.", ) print("\nFor more details you can refer official documentation here:", "\nhttps://github.com/arpitbbhayani/bucket-list/wiki") return command_str = argv.pop(0) command = commands.get(command_str) if command is None: speedyio.error("Invalid commmand {}".format(command_str)) return try: command.execute(argv) except BucketlistError as e: speedyio.error("{}".format(e.description)) except speedyio.SpeedyIOError as e: speedyio.error("{}".format(e.description)) except getopt.GetoptError as e: speedyio.error(str(e)) except configparser.NoOptionError as e: speedyio.error("Config '{}' under '{}' not set \u2639".format( e.option, e.section)) speedyio.info("Run `bucket-list config --set {}.{} <value>`".format( e.section, e.option)) except PermissionError as e: speedyio.error(str(e)) except KeyboardInterrupt: speedyio.error("The process was killed \u2639") except Exception as e: logger.exception(e) speedyio.error( "Something went really bad \u2639 Check the logs ({}) for more details." .format(appconfig.get('logging', 'file')))
def patch(*args, **kwargs): headers = { 'X-Access-Token': appconfig.get('provider_config', 'access-token'), 'X-Client-ID': appconfig.get('provider_config', 'client-id') } resp = None for _ in range(WRequests.MAX_RETRIES): try: resp = requests.patch(*args, headers=headers, **kwargs).json() except json.decoder.JSONDecodeError: resp = None else: break raise_if_error(resp) return resp
def clean(): """ Removes all items and any metadata created in your provider. Returns: None """ folder_path = appconfig.get('provider_config', 'data-dir') localfs_api.validate_init(folder_path) localfs_api.delete_folder(folder_path)
def get_categories(): """ Gets all items from your Bucket List that belongs to category `category`. Returns: Returns list of categories in your Bucket List. type -> List<BucketlistCategory> """ folder_name = appconfig.get('provider_config', 'folder-name') folder = wunderlist_api.get_folder(folder_name) return [BucketlistCategory(l.get('title')) for l in wunderlist_api.get_lists(folder)]
def clean(): """ Removes all items and any metadata created in your provider. Returns: None """ folder_name = appconfig.get('provider_config', 'folder-name') folder = wunderlist_api.get_folder(folder_name) wlists = wunderlist_api.get_lists(folder) for l in wlists: wunderlist_api.delete_list(l['id'])
def init(): """ Initializes the provider. It sets up all necessary items/metadata in the provider. Returns: None """ folder_name = appconfig.get('provider_config', 'folder-name') try: folder = wunderlist_api.get_folder(folder_name) except BucketlistError: wlist = wunderlist_api.create_dummy_list() folder = wunderlist_api.create_folder(folder_name, [wlist.get('id')])
def execute(self, argv): Provider = get_current_provider() optlist, args = getopt.getopt(argv, '', ['file=', 'help']) optmap = {opt[0].lstrip('-'): opt[1] for opt in optlist} if 'help' in optmap: print("usage: bucket-list backup [options]", "\n options:", "\n --file absolute path of backup file", "\n --help prints help") print( "\nFor more details you can refer official documentation here:", "\nhttps://github.com/arpitbbhayani/bucket-list/wiki/backup") return if 'file' not in optmap: optmap['file'] = speedyio.askfor('file', empty_allowed=False) try: with open(optmap['file'], 'w') as f: f.write('') except Exception as e: raise BucketlistError(str(e)) provider_name = appconfig.get('provider', 'name') backup_data = { 'provider': provider_name, } data = {} categories = Provider.get_categories() speedyio.info("{} categories fetched".format(len(categories))) for category in categories: tasks_incomplete = Provider.get_items(category, completed=False) speedyio.info("{} incomplete items fetched for category {}".format( len(tasks_incomplete), category.name)) tasks_complete = Provider.get_items(category, completed=True) speedyio.info("{} completed items fetched for category {}".format( len(tasks_complete), category.name)) data[category.name] = [ t.__dict__ for t in tasks_incomplete + tasks_complete ] backup_data['data'] = data self.dump(backup_data, optmap['file']) speedyio.success("Backup successfully created at {}".format( optmap['file']))
def get_categories(): """ Gets all items from your Bucket List that belongs to category `category`. Returns: Returns list of categories in your Bucket List. type -> List<BucketlistCategory> """ folder_path = appconfig.get('provider_config', 'data-dir') localfs_api.validate_init(folder_path) return [ BucketlistCategory(name) for name in localfs_api.get_categories(folder_path) ]
def init(): """ Initializes the provider. It sets up all necessary items/metadata in the provider. Returns: None """ folder_path = appconfig.get('provider_config', 'data-dir') try: localfs_api.validate_init(folder_path) except BucketlistError as e: if e.error_code == 'file_instead_of_folder': raise e if not localfs_api.folder_exists(folder_path): localfs_api.create_folder(folder_path)
def create_category(category_name): """ Creates a category with name `category_name` in your Bucket List if any category with same name do not already exist. Args: category_name: Category name. type -> str Returns: Returns category saved in your Bucket List. type -> BucketlistCategory """ type(category_name) == str folder_name = appconfig.get('provider_config', 'folder-name') folder = wunderlist_api.get_folder(folder_name) try: wlist = wunderlist_api.get_list(folder, category_name) except BucketlistError: wlist = wunderlist_api.create_list(folder, category_name) return BucketlistCategory(wlist.get('title'))
def get_items(category, completed=False): """ Gets all items from your Bucket List that belongs to category `category`. Args: category: Category. type -> BucketlistCategory Keyword Args: completed: if True -> fetches all completed items from Bucket List other wise fetches Pending items Returns: Returns list of items that saved in your Bucket List. type -> List<BucketlistItem> """ assert type(category) == BucketlistCategory folder_name = appconfig.get('provider_config', 'folder-name') folder = wunderlist_api.get_folder(folder_name) wlist = wunderlist_api.get_list(folder, category.name) tasks = wunderlist_api.get_tasks(wlist, completed=completed) return [BucketlistItem(str(task['id']), task['title'], task['completed']) for task in tasks]
def create_category(category_name): """ Creates a category with name `category_name` in your Bucket List if any category with same name do not already exist. Args: category_name: Category name. type -> str Returns: Returns category saved in your Bucket List. type -> BucketlistCategory """ type(category_name) == str folder_path = appconfig.get('provider_config', 'data-dir') localfs_api.validate_init(folder_path) if localfs_api.category_exists(folder_path, category_name): raise BucketlistError( "Category {} already exists.".format(category_name)) localfs_api.create_category(folder_path, category_name) return BucketlistCategory(category_name)
def execute(self, argv): Provider = get_current_provider() optlist, args = getopt.getopt(argv, '', ['file=', 'help']) optmap = {opt[0].lstrip('-'): opt[1] for opt in optlist} if 'help' in optmap: print( "usage: bucket-list restore [options]", "\n options:", "\n --file absolute path of your backup file to be restored", "\n --help prints help") print( "\nFor more details you can refer official documentation here:", "\nhttps://github.com/arpitbbhayani/bucket-list/wiki/restore") return if 'file' not in optmap: optmap['file'] = speedyio.askfor('file', empty_allowed=False) provider_name = appconfig.get('provider', 'name') backedup_data = self.read(optmap['file']) try: Provider.clean() speedyio.info("Cleanup done") Provider.init() speedyio.info("Provider initialized") validate_backedup_data(backedup_data) for category_name, items in backedup_data.get('data').items(): speedyio.info( "Restoring data for category {}".format(category_name)) category = Provider.get_category(category_name) if category is None: category = Provider.create_category(category_name) for item in items: bucketlist_item = Provider.get_item(category, item['id']) if bucketlist_item is None: bucketlist_item = Provider.add_item( category, BucketlistItem(None, item['message'], False)) if bucketlist_item.is_completed is False and item[ 'is_completed'] is True: Provider.mark_as_complete(category, bucketlist_item) except BucketlistError as e: speedyio.error( "Data restored failed from {}.\nPlease try again.".format( optmap['file'])) speedyio.error(e.description) except Exception as e: logger.exception(e) speedyio.error( "Data restored failed from {}.\nPlease check logs ({}).". format(optmap['file'], appconfig.get('logging', 'file'))) else: speedyio.success("Data restored from {}".format(optmap['file']))
def execute(self, argv): optlist, args = getopt.getopt( argv, '', ['set=', 'get=', 'set-provider=', 'help']) optmap = {opt[0].lstrip('-'): opt[1] for opt in optlist} if 'help' in optmap: print( "usage: bucket-list config [options]", "\n options:", "\n --get prints value of config set in your config file", "\n --set sets value for config in your config file", "\n --set-provider change your provider", "\n --help prints help") print( "\nFor more details you can refer official documentation here:", "\nhttps://github.com/arpitbbhayani/bucket-list/wiki/config") return if 'set-provider' in optmap: if optmap['set-provider'] not in SUPPORTED_PROVIDERS: raise BucketlistError("Unsupported provider '{}'".format( optmap['set-provider'])) appconfig.put('provider', 'name', optmap['set-provider']) appconfig.init(optmap['set-provider']) speedyio.info( "Since you changed the provider. You must run `bucket-list init`." ) elif 'set' in optmap: if len(args) == 0: raise BucketlistError( "Value for config '{}' not provided.".format( optmap['set'])) config_name = optmap['set'] if config_name == 'provider.name': raise BucketlistError( "You cannot change provider name like this.\n" + "In case you want to change the provider please run following command.\n" + " bucket-list config --set-provider <provider_name>") tokens = config_name.split('.') if len(tokens) != 2: raise BucketlistError("Invalid config '{}'.".format( optmap['set'])) appconfig.put(tokens[0], tokens[1], args[0]) if tokens[0] == 'provider_config': speedyio.info( "Since you changed the config oy your provider. You must run `bucket-list init`." ) elif 'get' in optmap: config_name = optmap['get'] tokens = config_name.split('.') if len(tokens) != 2: raise BucketlistError( "Invalid config '{}'".format(config_name)) speedyio.plain_print(appconfig.get(tokens[0], tokens[1]))