Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
gifs: Introduce the Tenor GIF picker.
apoorvapendse849e3ea51024
diff --git a/api_docs/unmerged.d/ZF-35b8e6.md b/api_docs/unmerged.d/ZF-35b8e6.mdnew file mode 100644index 00000000000..33ea97faf02--- /dev/null+++ b/api_docs/unmerged.d/ZF-35b8e6.md@@ -0,0 +1,2 @@+* [`POST /register`](/api/register-queue): Added new `tenor_api_key`+ field, which is required to fetch GIFs using the Tenor API.diff --git a/tools/lib/capitalization.py b/tools/lib/capitalization.pyindex 3d8ae412d5e..d01813b8de0 100644--- a/tools/lib/capitalization.py+++ b/tools/lib/capitalization.py@@ -147,6 +147,8 @@ IGNORED_PHRASES = [# Used in GIPHY popover.r"GIFs",r"GIPHY",+ # Used for Tenor attributions+ r"Search Tenor",# Used in our case studiesr"Technical University of Munich",r"University of California San Diego",diff --git a/tools/test-js-with-node b/tools/test-js-with-nodeindex dff17bc80f4..f51a62f2806 100755--- a/tools/test-js-with-node+++ b/tools/test-js-with-node@@ -268,6 +268,7 @@ EXEMPT_FILES = make_set("web/src/stream_ui_updates.ts","web/src/submessage.ts","web/src/subscriber_api.ts",+ "web/src/tenor.ts","web/src/theme.ts","web/src/thumbnail.ts","web/src/timerender.ts",diff --git a/web/src/click_handlers.ts b/web/src/click_handlers.tsindex 6a432073fda..741a8e124b5 100644--- a/web/src/click_handlers.ts+++ b/web/src/click_handlers.ts@@ -796,7 +796,14 @@ export function initialize(): void {function handle_compose_click(e: JQuery.ClickEvent): void {const $target = $(e.target);// Emoji clicks should be handled by their own click handler in emoji_picker.js- if ($target.is(".emoji_map, img.emoji, .drag, .compose-gif-icon-giphy")) {+ if ($target.is(".emoji_map, img.emoji, .drag")) {+ return;+ }++ // GIF icon clicks should be handled by the click handlers defined in their+ // modules.+ if ($target.is(".compose-gif-icon-giphy, .compose-gif-icon-tenor")) {+ e.stopPropagation();return;}diff --git a/web/src/gif_state.ts b/web/src/gif_state.tsindex 0b0914e195a..c936d556b13 100644--- a/web/src/gif_state.ts+++ b/web/src/gif_state.ts@@ -1,5 +1,9 @@import {realm} from "./state_data.ts";+export function is_tenor_enabled(): boolean {+ return realm.tenor_api_key !== "";+}+export function is_giphy_enabled(): boolean {return (realm.giphy_api_key !== "" &&diff --git a/web/src/giphy.ts b/web/src/giphy.tsindex b864892e483..9a5c667a705 100644--- a/web/src/giphy.ts+++ b/web/src/giphy.ts@@ -163,7 +163,7 @@ function toggle_giphy_popover(target: HTMLElement): void {theme: "popover-menu",placement: "top",onCreate(instance) {- instance.setContent(ui_util.parse_html(render_gif_picker_ui()));+ instance.setContent(ui_util.parse_html(render_gif_picker_ui({is_giphy: true})));$(instance.popper).addClass("giphy-popover");},onShow(instance) {diff --git a/web/src/message_edit.ts b/web/src/message_edit.tsindex 698cc8e9b9e..48401b59591 100644--- a/web/src/message_edit.ts+++ b/web/src/message_edit.ts@@ -634,6 +634,7 @@ function edit_message($row: JQuery, raw_content: string): void {content: raw_content,file_upload_enabled,giphy_enabled: gif_state.is_giphy_enabled(),+ tenor_enabled: gif_state.is_tenor_enabled(),minutes_to_edit: Math.floor((realm.realm_message_content_edit_limit_seconds ?? 0) / 60),max_message_length: realm.max_message_length,}),diff --git a/web/src/state_data.ts b/web/src/state_data.tsindex 491f0cf560b..efe4ca5a4a2 100644--- a/web/src/state_data.ts+++ b/web/src/state_data.ts@@ -592,6 +592,7 @@ export const realm_schema = z.object({server_web_public_streams_enabled: z.boolean(),settings_send_digest_emails: z.boolean(),stop_words: z.array(z.string()),+ tenor_api_key: z.string(),upgrade_text_for_wide_organization_logo: z.string(),zulip_feature_level: z.number(),zulip_merge_base: z.string(),diff --git a/web/src/tenor.ts b/web/src/tenor.tsnew file mode 100644index 00000000000..efb7ac07454--- /dev/null+++ b/web/src/tenor.ts@@ -0,0 +1,272 @@+import $ from "jquery";+import _ from "lodash";+import assert from "minimalistic-assert";+import type * as tippy from "tippy.js";+import * as z from "zod/mini";++import render_gif_picker_ui from "../templates/gif_picker_ui.hbs";+import render_tenor_gif from "../templates/tenor_gif.hbs";++import * as channel from "./channel.ts";+import * as compose_ui from "./compose_ui.ts";+import * as popover_menus from "./popover_menus.ts";+import * as rows from "./rows.ts";+import * as scroll_util from "./scroll_util.ts";+import {realm} from "./state_data.ts";+import * as ui_util from "./ui_util.ts";+import {user_settings} from "./user_settings.ts";++const tenor_result_schema = z.object({+ results: z.array(+ z.object({+ media_formats: z.object({+ tinygif: z.object({+ url: z.url(),+ }),+ mediumgif: z.object({+ url: z.url(),+ }),+ }),+ }),+ ),+ // This denotes the identifier to use for the next API call+ // to fetch the next set of results for the current query.+ next: z.string(),+});++// Only used if popover called from edit message, otherwise it is `undefined`.+let edit_message_id: number | undefined;+let next_pos_identifier: string | number | undefined;+let is_loading_more = false;+let tenor_popover_instance: tippy.Instance | undefined;+let current_search_term: undefined | string;+const BASE_URL = "https://tenor.googleapis.com/v2";++type TenorPayload = {+ key: string;+ client_key: string;+ limit: string;+ media_filter: string;+ locale: string;+ contentfilter: string;+ pos?: typeof next_pos_identifier;+ q?: string;+};++function get_base_payload(): TenorPayload {+ return {+ key: realm.tenor_api_key,+ client_key: "ZulipWeb",+ limit: "10",+ // We use the tinygif size for the picker UI, and the mediumgif size+ // for what gets actually uploaded.+ media_filter: "tinygif,mediumgif",+ locale: user_settings.default_language,+ // TODO: This must be configurable, preferably via admin settings+ // just like GIPHY. For that we would first have to figure out+ // how to map the GIPHY and Tenor ratings, since they don't have+ // a 1:1 alignment based on the current `realm_giphy_rating` configuration.+ contentfilter: "high",+ };+}++function handle_gif_click(img_element: HTMLElement): void {+ const insert_url = img_element.dataset["insertUrl"];+ assert(insert_url !== undefined);++ let $textarea = $<HTMLTextAreaElement>("textarea#compose-textarea");+ if (edit_message_id !== undefined) {+ $textarea = $(`#edit_form_${CSS.escape(`${edit_message_id}`)} .message_edit_content`);+ }++ compose_ui.insert_syntax_and_focus(`[](${insert_url})`, $textarea, "block", 1);+ hide_tenor_popover();+}++function hide_tenor_popover(): boolean {+ // Returns `true` if the popover was open.+ if (tenor_popover_instance) {+ tenor_popover_instance.destroy();+ tenor_popover_instance = undefined;+ edit_message_id = undefined;+ next_pos_identifier = undefined;+ current_search_term = undefined;+ is_loading_more = false;+ return true;+ }+ return false;+}++function render_gifs_to_grid(raw_tenor_result: unknown, next_page: boolean): void {+ // Tenor popover may have been hidden by the+ // time this function is called.+ if (tenor_popover_instance === undefined) {+ return;+ }+ const parsed_data = tenor_result_schema.parse(raw_tenor_result);+ const urls = parsed_data.results.map((result) => ({+ preview_url: result.media_formats.tinygif.url,+ insert_url: result.media_formats.mediumgif.url,+ }));+ next_pos_identifier = parsed_data.next;+ let gif_grid_html = "";+ for (const url of urls) {+ gif_grid_html += render_tenor_gif({+ preview_url: url.preview_url,+ insert_url: url.insert_url,+ });+ }+ const $popper = $(tenor_popover_instance.popper);+ if (next_page) {+ $popper.find(".tenor-content").append($(gif_grid_html));+ } else {+ $popper.find(".gif-scrolling-container .simplebar-content-wrapper").scrollTop(0);+ $popper.find(".tenor-content").html(gif_grid_html);+ }++ is_loading_more = false;+}++function render_featured_gifs(next_page: boolean): void {+ if (is_loading_more || (current_search_term !== undefined && current_search_term.length > 0)) {+ return;+ }+ let data = get_base_payload();++ if (next_page) {+ is_loading_more = true;+ data = {...data, pos: next_pos_identifier};+ }+ void channel.get({+ url: `${BASE_URL}/featured`,+ data,+ success(raw_tenor_result) {+ render_gifs_to_grid(raw_tenor_result, next_page);+ },+ });+}++function update_grid_with_search_term(search_term: string, next_page = false): void {+ if (is_loading_more || (search_term.trim() === current_search_term && !next_page)) {+ return;+ }+ // We set `current_search_term` here to avoid using to a stale+ // version of the search term in `render_featured_gifs` for return checks+ // in case the current `search_term` is empty.+ current_search_term = search_term;+ if (search_term.trim().length === 0) {+ render_featured_gifs(next_page);+ return;+ }+ let data: TenorPayload = {+ q: search_term,+ ...get_base_payload(),+ };++ if (next_page) {+ is_loading_more = true;+ data = {...data, pos: next_pos_identifier};+ }++ void channel.get({+ url: `${BASE_URL}/search`,+ data,+ success(raw_tenor_result) {+ render_gifs_to_grid(raw_tenor_result, next_page);+ },+ });+}++function toggle_tenor_popover(target: HTMLElement): void {+ popover_menus.toggle_popover_menu(+ target,+ {+ theme: "popover-menu",+ placement: "top",+ onCreate(instance) {+ instance.setContent(ui_util.parse_html(render_gif_picker_ui({is_giphy: false})));+ $(instance.popper).addClass("tenor-popover");+ },+ onShow(instance) {+ tenor_popover_instance = instance;+ const $popper = $(instance.popper).trigger("focus");+ const debounced_search = _.debounce((search_term: string) => {+ update_grid_with_search_term(search_term);+ }, 300);+ const $click_target = $(instance.reference);+ if ($click_target.parents(".message_edit_form").length === 1) {+ // Store message id in global variable edit_message_id so that+ // its value can be further used to correctly find the message textarea element.+ edit_message_id = rows.id($click_target.parents(".message_row"));+ } else {+ edit_message_id = undefined;+ }+ $popper.on("keyup", "#gif-search-query", (e) => {+ assert(e.target instanceof HTMLInputElement);+ debounced_search(e.target.value);+ });+ $popper.on("click", ".tenor-gif", (e) => {+ assert(e.currentTarget instanceof HTMLElement);+ handle_gif_click(e.currentTarget);+ });++ $popper.on("keydown", ".tenor-gif", (e) => {+ assert(e.currentTarget instanceof HTMLElement);+ const key = e.key;+ if (key === "Enter" || key === " " || key === "Spacebar") {+ // Meant to avoid page scroll on pressing space.+ e.preventDefault();+ handle_gif_click(e.currentTarget);+ }+ });+ },+ onMount(instance) {+ render_featured_gifs(false);+ const $popper = $(instance.popper);+ $popper.find("#gif-search-query").trigger("focus");++ const scroll_element = scroll_util.get_scroll_element(+ $(".gif-scrolling-container"),+ )[0];+ assert(scroll_element instanceof HTMLElement);++ scroll_element.addEventListener("scroll", () => {+ if (+ scroll_element.scrollTop + scroll_element.clientHeight >+ scroll_element.scrollHeight - scroll_element.clientHeight+ ) {+ if (is_loading_more) {+ return;+ }+ if (current_search_term === undefined) {+ render_featured_gifs(true);+ return;+ }+ update_grid_with_search_term(current_search_term, true);+ }+ });+ },+ onHidden() {+ hide_tenor_popover();+ },+ },+ {+ show_as_overlay_on_mobile: true,+ show_as_overlay_always: false,+ },+ );+}++function register_click_handlers(): void {+ $("body").on(+ "click",+ ".compose_control_button.compose-gif-icon-tenor",+ function (this: HTMLElement) {+ toggle_tenor_popover(this);+ },+ );+}++export function initialize(): void {+ register_click_handlers();+}diff --git a/web/src/ui_init.js b/web/src/ui_init.jsindex fb835a4c244..7615bf7f822 100644--- a/web/src/ui_init.js+++ b/web/src/ui_init.js@@ -149,6 +149,7 @@ import * as stream_settings_ui from "./stream_settings_ui.ts";import * as stream_topic_history from "./stream_topic_history.ts";import * as stream_topic_history_util from "./stream_topic_history_util.ts";import * as sub_store from "./sub_store.ts";+import * as tenor from "./tenor.ts";import * as theme from "./theme.ts";import * as thumbnail from "./thumbnail.ts";import * as timerender from "./timerender.ts";@@ -210,6 +211,7 @@ function initialize_compose_box() {file_upload_enabled: realm.max_file_upload_size_mib > 0 && upload.feature_check(),giphy_enabled: gif_state.is_giphy_enabled(),max_stream_name_length: realm.max_stream_name_length,+ tenor_enabled: gif_state.is_tenor_enabled(),max_topic_length: realm.max_topic_length,empty_string_topic_display_name: util.get_final_topic_display_name(""),}),@@ -664,6 +666,7 @@ export async function initialize_everything(state_data) {gear_menu.initialize();navbar_help_menu.initialize();giphy.initialize();+ tenor.initialize();presence.initialize(state_data.presence);settings_preferences.initialize();settings_notifications.initialize();diff --git a/web/styles/popovers.css b/web/styles/popovers.cssindex 067c2bf837a..0958e875ef1 100644--- a/web/styles/popovers.css+++ b/web/styles/popovers.css@@ -668,10 +668,11 @@ ul.popover-group-menu-member-list {}.giphy-popover,+.tenor-popover,.emoji-popover-root {.tippy-content {/* We remove the default padding from this container- as it is not necessary for the Giphy popover. */+ as it is not necessary for the Giphy and Tenor popovers. */padding: 0;/* By resetting to the default color from the `body`,@@ -703,18 +704,34 @@ ul.popover-group-menu-member-list {}.gif-grid-in-popover {- /* 300px of GIPHY grid + 5px is the extra gutter space+ /* 300px of GIF grid + 5px is the extra gutter space* + 1px for outline.* between gif columns. */width: 306px;border: 0;padding: 0;- .giphy-gif {+ .tenor-content {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));+ grid-auto-rows: auto;+ gap: 6px;+ }++ .giphy-gif,+ .tenor-gif {cursor: pointer;}- .giphy-gif:focus {+ .tenor-gif {+ width: 100%;+ height: 100%;+ border-radius: 10px;+ object-fit: cover;+ }++ .giphy-gif:focus,+ .tenor-gif:focus {/* Red outline for clear visibility* of which image is in focus.*/diff --git a/web/templates/compose_control_buttons.hbs b/web/templates/compose_control_buttons.hbsindex f1c59022670..5c30a6cf868 100644--- a/web/templates/compose_control_buttons.hbs+++ b/web/templates/compose_control_buttons.hbs@@ -24,9 +24,12 @@<div class="compose_control_button_container preview_mode_disabled compose_button_tooltip" data-tooltip-template-id="add-global-time-tooltip" data-tippy-maxWidth="none"><a role="button" class="compose_control_button zulip-icon zulip-icon-time time_pick" aria-label="{{t 'Add global time' }}" tabindex=0></a></div>- <div class="compose_control_button_container {{#unless giphy_enabled }}hide{{/unless}} preview_mode_disabled compose_button_tooltip" data-tippy-content="{{t 'Add GIF' }}">- <a role="button" class="compose_control_button compose-gif-icon-giphy zulip-icon zulip-icon-gif" aria-label="{{t 'Add GIF' }}" tabindex=0></a>- </div>+ {{#if (or tenor_enabled giphy_enabled)}}+ {{!-- We prefer showing the Tenor picker over the GIPHY picker, if both are enabled. --}}+ <div class="compose_control_button_container preview_mode_disabled compose_button_tooltip" data-tippy-content="{{t 'Add GIF' }}">+ <a role="button" class="compose_control_button {{#if tenor_enabled}}compose-gif-icon-tenor{{else}}compose-gif-icon-giphy{{/if}} zulip-icon zulip-icon-gif" aria-label="{{t 'Add GIF' }}" tabindex=0></a>+ </div>+ {{/if}}{{#if message_id}}<div class="compose_control_button_container preview_mode_disabled compose_button_tooltip" data-tooltip-template-id="add-saved-snippet-tooltip"><a role="button" class="saved_snippets_widget saved-snippets-message-edit-widget compose_control_button zulip-icon zulip-icon-message-square-text" aria-label="{{t 'Add saved snippet' }}" data-message-id="{{message_id}}" tabindex=0></a>diff --git a/web/templates/gif_picker_ui.hbs b/web/templates/gif_picker_ui.hbsindex 2aeed150a95..1fec440f1d4 100644--- a/web/templates/gif_picker_ui.hbs+++ b/web/templates/gif_picker_ui.hbs@@ -2,17 +2,31 @@<div class="arrow"></div><div class="popover-inner"><div class="popover-filter-input-wrapper">- <input type="text" id="gif-search-query" class="popover-filter-input filter_text_input" autocomplete="off" placeholder="{{t 'Filter' }}" autofocus/>+ {{#if is_giphy}}+ <input type="text" id="gif-search-query" class="popover-filter-input filter_text_input" autocomplete="off" placeholder="{{t 'Filter' }}" autofocus/>+ {{else}}+ <input type="text" id="gif-search-query" class="popover-filter-input filter_text_input" autocomplete="off" placeholder="{{t 'Search Tenor' }}" autofocus/>+ {{/if}}</div><div class="gif-scrolling-container" data-simplebar data-simplebar-tab-index="-1">{{! We need a container we can replacewithout removing the simplebar wrappers.- We replace the `giphy-content` when+ We replace the `giphy-content`/`tenor-content` whensearching for GIFs. }}- <div class="giphy-content"></div>- </div>- <div class="popover-footer">- <img src="../images/giphy/GIPHY_attribution.png" alt="{{t 'GIPHY attribution' }}" />+ {{#if is_giphy}}+ <div class="giphy-content"></div>+ {{else}}+ <div class="tenor-content"></div>+ {{/if}}</div>+ {{!-- We are required to include the+ "Powered By GIPHY" banner, which isn't mandatory+ for Tenor. So we avoid including one for Tenor+ to save space. --}}+ {{#if is_giphy}}+ <div class="popover-footer">+ <img src="../images/giphy/GIPHY_attribution.png" alt="{{t 'GIPHY attribution' }}" />+ </div>+ {{/if}}</div></div>diff --git a/web/templates/tenor_gif.hbs b/web/templates/tenor_gif.hbsnew file mode 100644index 00000000000..c3e313b5795--- /dev/null+++ b/web/templates/tenor_gif.hbs@@ -0,0 +1 @@+<img src="{{preview_url}}" data-insert-url="{{insert_url}}" class="tenor-gif" tabindex="0" loading="lazy"/>diff --git a/zerver/lib/events.py b/zerver/lib/events.pyindex d66aae7d877..00799a349d6 100644--- a/zerver/lib/events.py+++ b/zerver/lib/events.py@@ -918,6 +918,10 @@ def fetch_initial_state_data(# abuse.state["giphy_api_key"] = settings.GIPHY_API_KEY if settings.GIPHY_API_KEY else ""+ if want("tenor"):+ # See Giphy comment above; Tenor API keys work similarly.+ state["tenor_api_key"] = settings.TENOR_API_KEY if settings.TENOR_API_KEY else ""+if want("push_device"):state["push_devices"] = {} if user_profile is None else get_push_devices(user_profile)diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex b7eb6eb6d25..dfe026b7310 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -18295,6 +18295,23 @@ paths:before using this API key.**Changes**: Added in Zulip 4.0 (feature level 47).+ tenor_api_key:+ type: string+ description: |+ Present if `tenor` is present in `fetch_event_types`.++ Tenor API keys are meant to be sent to the clients, see the+ examples in the [Tenor Endpoints documentation](https://developers.google.com/tenor/guides/endpoints).+ Please don't use our API key for an app unrelated to Zulip.++ Developers of clients are recommended to use their Zulip client string,+ like `ZulipFlutter`, as the `client` in the Tenor API to differentiate+ across clients as per the [Tenor Endpoints documentation](https://developers.google.com/tenor/guides/endpoints).++ Developers of clients should also read the+ [Tenor API TOS](https://developers.google.com/tenor/guides/api-terms).++ **Changes**: Added in Zulip 12.0 (feature level ZF-35b8e6).push_devices:type: objectdescription: |diff --git a/zerver/tests/test_event_system.py b/zerver/tests/test_event_system.pyindex 1a4c4c44070..55d1c71f11a 100644--- a/zerver/tests/test_event_system.py+++ b/zerver/tests/test_event_system.py@@ -1226,6 +1226,7 @@ class FetchQueriesTest(ZulipTestCase):default_stream_groups=1,drafts=1,giphy=0,+ tenor=0,message=1,muted_topics=1,muted_users=1,diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex c76181f7bd8..6322aa8146f 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -87,6 +87,7 @@ class HomeTest(ZulipTestCase):"event_queue_longpoll_timeout_seconds","full_name","giphy_api_key",+ "tenor_api_key","giphy_rating_options","has_zoom_token","is_admin",diff --git a/zproject/default_settings.py b/zproject/default_settings.pyindex 6547443de3f..4f4231d1ad1 100644--- a/zproject/default_settings.py+++ b/zproject/default_settings.py@@ -188,6 +188,9 @@ JITSI_SERVER_URL: str | None = "https://meet.jit.si"# GIPHY API key.GIPHY_API_KEY = get_secret("giphy_api_key")+# Tenor API key+TENOR_API_KEY = get_secret("tenor_api_key")+# Allow setting BigBlueButton settings in zulip-secrets.conf in# development; this is useful since there are no public BigBlueButton servers.BIG_BLUE_BUTTON_URL = get_secret("big_blue_button_url", development_only=True)diff --git a/zproject/prod_settings_template.py b/zproject/prod_settings_template.pyindex d0a776c99e8..3318ffa519b 100644--- a/zproject/prod_settings_template.py+++ b/zproject/prod_settings_template.py@@ -702,9 +702,10 @@ SOCIAL_AUTH_SAML_SUPPORT_CONTACT = {# LOGGING_SHOW_PID = False#################-## Animated GIF integration powered by GIPHY. See:+## GIF picker / search engine integrations. To get an API key, see:## https://zulip.readthedocs.io/en/latest/production/gif-picker-integrations.html# GIPHY_API_KEY = "<Your API key from GIPHY>"+# TENOR_API_KEY = "<Your API key from Tenor>"################## Video call integrations.