using System.Collections.Frozen; using System.Text.Json; using Febe.Core.Collection.Privacy; namespace Febe.Core.Collection.Readers; /// /// The closed list of words a key may be made of to appear in the strict key structure of the diagnostic report /// (issue #39, ). Every other key is written «#»: a user name, a post code or a /// short token used as a key never leaves the machine, even when the body does not repeat it as a value. /// /// /// /// A key passes when it has only ASCII letters, digits, «_» and «-», does not look like an identifier, and every part /// between «_» and «-» is a word of the list (case ignored): image_versions2, __typename, /// has_more_headload_comments. The words come from the keys of the cleaned samples in tests/Febe.Tests/campioni /// (structure only: the sanitizer already replaced every key that is data), from the shipped reader vocabularies /// (lettori.instagram.json, lettori.prova.json) and from the words of the site's addresses /// (). A missing word only costs detail («#»), never privacy. /// /// /// A few words that are also first names, places or opaque codes () pass only inside a key /// that also has a word of the list (next_max_id), never alone (a user called «max») nor with one another /// (max_mark, two first names). /// /// /// A name made only of words of the list («the_artist», «street_style») still passes this check, so the strict structure /// () asks more of two kinds of keys. A key with a plain value (text, number, /// true or false, null) stays only when it is a field of the closed list (): the entries of a /// map of counts or flags keyed by name never show. The entries of a map of objects or lists are found by their /// siblings (similar keys, a shared identity field such as pk, an empty value, lists of plain values, or a key /// that only the first element of a list has), and among them too only the fields of the closed list stay. A /// single such name used as the key of an object or a list, with no sibling alike and never repeated as a value in the /// body, is the residual risk of a closed list of words. /// /// public static class StructureWords { private const string SampleWords = """ a accessibility account achievements action activation active ad add additional address ads affiliate agent aggregated ai aigm all allow allowed alpha altezza altro and anonymous api app appearance appreciation archive are artist as asset associated at attachment attribute attributed attribution attributions audience audio author authors auto autodub automatically autore autosave available awaiting award background badge badges bandwidth barra base batch bbox be been behavior benefits best bestie besties bio biography bit blocked blocking bloks bookmarked boost boosted bottomsheet brand branded breaking broadcast broadcasts business button by cache camera can candidates canonical caption capture carousel category chaining challenge chat check city client clip clips club cluster coauthor code codecs collab collaborator collection color comment commenter commenting comments commerce commission community complete composer composition config configs connected connection consideration consumption container content contenuti contenuto context contextual control copertina count countdowns counts cover covered created creation creative creator cropped cropping crosspost crosspostable cta cursor custom cut cutout dash data debug decision default delayed deleted demotion deny derived details detected detection dettagli device did disable disabled discover display distribution dopo download downloads downstream durata duration eager earned edges edit edited editing educational effect effects elements eligibility eligible eligiblity embeds embodiment emojis enable enabled encoding end enforced enough entities entry entrypoint entrypoints errors estimated event exclusive expansion expiration expiring explicit explore extensions external face facepile failure fallback fan favorite fb fbid fbsearch featured feed feedback fetch fetching file filmati filter filtered filters final first fissato fitting flags floating flush follow followed follower followers following for formatted foto foundation frame free friction friendship from full gating gen genai geoblocked gif gifting graphql grid group guardian has hashtag hashtags have hd header headline headload height hidden hide high highlight highlights host hypercard id identifier ids ig igbio igids igtv image improvements in incoming indirizzo info inform infos initial initiate inline insert insights instagram integrity interaction interactive internal interop inventory invited invocation io is item items kb key label labels langs language largest larghezza lat latest length light like liked likers likes link linked links list live lng load locales location locations logging long longform main manifest manually marketplace mashed mashup mashups may media medias member memorialized mention merchandising message messaging meta metadata method mids mime module more ms music mute muted muting mutual name new news next node nome non nonmimicable note notes notice notices num number numero nux of on only open options organic original originality outgoing overlap overlay owner page pagina paid param parent parti partnership parts party path payload per photo pic picture pill pinned pivot pivots pk places play playback player playlist playlists point pos position post prefetch premium presets preview previous privacy private privately producer producers product production products professional profile profilo progressive project promo promotion promotions prompts pronouns pubblicato pubblicazioni public qualities quando questions quick quiet raccolta raccolte rank ranked ranking reaction reactions reason reattribution recommendation recs reel reels referral refresh regulated related remix remixes remixing remove rename render rendered reply report repost reposter representation representations request requesting require reshare reshared resolution response rest restore restricted restyle result results reusable reuse revamp review ring riservato risk risorsa risultati ritratto roll root rotation routing row save saved scade scans scroll scrubber search secondary seconds see seen segments seguiti seguito selector sequence server settings severity share shared sharing shop shopping short should show sigla size sizes sliders smart snippet social sort sound source spam spatial speed sponsor sprite spritesheet start starting stato status sticker stickers storia storie story street string strong style submission submitted submitters subscribe subscriber subscribers subtype successiva successivo suggested supervision surface tab tag tagged tagging tags taken tappable tappables teen template testo text the third threading thumbnail thumbnails time timeline timeout timer timestamp tipo tips title titolo to toggle token tool top topic topics topsearch total totali tracking translated translation translations transparency tray treatment trend trending trial type typename ufi ui ultima unavailable unicode unified unpublished unseen unviewable up upcoming upsell uri url urls us use user userid username users usertags utc v1 v2 variant verified version versione versions versions2 video view viewer viewers views visibile visibility visible visual voci wearable wearables weight welcome width with x xdt xdtuserdict xpost y you zip """; /// /// Every key of the cleaned samples of tests/Febe.Tests/campioni (their data keys were already replaced by the /// sanitizer), frozen here because the samples do not ship with Febe: with the keys of the reader vocabularies, the /// closed list of fields (). /// private const string SampleKeys = """ __bbox __typename accessibility_caption account_badges account_type achievements_info action_type active_meta_verified_benefits additional_audio_info additional_audio_username additional_candidates address_street ai_agent_owner_username ai_agent_type ai_interactive_embodiment_attachment_style_info ai_label_info ai_topic_filters aigm_account_label_info all_previous_submitters all_video_dash_prefetch_representations allow_creator_to_rename altezza altro appearance_effect are_remixes_crosspostable asset_recommendation_info associated_clip_medias attributed_custom_audio_asset_id attribution_label_text attribution_user audience audio audio_asset_id audio_asset_start_time_in_ms audio_filter_infos audio_parts audio_parts_by_filter audio_ranking_info audio_reattribution_info audio_type auto_load_more_enabled autore autosave_to_exclusive_highlight bandwidth barra base_url basel_encoding_timeout best_audio_cluster_id bio_links biography biography_with_entities bit_flags blocking bloks_app_url bloks_sticker boost_unavailable_identifier boost_unavailable_reason boost_unavailable_reason_v2 boosted_status branded_content_tag_info breaking_content_info breaking_creator_info broadcasts camera_tool can_add_tag can_remix_be_shared_to_fb can_remix_be_shared_to_fb_expansion can_reply can_reshare can_see_insights_as_brand can_see_organic_insights can_see_quiet_post_attribution can_toggle_mashups_allowed can_view_more_preview_comments can_viewer_reshare can_viewer_save candidates caption caption_is_edited capture_type carousel_media carousel_media_count carousel_parent_id category challenge_info chiave city_name client_cache_key clips_attribution_info clips_connection clips_creation_entry_point clips_metadata clips_tab_pinned_user_ids coauthor_producer_can_see_organic_insights coauthor_producers code codecs collab_follow_button_info collaborator_edit_eligibility color_filters comment comment_count comment_cover_pos comment_filter_param comment_inform_treatment comment_likes_enabled commenting_disabled_for_viewer comments comments_disabled commerce_integrity_review_decision community_notes_info complete connected_member_count consumption_info content_appreciation_info content_type contenuti contenuto contextual_highlight_info copertina corpo cover_media created_at created_at_for_fb_app created_at_utc creation_tool_info creative_config creator_is_in_premium_reactions_alpha cropped_image_version crosspost_metadata cursor custom_list_info cutout_sticker_info dash_manifest data debug_link default deleted_reason derived_content_start_time_in_composition_in_ms descrittore detection_method dettagli device_timestamp did_report_as_spam disable_caption_and_comment disable_use_in_clips_client_cache display_artist display_labels display_labels_with_translations display_media_id display_uri dopo downstream_use_xpost_deny_reason durata duration_in_ms duration_selector_seconds edges effect_configs effect_filter_name effect_preview eligible_for_text_app_activation_badge eligible_insights_entrypoints eligible_promotions enable_media_notes_production enable_submission_friction enabled end end_cursor entities entry_point_container errors estimated_scans_sizes expiring_at explore extensions external_lynx_url external_media_info external_url face_effect_id facepile_top_likers failure_reason fallback fan_club_id fan_club_info fan_club_name fan_consideration_page_revamp_eligiblity fb_comment_count fb_comments fb_downstream_use_xpost_metadata fb_like_count fb_play_count fb_user_tags fbid fbid_v2 featured_label featured_products feed_demotion_control feed_post_reshare_disabled feed_recs_demotion_control fetch__XDTUserDict file_size_kb filmati filter_options filter_type first_frame fissato floating_context_item_type floating_context_items follow_hashtag_info followed_by follower_count following following_count formatted_clips_media_count formatted_mashups_count foto foundation_improvements_enabled friendship_status full_image_version full_name gating gen_ai_detection_method gen_ai_tool_info geoblocked_comment_notices group guardian_hypercard_content has_anonymous_profile_picture has_audio has_been_mashed_up has_besties_media has_chaining has_created_ssc has_delayed_metadata has_enough_subscribers_for_ssc has_high_risk_gen_ai_inform_treatment has_liked has_longform_media has_more_comments has_more_headload_comments has_more_headload_fb_comments has_next_page has_nonmimicable_additional_audio has_previous_page has_privately_liked has_profile_pic has_restyle_presets has_shared_to_fb has_story_archive has_tagged_users has_translation has_viewer_saved has_viewer_submitted_note has_views_fetching has_visible_media_notes hashtags hd_profile_pic_url_info hd_profile_pic_versions headline height hidden_likes_string_variant hide_creator_marketplace_badge hide_remixing hide_stickers_for_original_language hide_view_all_comment_entrypoint highlights horizon_attribution_info host id ig_artist ig_media_sharing_disabled ig_mention ig_play_count ig_quick_promotion_batch_fetch_root igbio_product igtv_first_frame image_versions2 in incoming_request indirizzo inform_module initial_representation_ids initiate_at_top inline_audio_label insert_new_comment_to_top instagram_pk integrity_review_decision interop_messaging_user_fbid inventory_source invited_coauthor_producers io is_active_on_text_post_app is_active_trial is_affiliate_commission_eligible is_ai_user is_audio_automatically_attributed is_auto_detected is_awaiting_distribution is_bestie is_bookmarked is_business is_cannes is_comments_gif_composer_enabled is_coppa_enforced is_covered is_created_by_media_owner is_creator_requesting_mashup is_cutout_sticker_allowed is_dash_eligible is_educational is_eligible_content_for_post_roll_ad is_eligible_for_audio_effects is_eligible_for_autodub is_eligible_for_autodub_upsell is_eligible_for_organic_eager_refresh is_eligible_for_poe is_eligible_for_poe_premium is_eligible_for_request_a_note is_eligible_for_rta is_eligible_for_vinyl_sticker is_embeds_disabled is_enabled is_explicit is_fan_club_gifting_eligible is_fan_club_promo_video is_fan_club_referral_eligible is_favorite is_fb_only is_feed_favorite is_feed_feedback_aggregated is_feedback_aggregated is_feta_guardian_user is_final is_free_trial_eligible is_guardian_user is_in_profile_grid is_internal_only is_light_weight_check is_light_weight_reuse_allowed_check is_longform_player_eligible is_manually_enabled is_memorialized is_meta_ai_invocation_blocked_by_author is_muting_reel is_open_to_public_submission is_organic_product_tagging_eligible is_original_audio_download_eligible is_paid_partnership is_photo_comments_composer_enabled_for_author is_pivot_page_available is_post_live_clips_media is_private is_professional_account is_public_chat_welcome_video is_quiet_post is_ranked_comment is_regulated_c18 is_reshare_of_text_post_app_media_in_ig is_restricted is_reuse_allowed is_reuse_disabled is_ring_creator is_seen is_shared_from_basel is_shared_to_fb is_short_drama is_social_ufi_disabled is_spatial_image is_story_edited is_third_party_downloads_eligible is_trending_in_clips is_unpublished is_verified is_visual_reply_commenter_notice_enabled is_xpost_from_fb items largest_public_bc_id larghezza lat latest_besties_reel_media latest_reel_media latest_wearables_reel_media_long like_and_view_counts_disabled like_count liked_by_media_owner_badge_enabled link link_text linked_fb_info linked_media_playlist_data live_broadcast_id live_broadcast_visibility lng location locations logging_info_token longform_clip_metadata longform_title magic_cut_end_time magic_cut_start_time main_feed_carousel_starting_media_id mashup_info mashup_type mashups_allowed mashups_allowed_for_carousel max_thumbnails_per_sprite may_have_template_info media media_attributions_data media_count media_cropping_info media_header_display media_id media_note media_notes media_overlay_info media_repost_count media_reposter_bottomsheet_enabled media_type media_ui_attributions_data media_ui_attributions_data_v2 merchandising_pill_info message meta_ai_suggested_prompts meta_verified_benefits_info mezql_token mids mime_type more_available music_asset_info music_canonical_id music_info music_metadata muted muting mutual_followers_count name node nome nome_visibile non_privacy_filtered_mashups_media_count note_submission_disabled num_earned_achievements num_results number_of_qualities numero nux_info oa_owner_is_music_artist organic_tracking_token original_audio_subtype original_audio_title original_height original_media original_media_id original_sound_info original_width originality_info outgoing_request overlap_duration_in_ms owner owner_id page_info pagina parti parti_totali path photo_of_you pk pk_id places play_count playback_resolution_csvqm playback_resolution_mos position premium_reaction_count preview preview_comments previous_trend_rank privacy_filtered_mashups_media_count private_reply_status product_type professional_clips_upsell_type profile_background_color profile_background_secondary_color profile_context_facepile_users profile_context_links_with_user_ids profile_grid_control_enabled profile_grid_thumbnail_fitting_style profile_pic_genai_tool_info profile_pic_id profile_pic_url profilo progressive_download_url progressive_identifier pronouns pubblicato pubblicazioni quando quick_response_emojis raccolta raccolte rank_token ranked_position reactions reel_media_background reel_media_seen_timestamp reel_type reels_media reels_on_the_rise_info regulated_news_in_locations related_ads_pivots_media_info remove_message_entrypoint rendered_width representation_id representations request_start_time_ms require reshare_count reshared_story_media_author result reusable_text_attribute_string reusable_text_info ring_creator_metadata riservato risorsa risultati ritratto rotation saved_collection_ids scade scans_profile scroll_behavior scrubber_spritesheet_info_candidates search_social_context search_social_context_snippet_type see_more seen seen_ranked_position segments seguiti seguito sequence_number server_metadata severity share_count_disabled share_enabled sharing_friction_info sharing_friction_payload shop_routing_user_id shopping_info short_drama_creator should_allow_audio_editing should_allow_restore should_have_inform_treatment should_have_sharing_friction should_mute_audio should_mute_audio_reason should_mute_audio_reason_type should_render_upsell should_request_ads should_show_author_pog_for_tagged_media_shared_to_profile_grid should_show_category should_show_playlists_in_profile_tab show_account_transparency_details show_achievements show_ring_award show_text_post_app_badge show_tips sigla smart_frame social_context social_context_facepile_users social_context_type social_context_users_count sort_options speed_selector sponsor_tags sprite_height sprite_urls sprite_width start start_cursor stato status sticker_data storie story_app_attribution story_bloks_stickers story_bloks_tappables story_countdowns story_cta story_feed_media story_hashtags story_link_stickers story_locations story_music_stickers story_questions story_sliders strong_id__ subscribe_cta_visible subscriber_count subtype_name_for_REST__ successiva successivo supervision_info surface_nux_id taken_at tappable_elements teen_project_info template_info testo text text_post_app_badge_label text_post_app_is_private text_post_share_to_ig_story_stickers third_party_downloads_enabled threading_enabled thumbnail_duration thumbnail_height thumbnail_width thumbnails thumbnails_per_row time_at_flush_ms time_created timeline_pinned_user_ids timer_selector_seconds tipo title titolo top_likers total_clips_count total_thumbnail_num_per_sprite translated_langs_for_autodub transparency_label transparency_product transparency_product_enabled tray trend_rank tya_media_related_topics type ultima_storia unicode unified_feedback_enabled unseen_count unseen_wearables_media_igids unviewable_authors_infos upcoming_event url url_expiration_timestamp_us user userID user_activation_info user_id user_notes username users usertags valore versione video_dash_manifest video_duration video_id video_length video_sticker_locales video_versions view_count viewer viewer_count viewer_has_liked viewer_interaction_settings viewer_premium_reaction_asset_id viewers visibility visual_comment_reply_sticker_info voci wearable_attribution_info width x xdt_api__v1__discover__chaining xdt_api__v1__fbsearch__topsearch_connection xdt_api__v1__feed__reels_media xdt_api__v1__feed__reels_media__connection xdt_api__v1__feed__reels_tray xdt_api__v1__feed__user_timeline_graphql_connection xdt_api__v1__usertags__user_id__feed_connection xdt_mark_story_reel_seen xdt_viewer xpost_fb_creator_info y zip """; private static readonly FrozenSet CompoundOnlyWords = FrozenSet.Create( StringComparer.OrdinalIgnoreCase, "max", "mark", "basel", "cannes", "lynx", "feta", "poe", "drama", "magic", "rise", "vinyl", "horizon", "coppa", "csvqm", "tya", "rta", "ssc", "oa", "bc", "pog", "mezql", "c18", "mos"); private static readonly Lazy Built = new(Build); /// Words that pass only as a part of a key that also has a word of the list. public static IReadOnlySet CompoundOnly => CompoundOnlyWords; /// True for a word of the list (case ignored). public static bool IsWord(string word) => Built.Value.Words.Contains(word); /// /// True for a whole key of the shipped reader vocabularies (user, owner, image_versions2), case /// ignored: the only keys the strict structure keeps among the entries of a map. /// public static bool IsKnownKey(string key) => Built.Value.Keys.Contains(key) && IsStructural(key); /// /// True for a field of the closed list: a whole key of the reader vocabularies () or of the /// cleaned samples (is_private, has_next_page, pubblicazioni), case ignored, that is also /// structural. In the strict structure, a key with a plain value (text, number, true or false, null), and a key /// among the entries of a map, stays only when it is one of these. /// public static bool IsFieldKey(string key) => (Built.Value.Keys.Contains(key) || Built.Value.SampleKeys.Contains(key)) && IsStructural(key); /// True when may appear as it is in the strict key structure. public static bool IsStructural(string key) { ArgumentNullException.ThrowIfNull(key); if (key.Length == 0 || key.Length > 120 || KeyStructure.IsDataKey(key)) { return false; } var parts = key.Split(['_', '-'], StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 0) { return false; } var words = Built.Value.Words; var listWord = false; foreach (var part in parts) { if (words.Contains(part)) { listWord = true; } else if (!CompoundOnlyWords.Contains(part)) { return false; } } // Compound-only words never stand on their own, nor together («max_mark»): at least one part is a word of the list. return listWord; } private static Lists Build() { var words = new HashSet(SampleWords.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries), StringComparer.OrdinalIgnoreCase); var keys = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var segment in PathPatterns.KnownSegments) { AddParts(words, segment); } foreach (var file in new[] { "lettori.instagram.json", "lettori.prova.json" }) { try { using var document = JsonDocument.Parse(SiteMap.ReadEmbeddedText(file)); AddVocabulary(words, keys, document.RootElement, 0); } catch (Exception ex) when (ex is JsonException or IOException) { // The sample words are enough: a vocabulary only adds detail. } } words.ExceptWith(CompoundOnlyWords); var sampleKeys = SampleKeys.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).ToFrozenSet(StringComparer.OrdinalIgnoreCase); return new Lists(words.ToFrozenSet(StringComparer.OrdinalIgnoreCase), keys.ToFrozenSet(StringComparer.OrdinalIgnoreCase), sampleKeys); } /// /// The key names of a vocabulary file: every string of its lists, split at «.» (whole keys) and then at «_» and «-» /// (words). /// private static void AddVocabulary(HashSet words, HashSet keys, JsonElement element, int depth) { if (depth > 8) { return; } switch (element.ValueKind) { case JsonValueKind.Object: foreach (var property in element.EnumerateObject()) { AddVocabulary(words, keys, property.Value, depth + 1); } break; case JsonValueKind.Array: foreach (var item in element.EnumerateArray()) { if (item.ValueKind == JsonValueKind.String && item.GetString() is { } path) { foreach (var key in path.Split('.', StringSplitOptions.RemoveEmptyEntries)) { if (!KeyStructure.IsDataKey(key)) { keys.Add(key); AddParts(words, key); } } } else { AddVocabulary(words, keys, item, depth + 1); } } break; } } private sealed record Lists(FrozenSet Words, FrozenSet Keys, FrozenSet SampleKeys); private static void AddParts(HashSet words, string key) { foreach (var part in key.Split(['_', '-'], StringSplitOptions.RemoveEmptyEntries)) { words.Add(part); } } }