async def get_client_debug(self, request): name = request.match_info['client_name'] manager = None for managers in self.orchestrator.managers_by_realm.values(): for realm_manager in managers: if realm_manager.name == name: manager = realm_manager if not manager: return JsonResponse({'detail': 'Manager not found'}, status=404) return JsonResponse(manager.get_debug_dict(), compact=False)
def get_service(origin): "Fetches a service by origin, as well as a list of UIDs (corresponding to unique identities)." service = paranoid.get_service(origin) if not service: return JsonResponse() uids = paranoid.get_service_uids(origin) return JsonResponse({ 'info': service, 'uids': uids, })
async def force_recheck(self, request): realm = Realm.select().where(Realm.name == request.match_info['realm_name']).first() if not realm: return JsonResponse({'detail': 'Realm does not exist. Create it by adding a client to it.'}, status=400) try: await self.orchestrator.force_recheck( realm=realm, info_hash=request.match_info['info_hash'] ) return JsonResponse({}) except TorrentNotFoundException: return JsonResponse({'detail': 'Torrent not found.'}, status=404) except asyncio.TimeoutError: return JsonResponse({'detail': 'Alcazar is busy performing another action. Try again later.'}, status=503)
def get_service_identity(origin, uid): "Fetches a list of fields and their values for a service identity." # Read service identity info = paranoid.get_service_identity(origin, uid) if info is None: return JsonResponse() # Read individual service identity field mappings info['map'] = {} for field in info.get('fields'): data = paranoid.decrypt_data_file(origin, uid, field) if data is not None: info['map'][field] = data return JsonResponse(info)
def put_service(origin): "Upserts a service by origin." data = request.get_json() paranoid.set_service(origin, data) return JsonResponse()
def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = super_exception_handler(exc, context) # default code status_code = '500' if response is None: return JsonResponse(context,status_code) # Now add the HTTP status code to the response. if response.status_code: status_code = str(response.status_code) return JsonResponse(context,status_code,response.data['detail'], exception=True,content_type=response.content_type)
def unshare_service_identity_mapping(origin, uid, field_name, username): "Unshares a field with a Keybase user." # Read service identity info = paranoid.get_service_identity(origin, uid) if info is None: raise ParanoidException( 'Service identity does not exist for {}:{}'.format(origin, uid)) # Validate field name paranoid.validate_field_name(info, field_name) # Get list of shared users for this field mapping shared_users = info['fields'][field_name].get('shared_with', []) # Make sure username is shared with if username not in shared_users: raise ParanoidException('"{}" did not have access to {}:{}'.format( username, origin, uid)) # Remove username from list of shared users shared_users.remove(username) # Re-encrypt the file with the new list of shared users paranoid.reencrypt_data_file(origin, uid, field_name, shared_users) # If there is no error, update the identity metadata info['fields'][field_name]['shared_with'] = shared_users paranoid.set_service_identity(origin, uid, info) return JsonResponse()
async def post_clients(self, request): data = await request.json() with DB.atomic(): realm = Realm.select().where(Realm.name == data['realm']).first() if not realm: realm = Realm.create(name=data['realm']) try: instance = self.orchestrator.add_instance( realm=realm, instance_type=data['instance_type'], config_kwargs=data.get('config', {}), ) except asyncio.TimeoutError: return JsonResponse( data={'detail': 'Alcazar is busy performing another action. Try again later.'}, status=503, ) return JsonResponse(instance.get_info_dict())
async def execute_method(self, id, req_method, req_args, req_kwargs): xpub = req_kwargs.pop("xpub", None) wallet, cmd, config, error = await self._get_wallet(id, req_method, xpub) if error: return error.send() exec_method, custom, error = await self.get_exec_method(cmd, id, req_method) if error: return error.send() if self.get_method_data(req_method, custom).requires_wallet and not xpub: return JsonResponse(code=-32000, error="Wallet not loaded", id=id).send() try: result = await self.get_exec_result( xpub, req_method, req_args, req_kwargs, exec_method, custom, wallet=wallet, config=config ) return JsonResponse(result=result, id=id).send() except BaseException as e: error_message = self.get_exception_message(e) return JsonResponse(code=self.get_error_code(error_message), error=error_message, id=id).send()
async def get_clients(self, request): manager_data = [] for managers in self.orchestrator.managers_by_realm.values(): for manager in managers: manager_data.append(manager.get_info_dict()) return JsonResponse({ 'clients': manager_data, })
async def get_handle_request_params(self, request): data = await (request.json() if LEGACY_AIOHTTP else request.json( content_type=None)) method, id, params = data.get("method"), data.get("id", None), data.get( "params", []) error = None if method else JsonResponse( code=-32601, error="Procedure not found", id=id) args, kwargs = parse_params(params) return id, method, args, kwargs, error
async def post_torrents(self, request): data = await request.json() realm = Realm.select().where(Realm.name == request.match_info['realm_name']).first() if not realm: return JsonResponse({'detail': 'Realm does not exist. Create it by adding a client to it.'}, status=400) try: data = await self.orchestrator.add_torrent( realm=realm, torrent_file=base64.b64decode(data['torrent']), download_path=data['download_path'], name=data.get('name'), ) except (NotInitializedException, NoManagerForRealmException) as exc: return JsonResponse({'detail': str(exc)}, status=400) except TorrentAlreadyAddedException as exc: return JsonResponse({'detail': str(exc)}, status=409) except asyncio.TimeoutError: return JsonResponse({'detail': 'Alcazar is busy performing another action. Try again later.'}, status=503) return JsonResponse(data)
async def _get_wallet(self, id, req_method, xpub): wallet = cmd = config = error = None try: wallet, cmd, config = await self.load_wallet(xpub) except Exception as e: if req_method not in self.supported_methods or self.supported_methods[req_method].requires_wallet: error = JsonResponse( code=self.get_error_code(self.get_exception_message(e), fallback_code=-32005), error="Error loading wallet", id=id, ) return wallet, cmd, config, error
async def get_exec_method(self, cmd, id, req_method): error = None exec_method = None if req_method in self.supported_methods: exec_method, custom = self.supported_methods[req_method], True else: custom = False if hasattr(cmd, req_method): exec_method = getattr(cmd, req_method) else: error = JsonResponse(code=-32601, error="Procedure not found", id=id) return exec_method, custom, error
def test_list(request): "An example view" from wrcc.wea_server.libwea.products.listers import test_list stn = request.args.get('stn', None) if stn is None: return ErrorResponse("'stn' argument required.") sD = datetime.datetime(2011, 12, 7, 14) eD = datetime.datetime(2011, 12, 7, 15) try: result = test_list(stn, sD, eD) except IOError: return ErrorResponse("No data available.") return JsonResponse(result)
def getStnDates(request): from wrcc.wea_server.libwea.products.listers import getStnDates error = require(request, ['stn']) if error: return ErrorResponse(error) stn = request.args.get('stn') try: result = getStnDates(stn) except IOError: return ErrorResponse("No data available.") return JsonResponse(result)
def getMostRecentData(request): from wrcc.wea_server.libwea.products.listers import getMostRecentData error = require(request, ['stn']) if error: return ErrorResponse(error) stn = request.args.get('stn') eD = parse_date(request.args.get('eD', None)) units_system = request.args.get('units', 'N') # N (native) units by default try: result = getMostRecentData(stn, eD, units_system=units_system) except IOError: return ErrorResponse("No data available.") return JsonResponse(result)
def getDataSingleDay(request): from wrcc.wea_server.libwea.products.listers import getDataSingleDay error = require(request, ['stn', 'sD']) if error: return ErrorResponse(error) stn = request.args.get('stn') sD = parse_date(request.args.get('sD')) units_system = request.args.get('units', 'N') # N (native) units by default try: result = getDataSingleDay(stn, sD, units_system=units_system) except IOError: return ErrorResponse("No data available.") return JsonResponse(result)
def share_service_identity_mapping(origin, uid, field_name, username): "Shares a field with a Keybase user." # Read service service = paranoid.get_service(origin) if service is None: raise ParanoidException( 'Service does not exist for origin {}'.format(origin)) # Read service identity info = paranoid.get_service_identity(origin, uid) if info is None: raise ParanoidException( 'Service identity does not exist for {}:{}'.format(origin, uid)) # Validate field name paranoid.validate_field_name(info, field_name) # Get list of shared users for this field mapping shared_users = info['fields'][field_name].get('shared_with', []) # Make sure username is not already shared with if username in shared_users: raise ParanoidException('"{}" already has access to {}:{}'.format( username, origin, uid)) # Add username to list of shared users shared_users.append(username) # Re-encrypt the file with the new list of shared users paranoid.reencrypt_data_file(origin, uid, field_name, shared_users) # If there is no error, update the identity metadata info['fields'][field_name]['shared_with'] = shared_users paranoid.set_service_identity(origin, uid, info) # Send a share request. # We send the full origin (stored in the service) instead of the origin key. full_origin = service.get('origin') paranoid.send_share_request(full_origin, uid, field_name, username) return JsonResponse()
def put_service_identity_mapping(origin, uid, field_name): "Updates an identity mapping for a service." # Read service identity info = paranoid.get_service_identity(origin, uid) if info is None: raise ParanoidException( 'Service identity does not exist for {}:{}'.format(origin, uid)) # Validate field name paranoid.validate_field_name(info, field_name) # Get list of shared users for this field mapping shared_users = info['fields'][field_name].get('shared_with', []) # Encrypt the data file with the list of shared users paranoid.encrypt_data_file(origin, uid, field_name, request.data.decode('utf-8'), shared_users) return JsonResponse()
def put_service_identity(origin, uid): "Inserts an identity for a service." # Get service service = paranoid.get_service(origin) if service is None: raise ParanoidException( 'Service does not exist for origin: {}'.format(origin)) # Make sure that service identity doesn't already exist if paranoid.get_service_identity(origin, uid) is not None: raise ParanoidException( 'Service identity already exists for {}:{}'.format(origin, uid)) # Decode request data as JSON data = request.get_json() key = data.get('key') field_names = data.get('fields') if not key: raise ParanoidException('Service identity key not specified') if not field_names: raise ParanoidException('Service identity fields not specified') # Prepare identity metadata object info = { 'origin': service.get('origin'), 'uid': uid, 'key': key, 'fields': {}, } for field_name in field_names: info['fields'][field_name] = { 'type': 'str', 'shared_with': [], } # Store identity metadata paranoid.set_service_identity(origin, uid, info) return JsonResponse()
def targeting_stats(request, ad_id=None): ''' Return targeting audiency and recommended bid ''' kwargs = dict([(k, v) for k, v in request.POST.items() if k[:6] in ['layout', 'target']]) if 'account_id' in request.POST: try: account = Account.objects.get(id=request.POST['account_id']) except: pass elif ad_id: try: account = Ad.objects.get(id=ad_id).account except: pass stat = TargetingStats.remote.get(ad=Ad(account=account, **kwargs)) response = stat.__dict__ del response['_state'] return JsonResponse(response)
def get(self, request, *args, **kwargs): print(request.GET) print('args:', args) print('kwargs:', kwargs) return JsonResponse({})
def get_service_foreign_map(origin): "Fetches a foreign map for a service." foreign_map = paranoid.resolve_foreign_map(origin) return JsonResponse(foreign_map)
def get_services(): "Fetches a list of services." origins = paranoid.get_origins() return JsonResponse(origins)
def add_foreign_map(origin, uid, field_name, username): "Adds a foreign map mapping for an origin." paranoid.add_foreign_map(origin, uid, field_name, username) return JsonResponse()
async def post_pop_update_batch(self, request): limit = int(request.query.get('limit', '10000')) realm_batches = self.orchestrator.pop_update_batch_dicts(limit) return JsonResponse(realm_batches)
async def ping(self, request): return JsonResponse({'success': True})
async def get_config(self, request): return JsonResponse(self.config.to_dict())
async def put_config(self, request): data = await request.json() with DB.atomic(): self.config.update_from_dict(data) self.config.save() return JsonResponse(self.config.to_dict())