from typing import Callable, Optional from server.db.models import Settings def set_single_settings(data: list): """Set single settings item. Args: data: List of accounts. """ for item in data: if item.settings: item.settings_item = item.settings[0] async def migrate_settings_v1_to_v2(account_id: int, subtype: str): """Migrates settings from version 1 to version 2 Description: Example settings version 1: {"markets": ["global"], "vendors": {"apple": true, "spotify": false}, "notifications": true} Example settings version 2: { "markets": [ "global" ], "categories": { "charts": { "apple_top_100": true, "spotify_top_200": false }, "starred_tracks": { "apple": true, "spotify": false }, "starred_playlists": { "apple": true, "spotify": false } }, "notifications": true } """ setting = await Settings.get(account_id=account_id, type=subtype, version=1) if not setting: return None data = setting.data categories = { "charts": {"apple": False, "spotify": False}, "starred_tracks": {"apple": False, "spotify": False}, "starred_playlists": {"apple": False, "spotify": False}, } vendors = data.pop("vendors", {}) for vendor, value in vendors.items(): if vendor == "apple" and value is True: categories["starred_tracks"]["apple"] = True categories["starred_playlists"]["apple"] = True categories["charts"]["apple"] = True if vendor == "spotify" and value is True: categories["starred_tracks"]["spotify"] = True categories["starred_playlists"]["spotify"] = True categories["charts"]["spotify"] = True data["categories"] = categories return await Settings.update({"data": data, "version": 2}, id=setting.id, return_source=Settings) USER_SETTING_HANDLER = {2: migrate_settings_v1_to_v2} def settings_migration_handler(version: int) -> Optional[Callable[[], None]]: """Get handler to migrate previous user settings if possible Args: version: str - version of user settings Returns: Handler for a current version or None """ return USER_SETTING_HANDLER.get(version)