forked from Blendman974/faceclaw
Unify Android and iOS config formats
This commit is contained in:
1 parent
35a4ae7064
commit
210b111e27
18 files changed
+1116
-427
No files matched your search
@@ -0,0 +1,76 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const { readFileSync, readdirSync, statSync } = require('node:fs');
|
||||
const { join } = require('node:path');
|
||||
|
||||
test('config_document converts Android XML, passes JSON documents through and rejects unusable files', () => {
|
||||
execFileSync('python3', ['-c', `
|
||||
import importlib.util, json, pathlib, sys, tempfile
|
||||
sys.path.insert(0, 'scripts')
|
||||
spec = importlib.util.spec_from_file_location('ios_config', 'scripts/ios_config.py')
|
||||
ios = importlib.util.module_from_spec(spec); spec.loader.exec_module(ios)
|
||||
import config_document as m
|
||||
xml = b'''<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
|
||||
<map>
|
||||
<string name="terminal.connections">[{"url":"g2mirror://test@host"}]</string>
|
||||
<boolean name="flag" value="true" />
|
||||
<string name="empty"></string>
|
||||
<long name="number" value="42" />
|
||||
<float name="ratio" value="0.25" />
|
||||
<string name="unicode">π & < 🔋 next</string>
|
||||
</map>'''
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = pathlib.Path(d) / 'settings'
|
||||
p.write_bytes(xml)
|
||||
doc = json.loads(m.read_document(p))
|
||||
assert doc['schema'] == 1 and doc['platform'] == 'android', doc
|
||||
assert doc['settings'] == {'terminal.connections': '[{"url":"g2mirror://test@host"}]', 'flag': True, 'empty': '', 'number': 42, 'ratio': 0.25, 'unicode': '\\u03c0 & < \\U0001f50b\\nnext'}, doc
|
||||
text = json.dumps({'schema': 2, 'platform': 'ios', 'settings': {'a': [1, {'b': None is None}]}, 'platformSettings': {'ios.x': 'y'}})
|
||||
p.write_text(text)
|
||||
assert m.read_document(p) == text
|
||||
ios.atomic_write(p, b'{}')
|
||||
assert p.stat().st_mode & 0o777 == 0o600
|
||||
for invalid in [b'{}', b'[]', b'{"schema":3,"settings":{}}', b'{"schema":true,"settings":{}}', b'{"schema":2.0,"settings":{}}', b'{"schema":2}',
|
||||
b'{"schema":2,"settings":{"x":null}}', b'{"schema":2,"settings":{"x":NaN}}', b'{"schema":2,"settings":{"x":1e999}}',
|
||||
b'{"schema":2,"settings":{"x":1,"x":2}}', b'{"schema":2,"settings":{},"platformSettings":[]}',
|
||||
b'{"schema":2,"platform":1,"settings":{}}', b'{"schema":2,"settings":{"":"x"}}',
|
||||
b'<map><set name="x"/></map>', b'<map><boolean name="x" value="maybe"/></map>',
|
||||
b'<map><string name="x">a</string><string name="x">b</string></map>', b'<map><string name="x">oops']:
|
||||
p.write_bytes(invalid)
|
||||
try: m.read_document(p)
|
||||
except (ValueError, m.ET.ParseError): pass
|
||||
else: raise AssertionError(f'accepted invalid config {invalid!r}')
|
||||
`], { stdio: 'inherit' });
|
||||
});
|
||||
|
||||
// FaceclawSettingsPortReceiver exports and imports the keys the app keeps in NativeScript's
|
||||
// ApplicationSettings (prefs.db) from that file, by a fixed list. A new ApplicationSettings
|
||||
// caller needs its keys added there (nativeScriptKey) and here.
|
||||
test('settings stored outside FaceclawSettings are the ones the Android config port knows about', () => {
|
||||
const known = new Map([
|
||||
['app/g2/device-addresses.ts', ['deviceAddress.', 'deviceIdentity.']],
|
||||
['app/phone-ui/onboarding-state.ts', ['onboarding.complete', 'onboarding.previewOnly']],
|
||||
['app/apps/evenhub/session.ts', ['evenhub:']],
|
||||
// iOS-only: NSUserDefaults holds every setting there.
|
||||
['app/native/ios-bluetooth.ts', null],
|
||||
['app/native/settings-store.ios.ts', null],
|
||||
]);
|
||||
const users = [];
|
||||
const walk = (dir) => {
|
||||
for (const name of readdirSync(dir)) {
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) walk(path);
|
||||
else if (path.endsWith('.ts') && /\bApplicationSettings\b/.test(readFileSync(path, 'utf8'))) users.push(path);
|
||||
}
|
||||
};
|
||||
walk('app');
|
||||
assert.deepStrictEqual(users.sort(), [...known.keys()].sort());
|
||||
const receiver = readFileSync('App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawSettingsPortReceiver.kt', 'utf8');
|
||||
for (const [file, keys] of known) {
|
||||
for (const key of keys ?? []) {
|
||||
assert.ok(receiver.includes(`"${key}"`), `${file}: FaceclawSettingsPortReceiver.nativeScriptKey is missing ${key}`);
|
||||
assert.ok(readFileSync(file, 'utf8').includes(key) || file.endsWith('session.ts'), `${file} no longer uses ${key}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,21 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
test('iOS config codec preserves Android XML and JSON types and rejects malformed imports', () => {
|
||||
execFileSync('python3', ['-c', `
|
||||
import importlib.util, pathlib, tempfile
|
||||
spec = importlib.util.spec_from_file_location('config', 'scripts/ios_config.py')
|
||||
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
|
||||
values = {'terminal.connections': '[{"url":"g2mirror://test@host"}]', 'flag': True, 'empty': '', 'number': 42, 'ratio': 0.25, 'unicode': 'π & < 🔋\\nnext'}
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
p = pathlib.Path(d) / 'settings'
|
||||
for xml in [False, True]:
|
||||
m.atomic_write(p, m.encode_config(values, xml))
|
||||
assert m.read_config(p) == values
|
||||
assert p.stat().st_mode & 0o777 == 0o600
|
||||
for invalid in [b'{}', b'<map><set name="x"/></map>', b'<map><boolean name="x" value="maybe"/></map>', b'<map><string name="x">a</string><string name="x">b</string></map>', b'{"schema":1,"settings":{"x":null}}', b'{"schema":1,"settings":{"x":NaN}}', b'<map><string name="x">oops']:
|
||||
p.write_bytes(invalid)
|
||||
try: m.read_config(p)
|
||||
except (ValueError, m.ET.ParseError): pass
|
||||
else: raise AssertionError('accepted invalid config')
|
||||
`], { stdio: 'inherit' });
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFailsWith
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class SettingsTransferTest {
|
||||
private val androidSettings: Map<String, Any?> = linkedMapOf(
|
||||
"display.timeFormat" to "24h",
|
||||
"terminal.connections" to """[{"id":"c1","url":"g2mirror://token@host:8737","enabled":true}]""",
|
||||
"display.uiFont2" to """{"kind":"ttf","file":"Roboto-Light.ttf","size":15}""",
|
||||
"navigate.homeAddress" to "[home] 1 Main St",
|
||||
"assistant.prompt" to "{ \"not\": \"compact\" }",
|
||||
"voice.enabled" to true,
|
||||
"flappy.highScore" to "18",
|
||||
"ratio" to 0.25,
|
||||
"count" to 42L,
|
||||
"notifications.sources" to """[{"packageName":"com.tailscale.ipn","showOnGlasses":true}]""",
|
||||
"deviceIdentity.pairedAtMs" to JsonNumber("1791678209651"),
|
||||
"deviceAddress.left" to "EC:D7:82:69:3C:CB",
|
||||
"onboarding.complete" to true,
|
||||
"evenhub:com.example.app:ls:state" to """{"level":3}""",
|
||||
"ios.settings.changeToken" to "bookkeeping",
|
||||
)
|
||||
|
||||
@Test
|
||||
fun exportSplitsPortableAndPlatformSettingsAndExpandsJsonLosslessly() {
|
||||
val text = SettingsTransfer.export(androidSettings, "android", "0.8.3")
|
||||
val document = Json.parseObject(text)
|
||||
assertEquals(JsonNumber("2"), document["schema"])
|
||||
assertEquals("android", document["platform"])
|
||||
assertEquals("0.8.3", document["appVersion"])
|
||||
val settings = document["settings"].asObject()!!
|
||||
val local = document["platformSettings"].asObject()!!
|
||||
assertEquals(settings.keys.sorted(), settings.keys.toList())
|
||||
assertEquals(
|
||||
setOf("notifications.sources", "deviceIdentity.pairedAtMs", "deviceAddress.left", "onboarding.complete"),
|
||||
local.keys,
|
||||
)
|
||||
assertTrue("ios.settings.changeToken" !in settings && "ios.settings.changeToken" !in local)
|
||||
// Compact JSON becomes structure; anything that wouldn't round-trip exactly stays a string.
|
||||
assertEquals("g2mirror://token@host:8737", settings["terminal.connections"].asArray()!![0].asObject()!!["url"])
|
||||
assertEquals(JsonNumber("3"), settings["evenhub:com.example.app:ls:state"].asObject()!!["level"])
|
||||
assertEquals("[home] 1 Main St", settings["navigate.homeAddress"])
|
||||
assertEquals("{ \"not\": \"compact\" }", settings["assistant.prompt"])
|
||||
assertEquals(true, settings["voice.enabled"])
|
||||
assertEquals("18", settings["flappy.highScore"])
|
||||
assertEquals(JsonNumber("0.25"), settings["ratio"])
|
||||
assertEquals(JsonNumber("42"), settings["count"])
|
||||
assertEquals(JsonNumber("1791678209651"), local["deviceIdentity.pairedAtMs"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun samePlatformImportRestoresEveryValueExactly() {
|
||||
val plan = SettingsTransfer.planImport(SettingsTransfer.export(androidSettings, "android"), "android")
|
||||
assertEquals("android", plan.sourcePlatform)
|
||||
assertTrue(plan.skipped.isEmpty())
|
||||
val expected = androidSettings - "ios.settings.changeToken"
|
||||
assertEquals(expected.keys, plan.values.keys)
|
||||
for ((key, value) in expected) {
|
||||
val want: Any? = when (value) {
|
||||
is Double -> JsonNumber.of(value)
|
||||
is Long -> JsonNumber(value.toString())
|
||||
else -> value
|
||||
}
|
||||
assertEquals(want, plan.values[key], key)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun crossPlatformImportCarriesOnlyPortableSettings() {
|
||||
val plan = SettingsTransfer.planImport(SettingsTransfer.export(androidSettings, "android"), "ios")
|
||||
assertEquals(
|
||||
setOf("notifications.sources", "deviceIdentity.pairedAtMs", "deviceAddress.left", "onboarding.complete"),
|
||||
plan.skipped.toSet(),
|
||||
)
|
||||
assertEquals("24h", plan.values["display.timeFormat"])
|
||||
assertEquals(androidSettings["terminal.connections"], plan.values["terminal.connections"])
|
||||
assertTrue(plan.values.keys.none { SettingsTransfer.isPlatformLocal(it) })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun legacySchemaOneIsClassifiedAtImport() {
|
||||
val iosExport = """{"schema":1,"settings":{
|
||||
"ios.ble.peripheral.EC:D7:82:69:3C:CB":"{\"identifier\":\"8A2D\",\"role\":\"left\"}",
|
||||
"deviceAddress.left":"EC:D7:82:69:3C:CB",
|
||||
"integrations.evenhub.terminalId":"1429021a30db4586",
|
||||
"privacy.dataCollection":"full",
|
||||
"onboarding.complete":true}}"""
|
||||
val onAndroid = SettingsTransfer.planImport(iosExport, "android")
|
||||
assertEquals("ios", onAndroid.sourcePlatform)
|
||||
assertEquals(mapOf<String, Any>("privacy.dataCollection" to "full"), onAndroid.values)
|
||||
assertEquals(4, onAndroid.skipped.size)
|
||||
assertEquals(5, SettingsTransfer.planImport(iosExport, "ios").values.size)
|
||||
|
||||
// scripts/config_document.py converts Android shared-preferences XML to this shape.
|
||||
val fromXml = """{"schema":1,"platform":"android","settings":{"deviceAddress.left":"AA","display.mode":"576x288"}}"""
|
||||
assertEquals(2, SettingsTransfer.planImport(fromXml, "android").values.size)
|
||||
assertEquals(listOf("deviceAddress.left"), SettingsTransfer.planImport(fromXml, "ios").skipped)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun handEditedDocumentsFollowTheirSections() {
|
||||
val edited = """{
|
||||
"schema": 2,
|
||||
"settings": { "launcher.folders": { "pinball": "Games" }, "music.lastApp": "kept" },
|
||||
"platformSettings": { "deviceAddress.left": "AA" }
|
||||
}"""
|
||||
val plan = SettingsTransfer.planImport(edited, "ios")
|
||||
assertNull(plan.sourcePlatform)
|
||||
// No platform: platformSettings never apply, settings always do, even a platform-local key.
|
||||
assertEquals(mapOf<String, Any>("launcher.folders" to """{"pinball":"Games"}""", "music.lastApp" to "kept"), plan.values)
|
||||
assertEquals(listOf("deviceAddress.left"), plan.skipped)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun malformedDocumentsAreRejected() {
|
||||
val invalid = listOf(
|
||||
"not json",
|
||||
"[]",
|
||||
"""{"settings":{}}""",
|
||||
"""{"schema":3,"settings":{}}""",
|
||||
"""{"schema":2}""",
|
||||
"""{"schema":2,"settings":[]}""",
|
||||
"""{"schema":2,"settings":{"x":null}}""",
|
||||
"""{"schema":2,"settings":{"":"empty name"}}""",
|
||||
"""{"schema":2,"platform":7,"settings":{}}""",
|
||||
"""{"schema":2,"platform":"ios","settings":{"x":"a"},"platformSettings":{"x":"b"}}""",
|
||||
"""{"schema":2,"settings":{"x":"a","x":"b"}}""",
|
||||
)
|
||||
for (text in invalid) assertFailsWith<IllegalArgumentException>(text) { SettingsTransfer.planImport(text, "ios") }
|
||||
assertFailsWith<IllegalArgumentException> { SettingsTransfer.export(mapOf("x" to listOf("a")), "ios") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun objectiveCBridgeUsesJsonText() {
|
||||
val document = SettingsTransfer.exportValues("""{"a":"b","on":true,"n":1.5,"ios.ble.peripheral.X":"{}"}""", "ios", null)!!
|
||||
assertNull(Json.parseObject(document)["appVersion"])
|
||||
val reply = Json.parseObject(SettingsTransfer.importPlan(document, "android"))
|
||||
assertEquals(true, reply["ok"])
|
||||
assertEquals(mapOf<String, Any?>("a" to "b", "n" to JsonNumber("1.5"), "on" to true), reply["settings"])
|
||||
assertEquals(listOf<Any?>("ios.ble.peripheral.X"), reply["skipped"])
|
||||
assertEquals("ios", reply["sourcePlatform"])
|
||||
val failure = Json.parseObject(SettingsTransfer.importPlan("""{"schema":9,"settings":{}}""", "ios"))
|
||||
assertEquals(false, failure["ok"])
|
||||
assertEquals("Unsupported config schema 9", failure["message"])
|
||||
assertNull(SettingsTransfer.exportValues("[]", "ios", null))
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,80 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "FaceclawConfigPort.h"
|
||||
#include <assert.h>
|
||||
static NSDictionary *send(NSString *dir, NSUserDefaults *defaults, NSString *domain, NSDictionary *request) {
|
||||
#include <math.h>
|
||||
|
||||
static NSString *jsonText(id object) {
|
||||
return [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:object options:0 error:nil] encoding:NSUTF8StringEncoding];
|
||||
}
|
||||
static id parse(NSString *text) {
|
||||
return [NSJSONSerialization JSONObjectWithData:[text dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
|
||||
}
|
||||
|
||||
/** Stands in for Kotlin SettingsTransfer (tested in tests/kotlin): wraps and unwraps values. */
|
||||
@interface StubCodec : NSObject <FaceclawConfigCodec>
|
||||
@property NSString *lastAppVersion;
|
||||
@property NSDictionary *forcedPlan;
|
||||
@end
|
||||
@implementation StubCodec
|
||||
- (NSString *)exportValuesJson:(NSString *)valuesJson platform:(NSString *)platform appVersion:(NSString *)appVersion {
|
||||
self.lastAppVersion = appVersion;
|
||||
return jsonText(@{@"schema":@2, @"platform":platform, @"settings":parse(valuesJson)});
|
||||
}
|
||||
- (NSString *)importPlanDocument:(NSString *)document platform:(NSString *)platform {
|
||||
if (self.forcedPlan) return jsonText(self.forcedPlan);
|
||||
NSDictionary *doc = parse(document);
|
||||
if (![doc[@"schema"] isEqual:@2]) return jsonText(@{@"ok":@NO, @"message":@"Unsupported config schema"});
|
||||
return jsonText(@{@"ok":@YES, @"settings":doc[@"settings"], @"skipped":@[@"deviceAddress.left"], @"sourcePlatform":@"android"});
|
||||
}
|
||||
@end
|
||||
|
||||
static NSDictionary *send(NSString *dir, NSUserDefaults *defaults, NSString *domain, StubCodec *codec, NSDictionary *request) {
|
||||
NSData *json = [NSJSONSerialization dataWithJSONObject:request options:0 error:nil];
|
||||
assert([json writeToFile:[dir stringByAppendingPathComponent:@"request.json"] atomically:YES]);
|
||||
[FaceclawConfigPort processDirectory:dir defaults:defaults domain:domain];
|
||||
[FaceclawConfigPort processDirectory:dir defaults:defaults domain:domain codec:codec appVersion:@"1.2.3"];
|
||||
assert(![NSFileManager.defaultManager fileExistsAtPath:[dir stringByAppendingPathComponent:@"request.json"]]);
|
||||
return [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:[dir stringByAppendingPathComponent:@"response.json"]] options:0 error:nil];
|
||||
}
|
||||
|
||||
int main(int argc, const char **argv) { @autoreleasepool {
|
||||
NSString *dir = [NSString stringWithUTF8String:argv[1]];
|
||||
NSString *domain = [@"com.faceclaw.config-test." stringByAppendingString:NSUUID.UUID.UUIDString];
|
||||
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:domain];
|
||||
[defaults setPersistentDomain:@{@"keep":@"original", @"enabled":@NO} forName:domain];
|
||||
StubCodec *codec = [StubCodec new];
|
||||
[defaults setPersistentDomain:@{@"keep":@"original", @"enabled":@NO, @"notANumber":@(NAN)} forName:domain];
|
||||
NSDictionary *input = @{@"terminal.connections":@"[{\"url\":\"g2mirror://test@host\"}]", @"enabled":@YES, @"empty":@"", @"number":@42, @"unicode":@"π & < \n 🔋"};
|
||||
NSDictionary *reply = send(dir, defaults, domain, @{@"id":@"1", @"operation":@"push", @"settings":input});
|
||||
NSDictionary *reply = send(dir, defaults, domain, codec, @{@"id":@"1", @"operation":@"push",
|
||||
@"document":jsonText(@{@"schema":@2, @"settings":input})});
|
||||
assert([reply[@"ok"] boolValue] && [reply[@"count"] intValue] == 5);
|
||||
assert([[defaults persistentDomainForName:domain][@"keep"] isEqual:@"original"]);
|
||||
assert([reply[@"skipped"] isEqual:@[@"deviceAddress.left"]] && [reply[@"sourcePlatform"] isEqual:@"android"]);
|
||||
NSDictionary *stored = [defaults persistentDomainForName:domain];
|
||||
assert([stored[@"keep"] isEqual:@"original"]);
|
||||
assert(stored[@"enabled"] == (id)kCFBooleanTrue && [stored[@"number"] isEqual:@42]);
|
||||
NSDictionary *backup = [NSDictionary dictionaryWithContentsOfFile:[dir stringByAppendingPathComponent:@"previous.plist"]];
|
||||
assert([backup[@"keep"] isEqual:@"original"] && ![backup[@"enabled"] boolValue]);
|
||||
reply = send(dir, defaults, domain, @{@"id":@"2", @"operation":@"pull"});
|
||||
|
||||
reply = send(dir, defaults, domain, codec, @{@"id":@"2", @"operation":@"pull"});
|
||||
assert([reply[@"id"] isEqual:@"2"] && [reply[@"ok"] boolValue]);
|
||||
NSDictionary *output = reply[@"config"][@"settings"];
|
||||
assert([codec.lastAppVersion isEqual:@"1.2.3"]);
|
||||
NSDictionary *document = parse(reply[@"document"]);
|
||||
assert([document[@"platform"] isEqual:@"ios"]);
|
||||
NSDictionary *output = document[@"settings"];
|
||||
for (NSString *key in input) assert([output[key] isEqual:input[key]]);
|
||||
assert(!output[@"ios.settings.changeToken"]);
|
||||
assert([output[@"keep"] isEqual:@"original"] && [reply[@"count"] intValue] == (int)output.count);
|
||||
assert(!output[@"ios.settings.changeToken"] && !output[@"notANumber"]);
|
||||
|
||||
NSDictionary *before = [defaults persistentDomainForName:domain];
|
||||
reply = send(dir, defaults, domain, @{@"id":@"3", @"operation":@"push", @"settings":@{@"keep":@"changed", @"invalid":@[]}});
|
||||
reply = send(dir, defaults, domain, codec, @{@"id":@"3", @"operation":@"push", @"document":jsonText(@{@"schema":@9, @"settings":@{}})});
|
||||
assert(![reply[@"ok"] boolValue] && [reply[@"message"] isEqual:@"Unsupported config schema"]);
|
||||
codec.forcedPlan = @{@"ok":@YES, @"settings":@{@"keep":@"changed", @"invalid":@[]}};
|
||||
reply = send(dir, defaults, domain, codec, @{@"id":@"4", @"operation":@"push", @"document":@"{}"});
|
||||
assert(![reply[@"ok"] boolValue]);
|
||||
codec.forcedPlan = nil;
|
||||
// Requests from older scripts sent pre-converted settings rather than a document.
|
||||
reply = send(dir, defaults, domain, codec, @{@"id":@"5", @"operation":@"push", @"settings":@{@"keep":@"changed"}});
|
||||
assert(![reply[@"ok"] boolValue]);
|
||||
assert([[defaults persistentDomainForName:domain] isEqual:before]);
|
||||
reply = send(dir, defaults, domain, @{@"id":@"4", @"operation":@"bad"});
|
||||
reply = send(dir, defaults, domain, codec, @{@"id":@"6", @"operation":@"bad"});
|
||||
assert(![reply[@"ok"] boolValue]);
|
||||
[defaults removePersistentDomainForName:domain]; [defaults synchronize];
|
||||
puts("PASS: native config merges typed values, backs up, exports, consumes requests once and rejects invalid imports atomically");
|
||||
|
||||
Reference in new issue
Block a user