⋯ 40 lines Show the 40 lines above this hunk @@ -41,6 +41,7 @@ const jobject = jni.jobject; 41 41 pub const A = struct { 42 42 pub const delete_calendar_event = "deleteCalendarEvent"; 43 43 pub const get_calendar_events = "getCalendarEvents"; 44 + pub const create_calendar_event = "createCalendarEvent"; 44 45 }; 45 46 46 47 /// The globals the injected JS assigns for each action. ⋯ 5 lines Show the 5 lines above this hunk @@ -52,6 +53,8 @@ pub const resolve_global = "_craftDeleteEventResolve"; 52 53 pub const reject_global = "_craftDeleteEventReject"; 53 54 pub const list_resolve_global = "_craftCalendarResolve"; 54 55 pub const list_reject_global = "_craftCalendarReject"; 56 + pub const create_resolve_global = "_craftCreateEventResolve"; 57 + pub const create_reject_global = "_craftCreateEventReject"; 55 58 56 59 /// `Long.parseLong(text)`, or null where Java would throw. 57 60 /// ⋯ 64 lines Show the 64 lines above this hunk @@ -122,25 +125,26 @@ pub fn deleteEvent(j: Jni, activity: jobject, id: i64) !void { 122 125 /// call being inline — `events.settle` sends the payload as written, so a raw 123 126 /// message would emit a script that does not parse. See the module comment. 124 127 pub fn rejectWith(allocator: std.mem.Allocator, message: []const u8) !void { 125 - const payload = try rejectPayload (allocator, message); 126 - defer allocator.free(payload); 127 - try events.settle(allocator, reject_global, payload); 128 + try rejectOn (allocator , reject_global , message); 128 129 } 129 130 130 - /// ` message ` as a JSON string, quotes included. 131 + /// ` text ` as a JSON string, quotes included. 132 + /// 133 + /// Used for a rejection message and for the id `createCalendarEvent` resolves 134 + /// with, both of which are page-visible text that has to survive a quote. 131 135 /// 132 136 /// Split out so the test exercises this rather than a copy of it. An earlier 133 - /// version inlined the escaping here and asserted on the same three lines 134 - /// rewritten in the test — which passed happily when the escaping was removed 135 - /// from the code, because the test was not calling the code. 136 - pub fn rejectPayload (allocator: std.mem.Allocator, message : []const u8) ![]u8 { 137 + /// version inlined the escaping at the call site and asserted on the same 138 + /// three lines rewritten in the test — which passed happily when the escaping 139 + /// was removed from the code, because the test was not calling the code. 140 + pub fn jsonString (allocator: std.mem.Allocator, text : []const u8) ![]u8 { 137 141 var payload: std.ArrayListUnmanaged(u8) = .empty; 138 142 errdefer payload.deinit(allocator); 139 143 140 144 // The quotes are this caller's job: `appendJsonEscaped` escapes the 141 145 // contents and writes no delimiters. 142 146 try payload.append(allocator, '"'); 143 - try bridge_error.appendJsonEscaped(allocator, &payload, message ); 147 + try bridge_error.appendJsonEscaped(allocator, &payload, text ); 144 148 try payload.append(allocator, '"'); 145 149 146 150 return payload.toOwnedSlice(allocator); ⋯ 269 lines Show the 269 lines above this hunk @@ -416,6 +420,243 @@ fn columnText( 416 420 return try j.stringToUtf8(allocator, value); 417 421 } 418 422 423 + // ============================================================================= 424 + // createCalendarEvent 425 + // ============================================================================= 426 + // 427 + // ## Which payloads this serves, and which it hands back 428 + // 429 + // The shim reads the event through `org.json`, whose accessors coerce: a 430 + // `startDate` sent as the string "1700000000000" is a number to `optLong`, a 431 + // `title` sent as `1.5` is the string "1.5" to `optString`, and reproducing 432 + // `Double.toString` exactly is not something to guess at. 433 + // 434 + // So the rule here is narrow and stated rather than approximated: Zig serves 435 + // the shape `NewCalendarEvent` declares — strings for the text, numbers for 436 + // the dates, a boolean for the flag — plus absent keys and explicit nulls. A 437 + // payload of any other shape makes `parseNewEvent` return null, the native 438 + // returns false, and the shim reads it with the coercions it already has. The 439 + // page sees no difference; nothing has been settled at that point. 440 + // 441 + // The one coercion that *is* reproduced is the surprising one. `optString` on 442 + // an explicit JSON null returns the four characters "null", because 443 + // `JSONObject.NULL.toString()` is "null" and `JSON.toString` reaches for 444 + // `toString` on anything that is not already a String. `{"location":null}` is 445 + // an ordinary thing for `JSON.stringify` to produce, so this is a live path 446 + // and not a curiosity. 447 + 448 + /// `CalendarContract.Events.CALENDAR_ID`, `EVENT_TIMEZONE` — the two columns 449 + /// the shim fills without being asked. 450 + const col_calendar_id = "calendar_id"; 451 + const col_event_timezone = "eventTimezone"; 452 + 453 + /// The shim writes calendar 1 unconditionally. 454 + /// 455 + /// Not the primary calendar, not the first visible one — the row whose `_id` 456 + /// is 1, whatever that happens to be on the device. Reproduced because it is 457 + /// what the shim does, and because an event landing in a different calendar 458 + /// than before would be a behaviour change nobody asked for. 459 + const default_calendar_id: i32 = 1; 460 + 461 + /// The event to insert, in the shape `NewCalendarEvent` declares. 462 + pub const NewEvent = struct { 463 + title: []const u8, 464 + notes: []const u8, 465 + location: []const u8, 466 + start_date: i64, 467 + end_date: i64, 468 + all_day: bool, 469 + }; 470 + 471 + /// Read the declared shape, or null where only `org.json`'s coercions would. 472 + /// 473 + /// `default_start` and `default_end` are the shim's two separate 474 + /// `System.currentTimeMillis()` calls — separate because Kotlin evaluates each 475 + /// argument as its `put` runs, so the default end really can be a millisecond 476 + /// more than `start + 3600000`. 477 + pub fn parseNewEvent(value: std.json.Value, default_start: i64, default_end: i64) ?NewEvent { 478 + const object = switch (value) { 479 + .object => |o| o, 480 + else => return null, 481 + }; 482 + 483 + return .{ 484 + .title = optString(object, "title") orelse return null, 485 + .notes = optString(object, "notes") orelse return null, 486 + .location = optString(object, "location") orelse return null, 487 + .start_date = optLong(object, "startDate", default_start) orelse return null, 488 + .end_date = optLong(object, "endDate", default_end) orelse return null, 489 + .all_day = optBoolean(object, "isAllDay") orelse return null, 490 + }; 491 + } 492 + 493 + /// `event.optString(name, "")`, for the shapes this serves. 494 + /// 495 + /// Outer null means "a shape the shim would coerce and this will not". 496 + fn optString(object: std.json.ObjectMap, name: []const u8) ?[]const u8 { 497 + const value = object.get(name) orelse return ""; 498 + return switch (value) { 499 + .string => |text| text, 500 + // `JSONObject.NULL.toString()`. Not a typo and not a fallback: the 501 + // shim really does store the four characters. 502 + .null => "null", 503 + else => null, 504 + }; 505 + } 506 + 507 + /// `event.optLong(name, fallback)`, for the shapes this serves. 508 + fn optLong(object: std.json.ObjectMap, name: []const u8, fallback: i64) ?i64 { 509 + const value = object.get(name) orelse return fallback; 510 + return switch (value) { 511 + .integer => |n| n, 512 + // `JSON.toLong(NULL)` is null, so the fallback wins — unlike 513 + // `optString`, where the same null becomes text. 514 + .null => fallback, 515 + else => null, 516 + }; 517 + } 518 + 519 + /// `event.optBoolean(name, false)`, for the shapes this serves. 520 + fn optBoolean(object: std.json.ObjectMap, name: []const u8) ?bool { 521 + const value = object.get(name) orelse return false; 522 + return switch (value) { 523 + .bool => |b| b, 524 + .null => false, 525 + else => null, 526 + }; 527 + } 528 + 529 + /// `contentResolver.insert(Events.CONTENT_URI, values)`, and the id it lands at. 530 + /// 531 + /// Returns `uri?.lastPathSegment ?: ""` — so a provider that refuses the insert 532 + /// resolves the page's promise with an empty string rather than rejecting, 533 + /// which is the shim's answer and not an improvement on it. 534 + pub fn insertEvent(j: Jni, allocator: std.mem.Allocator, activity: jobject, event: NewEvent) ![]u8 { 535 + try j.pushLocalFrame(32); 536 + defer _ = j.popLocalFrame(null); 537 + 538 + const values_cls = try j.findClass("android/content/ContentValues"); 539 + const values = try j.newObjectA(values_cls, try j.methodId(values_cls, "<init>", "()V"), &.{}); 540 + 541 + // `ContentValues.put` is overloaded on the *boxed* types, so each number 542 + // has to be boxed before it can be put. 543 + const put_string = try j.methodId(values_cls, "put", "(Ljava/lang/String;Ljava/lang/String;)V"); 544 + const put_long = try j.methodId(values_cls, "put", "(Ljava/lang/String;Ljava/lang/Long;)V"); 545 + const put_int = try j.methodId(values_cls, "put", "(Ljava/lang/String;Ljava/lang/Integer;)V"); 546 + 547 + try putString(j, allocator, values, put_string, col_title, event.title); 548 + try putString(j, allocator, values, put_string, col_description, event.notes); 549 + try putString(j, allocator, values, put_string, col_event_location, event.location); 550 + try putLong(j, values, put_long, col_dtstart, event.start_date); 551 + try putLong(j, values, put_long, col_dtend, event.end_date); 552 + try putInt(j, values, put_int, col_all_day, if (event.all_day) 1 else 0); 553 + try putInt(j, values, put_int, col_calendar_id, default_calendar_id); 554 + 555 + // `TimeZone.getDefault().id`. The provider needs one, and an event 556 + // inserted without it reads back at the wrong hour. 557 + const timezone_cls = try j.findClass("java/util/TimeZone"); 558 + const timezone = try j.callStaticObjectMethodA( 559 + timezone_cls, 560 + try j.staticMethodId(timezone_cls, "getDefault", "()Ljava/util/TimeZone;"), 561 + &.{}, 562 + ); 563 + const timezone_id = try j.callObjectMethod( 564 + timezone, 565 + try j.methodId(try j.objectClass(timezone), "getID", "()Ljava/lang/String;"), 566 + ); 567 + try j.callVoidMethodA(values, put_string, &.{ 568 + .{ .l = try j.newStringUtf(col_event_timezone) }, 569 + .{ .l = timezone_id }, 570 + }); 571 + 572 + const events_cls = try j.findClass("android/provider/CalendarContract$Events"); 573 + const content_uri = try j.staticObjectField( 574 + events_cls, 575 + try j.staticFieldId(events_cls, "CONTENT_URI", "Landroid/net/Uri;"), 576 + ); 577 + 578 + const activity_cls = try j.objectClass(activity); 579 + const resolver = try j.callObjectMethod( 580 + activity, 581 + try j.methodId(activity_cls, "getContentResolver", "()Landroid/content/ContentResolver;"), 582 + ); 583 + 584 + const uri = try j.callObjectMethodA( 585 + resolver, 586 + try j.methodId( 587 + try j.objectClass(resolver), 588 + "insert", 589 + "(Landroid/net/Uri;Landroid/content/ContentValues;)Landroid/net/Uri;", 590 + ), 591 + &.{ .{ .l = content_uri }, .{ .l = values } }, 592 + ); 593 + 594 + if (uri == null) return allocator.dupe(u8, ""); 595 + 596 + const segment = try j.callObjectMethod( 597 + uri, 598 + try j.methodId(try j.objectClass(uri), "getLastPathSegment", "()Ljava/lang/String;"), 599 + ); 600 + if (segment == null) return allocator.dupe(u8, ""); 601 + return j.stringToUtf8(allocator, segment); 602 + } 603 + 604 + fn putString( 605 + j: Jni, 606 + allocator: std.mem.Allocator, 607 + values: jobject, 608 + put: jni.jmethodID, 609 + column: [:0]const u8, 610 + text: []const u8, 611 + ) !void { 612 + try j.pushLocalFrame(4); 613 + defer _ = j.popLocalFrame(null); 614 + 615 + // `NewStringUTF` needs a NUL terminator, and a title is arbitrary page 616 + // text — so it is copied rather than pointed at. 617 + const terminated = try allocator.allocSentinel(u8, text.len, 0); 618 + defer allocator.free(terminated); 619 + @memcpy(terminated, text); 620 + 621 + try j.callVoidMethodA(values, put, &.{ 622 + .{ .l = try j.newStringUtf(column) }, 623 + .{ .l = try j.newStringUtf(terminated.ptr) }, 624 + }); 625 + } 626 + 627 + fn putLong(j: Jni, values: jobject, put: jni.jmethodID, column: [:0]const u8, value: i64) !void { 628 + try j.pushLocalFrame(4); 629 + defer _ = j.popLocalFrame(null); 630 + 631 + const long_cls = try j.findClass("java/lang/Long"); 632 + const boxed = try j.callStaticObjectMethodA( 633 + long_cls, 634 + try j.staticMethodId(long_cls, "valueOf", "(J)Ljava/lang/Long;"), 635 + &.{.{ .j = value }}, 636 + ); 637 + try j.callVoidMethodA(values, put, &.{ .{ .l = try j.newStringUtf(column) }, .{ .l = boxed } }); 638 + } 639 + 640 + fn putInt(j: Jni, values: jobject, put: jni.jmethodID, column: [:0]const u8, value: i32) !void { 641 + try j.pushLocalFrame(4); 642 + defer _ = j.popLocalFrame(null); 643 + 644 + const integer_cls = try j.findClass("java/lang/Integer"); 645 + const boxed = try j.callStaticObjectMethodA( 646 + integer_cls, 647 + try j.staticMethodId(integer_cls, "valueOf", "(I)Ljava/lang/Integer;"), 648 + &.{.{ .i = value }}, 649 + ); 650 + try j.callVoidMethodA(values, put, &.{ .{ .l = try j.newStringUtf(column) }, .{ .l = boxed } }); 651 + } 652 + 653 + /// `message` as a JSON string, for whichever reject global the caller owns. 654 + pub fn rejectOn(allocator: std.mem.Allocator, global: []const u8, message: []const u8) !void { 655 + const payload = try jsonString(allocator, message); 656 + defer allocator.free(payload); 657 + try events.settle(allocator, global, payload); 658 + } 659 + 419 660 // ============================================================================= 420 661 // Tests 421 662 // ============================================================================= ⋯ 28 lines Show the 28 lines above this hunk @@ -450,7 +691,7 @@ test "a rejection message with a quote is escaped rather than emitted raw" { 450 691 // The bug that used to be one line away. Before #154 the shim turned an id 451 692 // of `1'x` into `…Reject('For input string: "1'x"')`, which does not parse 452 693 // — so evaluateJavascript ran nothing and the promise never settled. 453 - const payload = try rejectPayload (testing.allocator, "For input string: \"1'x\""); 694 + const payload = try jsonString (testing.allocator, "For input string: \"1'x\""); 454 695 defer testing.allocator.free(payload); 455 696 456 697 // Valid JSON, and it round-trips to exactly the original message. ⋯ 166 lines Show the 166 lines above this hunk @@ -623,3 +864,146 @@ test "getCalendarEvents names its action and globals as the shim does" { 623 864 try testing.expectEqualStrings("_craftCalendarResolve", list_resolve_global); 624 865 try testing.expectEqualStrings("_craftCalendarReject", list_reject_global); 625 866 } 867 + 868 + // --- createCalendarEvent --------------------------------------------------- 869 + 870 + fn parseEvent(json: []const u8, default_start: i64, default_end: i64) !?NewEvent { 871 + var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{}); 872 + defer parsed.deinit(); 873 + 874 + // The strings borrow from `parsed`, so anything a caller keeps has to be 875 + // read before this returns. Every test below asserts inside its own call. 876 + const event = parseNewEvent(parsed.value, default_start, default_end) orelse return null; 877 + return NewEvent{ 878 + .title = try testing.allocator.dupe(u8, event.title), 879 + .notes = try testing.allocator.dupe(u8, event.notes), 880 + .location = try testing.allocator.dupe(u8, event.location), 881 + .start_date = event.start_date, 882 + .end_date = event.end_date, 883 + .all_day = event.all_day, 884 + }; 885 + } 886 + 887 + fn freeEvent(event: NewEvent) void { 888 + testing.allocator.free(event.title); 889 + testing.allocator.free(event.notes); 890 + testing.allocator.free(event.location); 891 + } 892 + 893 + test "the declared shape reads straight through" { 894 + const event = (try parseEvent( 895 + \\{"title":"Standup","notes":"daily","location":"Room 2", 896 + \\ "startDate":1700000000000,"endDate":1700000900000,"isAllDay":false} 897 + , 1, 2)).?; 898 + defer freeEvent(event); 899 + 900 + try testing.expectEqualStrings("Standup", event.title); 901 + try testing.expectEqualStrings("daily", event.notes); 902 + try testing.expectEqualStrings("Room 2", event.location); 903 + try testing.expectEqual(@as(i64, 1700000000000), event.start_date); 904 + try testing.expectEqual(@as(i64, 1700000900000), event.end_date); 905 + try testing.expect(!event.all_day); 906 + } 907 + 908 + test "absent keys take the shim's defaults" { 909 + // `optString(name, "")`, `optLong(name, now)`, `optBoolean(name, false)`. 910 + // The two date defaults are separate arguments because the shim calls 911 + // System.currentTimeMillis() twice, once per put. 912 + const event = (try parseEvent("{}", 111, 222)).?; 913 + defer freeEvent(event); 914 + 915 + try testing.expectEqualStrings("", event.title); 916 + try testing.expectEqualStrings("", event.notes); 917 + try testing.expectEqualStrings("", event.location); 918 + try testing.expectEqual(@as(i64, 111), event.start_date); 919 + try testing.expectEqual(@as(i64, 222), event.end_date); 920 + try testing.expect(!event.all_day); 921 + } 922 + 923 + test "an explicit null is text to optString and a fallback to optLong" { 924 + // The org.json quirk, and the reason it is worth a test rather than a 925 + // comment: `JSONObject.NULL.toString()` is "null", so `optString` hands 926 + // back four characters where every other accessor hands back the default. 927 + // `JSON.stringify({location: null})` produces this every day. 928 + const event = (try parseEvent( 929 + \\{"title":null,"notes":null,"location":null,"startDate":null,"endDate":null,"isAllDay":null} 930 + , 111, 222)).?; 931 + defer freeEvent(event); 932 + 933 + try testing.expectEqualStrings("null", event.title); 934 + try testing.expectEqualStrings("null", event.notes); 935 + try testing.expectEqualStrings("null", event.location); 936 + try testing.expectEqual(@as(i64, 111), event.start_date); 937 + try testing.expectEqual(@as(i64, 222), event.end_date); 938 + try testing.expect(!event.all_day); 939 + } 940 + 941 + test "a shape only org.json would coerce is handed back rather than guessed at" { 942 + // Each of these is something `optString`/`optLong`/`optBoolean` reads 943 + // happily and this does not. Returning null sends the native down its 944 + // false path, the shim reads it, and the page cannot tell — which is the 945 + // whole reason the rule can be this narrow. 946 + for ([_][]const u8{ 947 + // A number where NewCalendarEvent declares a string: optString would 948 + // give "1.5", and reproducing Double.toString is not a guess to make. 949 + \\{"title":1.5} 950 + , 951 + \\{"title":7} 952 + , 953 + \\{"location":true} 954 + , 955 + // A string where it declares a number: optLong parses it as a double 956 + // and truncates, so "1.9" is 1. 957 + \\{"startDate":"1700000000000"} 958 + , 959 + \\{"endDate":"1.9"} 960 + , 961 + // A float where it declares a number: optLong truncates toward zero. 962 + \\{"startDate":1.9} 963 + , 964 + // optBoolean reads "true" and "false" case-insensitively. 965 + \\{"isAllDay":"true"} 966 + , 967 + \\{"isAllDay":1} 968 + , 969 + // Not an object at all. 970 + \\[] 971 + , 972 + \\"title" 973 + , 974 + }) |payload| { 975 + const event = try parseEvent(payload, 1, 2); 976 + if (event) |kept| { 977 + freeEvent(kept); 978 + std.debug.print("payload was served rather than handed back: {s}\n", .{payload}); 979 + return error.CoercedShapeAccepted; 980 + } 981 + } 982 + } 983 + 984 + test "the columns createCalendarEvent fills are the shim's" { 985 + try testing.expectEqualStrings("calendar_id", col_calendar_id); 986 + try testing.expectEqualStrings("eventTimezone", col_event_timezone); 987 + 988 + // The shim writes calendar 1 unconditionally — not the primary calendar, 989 + // the row whose _id is 1. Written down because it looks like a bug and is 990 + // instead a faithful port of one. 991 + try testing.expectEqual(@as(i32, 1), default_calendar_id); 992 + } 993 + 994 + test "createCalendarEvent names its action and globals as the shim does" { 995 + try testing.expectEqualStrings("createCalendarEvent", A.create_calendar_event); 996 + try testing.expectEqualStrings("_craftCreateEventResolve", create_resolve_global); 997 + try testing.expectEqualStrings("_craftCreateEventReject", create_reject_global); 998 + } 999 + 1000 + test "an id carrying a quote resolves as JSON rather than breaking the reply" { 1001 + // `uri.lastPathSegment` is provider-controlled text, and it goes to the 1002 + // page through the same channel a rejection does. 1003 + const payload = try jsonString(testing.allocator, "17'x"); 1004 + defer testing.allocator.free(payload); 1005 + 1006 + var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, payload, .{}); 1007 + defer parsed.deinit(); 1008 + try testing.expectEqualStrings("17'x", parsed.value.string); 1009 + }