text
stringlengths
9
39.2M
dir
stringlengths
25
226
lang
stringclasses
163 values
created_date
timestamp[s]
updated_date
timestamp[s]
repo_name
stringclasses
751 values
repo_full_name
stringclasses
752 values
star
int64
1.01k
183k
len_tokens
int64
1
18.5M
```javascript /* @flow strict-local */ import type { Store } from 'redux'; import invariant from 'invariant'; import type { Config, Persistor } from './types'; import * as logging from '../../utils/logging'; import { KEY_PREFIX } from './constants'; import purgeStoredState from './purgeStoredState'; export default function createPersistor<S: { ... }, A, D>( store: Store<S, A, D>, config: Config, ): Persistor { // defaults const serializer = config.serialize; const whitelist = config.whitelist; const keyPrefix = config.keyPrefix !== undefined ? config.keyPrefix : KEY_PREFIX; const storage = config.storage; let paused = false; let writeInProgress = false; // This is the last state we've attempted to write out. let lastWrittenState = {}; // These are the keys for which we have a failed, or not yet completed, // write since the last successful write. const outstandingKeys = new Set(); store.subscribe(() => { if (paused) { return; } write(); }); async function write() { // Take the lock if (writeInProgress) { return; } writeInProgress = true; try { // and immediately enter a try/finally to release it. // Then yield so the `subscribe` callback can promptly return. await new Promise<void>(r => setTimeout(r, 0)); let state = undefined; // eslint-disable-next-line no-cond-assign while ((state = store.getState()) !== lastWrittenState) { await writeOnce(state); } } finally { // Release the lock, so the next `subscribe` callback will start the // loop again. writeInProgress = false; } } /** * Update the storage to the given state. * * The storage is assumed to already reflect `lastWrittenState`. * On completion, sets `lastWrittenState` to `state`. * * This function must not be called concurrently. The caller is * responsible for taking an appropriate lock. */ async function writeOnce(state) { // Identify what keys we need to write. // This includes anything already in outstandingKeys, because we don't // know what value was last successfully stored for those. for (const key: string of Object.keys(state)) { // TODO(flow): Weirdly Flow would infer `key: empty` here. if (whitelist.indexOf(key) === -1) { continue; } if (state[key] === lastWrittenState[key]) { continue; } outstandingKeys.add(key); } lastWrittenState = state; if (outstandingKeys.size === 0) { // `multiSet` doesn't like an empty array, so return early. return; } // Serialize those keys' subtrees, with yields after each one. const writes = []; for (const key of outstandingKeys) { const substate: mixed = state[key]; // TODO(flow): Weirdly Flow infers `any` here. writes.push([createStorageKey(key), serializer(substate)]); await new Promise<void>(r => setTimeout(r, 0)); } // Write them all out, in one `storage.multiSet` operation. invariant(writes.length > 0, 'should have nonempty writes list'); try { // Warning: not guaranteed to be done in a transaction. await storage.multiSet(writes); } catch (e) { logging.warn(e, { message: 'An error was encountered while trying to persist this set of keys', keys: [...outstandingKeys.values()], }); throw e; } // Record success. outstandingKeys.clear(); } function createStorageKey(key) { return `${keyPrefix}${key}`; } // return `persistor` return { pause: () => { paused = true; }, resume: () => { paused = false; }, purge: keys => purgeStoredState({ storage, keyPrefix }, keys), /** * Set `lastWrittenState` to the current `store.getState()`. * * Only to be used in `persistStore`, to force `lastWrittenState` to * update with the results of `REHYDRATE` even when the persistor is * paused. */ _resetLastWrittenState: () => { lastWrittenState = store.getState(); }, }; } ```
/content/code_sandbox/src/third/redux-persist/createPersistor.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
972
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import Emoji from '../emoji/Emoji'; import { emojiTypeFromReactionType } from '../emoji/data'; import type { LocalizableText, UserOrBot } from '../types'; import styles, { createStyleSheet } from '../styles'; import { useSelector } from '../react-redux'; import UserAvatar from '../common/UserAvatar'; import ComponentList from '../common/ComponentList'; import ZulipText from '../common/ZulipText'; import { getUserStatus } from '../user-statuses/userStatusesModel'; import PresenceStatusIndicator from '../common/PresenceStatusIndicator'; import { getDisplayEmailForUser } from '../selectors'; import { Role } from '../api/permissionsTypes'; import ZulipTextIntl from '../common/ZulipTextIntl'; import { getFullNameReactText } from '../users/userSelectors'; const componentStyles = createStyleSheet({ componentListItem: { alignItems: 'center', }, statusWrapper: { justifyContent: 'center', alignItems: 'center', flexDirection: 'row', }, presenceStatusIndicator: { position: 'relative', top: 2, marginRight: 5, }, statusText: { textAlign: 'center', }, boldText: { fontWeight: 'bold', }, }); type Props = $ReadOnly<{| user: UserOrBot, showEmail: boolean, showStatus: boolean, |}>; const getRoleText = (role: Role): LocalizableText => { switch (role) { case Role.Owner: return 'Owner'; case Role.Admin: return 'Admin'; case Role.Moderator: return 'Moderator'; case Role.Member: return 'Member'; case Role.Guest: return 'Guest'; } }; export default function AccountDetails(props: Props): Node { const { user, showEmail, showStatus } = props; const userStatusText = useSelector(state => getUserStatus(state, props.user.user_id).status_text); const userStatusEmoji = useSelector( state => getUserStatus(state, props.user.user_id).status_emoji, ); const realm = useSelector(state => state.realm); const { enableGuestUserIndicator } = realm; const displayEmail = getDisplayEmailForUser(realm, user); return ( <ComponentList outerSpacing itemStyle={componentStyles.componentListItem}> <View> <UserAvatar avatarUrl={user.avatar_url} size={200} /> </View> <View style={componentStyles.statusWrapper}> <PresenceStatusIndicator style={componentStyles.presenceStatusIndicator} userId={user.user_id} hideIfOffline={false} useOpaqueBackground={false} /> <ZulipTextIntl selectable style={[styles.largerText, componentStyles.boldText]} text={getFullNameReactText({ user, enableGuestUserIndicator })} /> </View> {displayEmail !== null && showEmail && ( <View> <ZulipText selectable style={styles.largerText} text={displayEmail} /> </View> )} <View> <ZulipTextIntl selectable style={styles.largerText} text={getRoleText(user.role)} /> </View> {showStatus && ( <View style={componentStyles.statusWrapper}> {userStatusEmoji && ( <Emoji code={userStatusEmoji.emoji_code} type={emojiTypeFromReactionType(userStatusEmoji.reaction_type)} size={24} /> )} {userStatusEmoji && userStatusText !== null && <View style={{ width: 2 }} />} {userStatusText !== null && ( <ZulipText style={[styles.largerText, componentStyles.statusText]} text={userStatusText} /> )} </View> )} </ComponentList> ); } ```
/content/code_sandbox/src/account-info/AccountDetails.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
854
```javascript /** * * This source code is licensed under the MIT license found in the * docs/THIRDPARTY file from the root directory of this source tree. * * @format * @flow strict-local */ 'use strict'; import React from 'react'; import type { ElementRef, Node } from 'react'; import { Keyboard, LayoutAnimation, Platform, StyleSheet, View } from 'react-native'; import type { ViewStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet'; import type { EventSubscription } from 'react-native/Libraries/vendor/emitter/EventEmitter'; import type { KeyboardEvent } from 'react-native/Libraries/Components/Keyboard/Keyboard'; import type { ViewProps, ViewLayout, ViewLayoutEvent, } from 'react-native/Libraries/Components/View/ViewPropTypes'; type Props = $ReadOnly<{| ...ViewProps, /** * Specify how to react to the presence of the keyboard. */ behavior?: ?('height' | 'position' | 'padding'), /** * Style of the content container when `behavior` is 'position'. */ contentContainerStyle?: ?ViewStyleProp, /** * Controls whether this `KeyboardAvoidingView` instance should take effect. * This is useful when more than one is on the screen. Defaults to true. */ enabled: ?boolean, /** * Distance between the top of the user screen and the React Native view. This * may be non-zero in some cases. Defaults to 0. */ keyboardVerticalOffset: number, |}>; type State = {| bottom: number, |}; /** * View that moves out of the way when the keyboard appears by automatically * adjusting its height, position, or bottom padding. */ class KeyboardAvoidingView extends React.Component<Props, State> { static defaultProps: {|enabled: boolean, keyboardVerticalOffset: number|} = { enabled: true, keyboardVerticalOffset: 0, }; _frame: ?ViewLayout = null; _keyboardEvent: ?KeyboardEvent = null; _subscriptions: Array<EventSubscription> = []; // $FlowFixMe[unclear-type] viewRef: {current: ElementRef<any> | null, ...}; _initialFrameHeight: number = 0; constructor(props: Props) { super(props); this.state = {bottom: 0}; this.viewRef = React.createRef(); } _relativeKeyboardHeight(keyboardFrame): number { const frame = this._frame; if (!frame || !keyboardFrame) { return 0; } if (keyboardFrame.height === 0) { // The keyboard is hidden, and occupies no height. // // This condition is needed because in some circumstances when the // keyboard is hidden we get both `screenY` and `height` (as well as // `screenX` and `width`) of zero. In particular, this happens on iOS // when the UIAccessibilityPrefersCrossFadeTransitions setting is // true, i.e. when the user has enabled both "Reduce Motion" and // "Prefer Cross-Fade Transitions" under Settings > Accessibility > // Motion. See zulip/zulip-mobile#5162 and // facebook/react-native#29974. return 0; } const keyboardY = keyboardFrame.screenY - this.props.keyboardVerticalOffset; // Calculate the displacement needed for the view such that it // no longer overlaps with the keyboard return Math.max(frame.y + frame.height - keyboardY, 0); } _onKeyboardChange = (event: ?KeyboardEvent) => { this._keyboardEvent = event; this._updateBottomIfNecesarry(); }; _onLayout = (event: ViewLayoutEvent) => { const wasFrameNull = this._frame == null; this._frame = event.nativeEvent.layout; if (!this._initialFrameHeight) { // save the initial frame height, before the keyboard is visible this._initialFrameHeight = this._frame.height; } if (wasFrameNull) { this._updateBottomIfNecesarry(); } }; _updateBottomIfNecesarry = () => { if (this._keyboardEvent == null) { this.setState({bottom: 0}); return; } const {duration, easing, endCoordinates} = this._keyboardEvent; const height = this._relativeKeyboardHeight(endCoordinates); if (this.state.bottom === height) { return; } // $FlowFixMe[sketchy-number-and] if (duration && easing) { LayoutAnimation.configureNext({ // We have to pass the duration equal to minimal accepted duration defined here: RCTLayoutAnimation.m duration: duration > 10 ? duration : 10, update: { duration: duration > 10 ? duration : 10, type: LayoutAnimation.Types[easing] || 'keyboard', }, }); } this.setState({bottom: height}); }; componentDidMount(): void { if (Platform.OS === 'ios') { this._subscriptions = [ Keyboard.addListener('keyboardWillChangeFrame', this._onKeyboardChange), ]; } else { this._subscriptions = [ Keyboard.addListener('keyboardDidHide', this._onKeyboardChange), Keyboard.addListener('keyboardDidShow', this._onKeyboardChange), ]; } } componentWillUnmount(): void { this._subscriptions.forEach(subscription => { subscription.remove(); }); } render(): Node { const { behavior, children, contentContainerStyle, enabled, keyboardVerticalOffset, style, ...props } = this.props; // $FlowFixMe[sketchy-null-bool] const bottomHeight = enabled ? this.state.bottom : 0; switch (behavior) { case 'height': let heightStyle; if (this._frame != null && this.state.bottom > 0) { // Note that we only apply a height change when there is keyboard present, // i.e. this.state.bottom is greater than 0. If we remove that condition, // this.frame.height will never go back to its original value. // When height changes, we need to disable flex. heightStyle = { height: this._initialFrameHeight - bottomHeight, flex: 0, }; } return ( <View ref={this.viewRef} style={StyleSheet.compose(style, heightStyle)} onLayout={this._onLayout} {...props}> {children} </View> ); case 'position': return ( <View ref={this.viewRef} style={style} onLayout={this._onLayout} {...props}> <View style={StyleSheet.compose(contentContainerStyle, { bottom: bottomHeight, })}> {children} </View> </View> ); case 'padding': return ( <View ref={this.viewRef} style={StyleSheet.compose(style, {paddingBottom: bottomHeight})} onLayout={this._onLayout} {...props}> {children} </View> ); default: return ( <View ref={this.viewRef} onLayout={this._onLayout} style={style} {...props}> {children} </View> ); } } } export default KeyboardAvoidingView; ```
/content/code_sandbox/src/third/react-native/KeyboardAvoidingView.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,628
```javascript /* @flow strict-local */ import React, { useCallback } from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import invariant from 'invariant'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import type { UserId } from '../types'; import globalStyles, { createStyleSheet } from '../styles'; import { useSelector, useDispatch } from '../react-redux'; import Screen from '../common/Screen'; import ZulipButton from '../common/ZulipButton'; import ZulipTextIntl from '../common/ZulipTextIntl'; import { IconPrivateChat } from '../common/Icons'; import { pm1to1NarrowFromUser } from '../utils/narrow'; import AccountDetails from './AccountDetails'; import ZulipText from '../common/ZulipText'; import ActivityText from '../title/ActivityText'; import { doNarrow } from '../actions'; import { getFullNameReactText, getUserIsActive, tryGetUserForId } from '../users/userSelectors'; import { nowInTimeZone } from '../utils/date'; import CustomProfileFields from './CustomProfileFields'; import { getRealm } from '../directSelectors'; const styles = createStyleSheet({ errorText: { marginHorizontal: 16, marginVertical: 32, textAlign: 'center', }, pmButton: { marginHorizontal: 16, marginBottom: 16, }, deactivatedText: { textAlign: 'center', paddingBottom: 20, fontStyle: 'italic', fontSize: 18, }, itemWrapper: { alignItems: 'center', marginBottom: 16, marginHorizontal: 16, }, }); type Props = $ReadOnly<{| navigation: AppNavigationProp<'account-details'>, route: RouteProp<'account-details', {| userId: UserId |}>, |}>; export default function AccountDetailsScreen(props: Props): Node { const dispatch = useDispatch(); const user = useSelector(state => tryGetUserForId(state, props.route.params.userId)); const isActive = useSelector(state => getUserIsActive(state, props.route.params.userId)); const enableGuestUserIndicator = useSelector(state => getRealm(state).enableGuestUserIndicator); const handleChatPress = useCallback(() => { invariant(user, 'Callback handleChatPress is used only if user is known'); dispatch(doNarrow(pm1to1NarrowFromUser(user))); }, [user, dispatch]); if (!user) { return ( <Screen title="Error"> <ZulipText style={styles.errorText} text="Could not show user profile." /> </Screen> ); } let localTime: string | null = null; // See comments at CrossRealmBot and User at src/api/modelTypes.js. if (user.timezone !== '' && user.timezone !== undefined) { try { localTime = `${nowInTimeZone(user.timezone)} Local time`; } catch { // The set of timezone names in the tz database is subject to change over // time. Handle unrecognized timezones by quietly discarding them. } } return ( <Screen title={getFullNameReactText({ user, enableGuestUserIndicator })}> <AccountDetails user={user} showEmail showStatus /> <View style={styles.itemWrapper}> <ActivityText style={globalStyles.largerText} user={user} /> </View> {localTime !== null && ( <View style={styles.itemWrapper}> <ZulipText style={globalStyles.largerText} text={localTime} /> </View> )} <View style={styles.itemWrapper}> <CustomProfileFields user={user} /> </View> {!isActive && ( <ZulipTextIntl style={styles.deactivatedText} text="(This user has been deactivated)" /> )} <ZulipButton style={styles.pmButton} text={isActive ? 'Send direct message' : 'View direct messages'} onPress={handleChatPress} Icon={IconPrivateChat} /> </Screen> ); } ```
/content/code_sandbox/src/account-info/AccountDetailsScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
882
```javascript // @flow strict-local import * as React from 'react'; import { View } from 'react-native'; import { type UserOrBot, type UserId } from '../api/modelTypes'; import WebLink from '../common/WebLink'; import ZulipText from '../common/ZulipText'; import { ensureUnreachable } from '../generics'; import { useSelector } from '../react-redux'; import { type CustomProfileFieldValue, getCustomProfileFieldsForUser, } from '../users/userSelectors'; import UserItem from '../users/UserItem'; import { useNavigation } from '../react-navigation'; type Props = {| +user: UserOrBot, |}; function CustomProfileFieldUser(props: {| +userId: UserId |}): React.Node { const { userId } = props; const navigation = useNavigation(); const onPress = React.useCallback( (user: UserOrBot) => { navigation.push('account-details', { userId: user.user_id }); }, [navigation], ); return <UserItem userId={userId} onPress={onPress} size="medium" />; } function CustomProfileFieldRow(props: {| +name: string, +value: CustomProfileFieldValue, +first: boolean, |}): React.Node { const { first, name, value } = props; const styles = React.useMemo( () => ({ row: { marginTop: first ? 0 : 8, flexDirection: 'row' }, label: { width: 96, fontWeight: 'bold' }, valueView: { flex: 1, paddingStart: 8 }, valueText: { flex: 1, paddingStart: 8 }, // The padding difference compensates for the paddingHorizontal in UserItem. valueUnpadded: { flex: 1 }, }), [first], ); let valueElement = undefined; switch (value.displayType) { case 'text': valueElement = <ZulipText selectable style={styles.valueText} text={value.text} />; break; case 'link': valueElement = ( <View style={styles.valueView}> {value.url ? ( <WebLink url={value.url} text={value.text} /> ) : ( <ZulipText text={value.text} /> )} </View> ); break; case 'users': valueElement = ( <View style={styles.valueUnpadded}> {value.userIds.map(userId => ( <CustomProfileFieldUser key={userId} userId={userId} /> ))} </View> ); break; default: ensureUnreachable(value.displayType); return null; } return ( <View style={styles.row}> <ZulipText style={styles.label} text={name} /> {valueElement} </View> ); } export default function CustomProfileFields(props: Props): React.Node { const { user } = props; const realm = useSelector(state => state.realm); const fields = React.useMemo(() => getCustomProfileFieldsForUser(realm, user), [realm, user]); const styles = React.useMemo( () => ({ outer: { flexDirection: 'row', justifyContent: 'center' }, inner: { flexBasis: 400, flexShrink: 1 }, }), [], ); return ( <View style={styles.outer}> <View style={styles.inner}> {fields.map((field, i) => ( <CustomProfileFieldRow key={field.fieldId} name={field.name} value={field.value} first={i === 0} /> ))} </View> </View> ); } ```
/content/code_sandbox/src/account-info/CustomProfileFields.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
800
```javascript /* @flow strict-local */ /** * This exposes the native CustomTabsAndroid module as a JS module. This has a * function 'openURL' which takes the following parameters: * * 1. String url: A url to be opened in customTabs */ import { NativeModules } from 'react-native'; export default NativeModules.ShareFileAndroid; ```
/content/code_sandbox/src/nativeModules/ShareFileAndroid.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
75
```javascript /* @flow strict-local */ import React, { useContext } from 'react'; import type { Node } from 'react'; import { ScrollView, View } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import { type UserId } from '../api/idTypes'; import { TranslationContext } from '../boot/TranslationProvider'; import { noTranslation } from '../i18n/i18n'; import type { RouteProp } from '../react-navigation'; import type { MainTabsNavigationProp } from '../main/MainTabsScreen'; import { createStyleSheet } from '../styles'; import { useDispatch, useSelector } from '../react-redux'; import ZulipButton from '../common/ZulipButton'; import { logout } from '../account/logoutActions'; import { tryStopNotifications } from '../notification/notifTokens'; import AccountDetails from './AccountDetails'; import { getRealm } from '../directSelectors'; import { getOwnUser, getOwnUserId } from '../users/userSelectors'; import { getAuth, getAccount, getZulipFeatureLevel } from '../account/accountsSelectors'; import { useNavigation } from '../react-navigation'; import { showConfirmationDialog } from '../utils/info'; import { OfflineNoticePlaceholder } from '../boot/OfflineNoticeProvider'; import { getUserStatus } from '../user-statuses/userStatusesModel'; import SwitchRow from '../common/SwitchRow'; import * as api from '../api'; import { identityOfAccount } from '../account/accountMisc'; import NavRow from '../common/NavRow'; import { emojiTypeFromReactionType } from '../emoji/data'; const styles = createStyleSheet({ buttonRow: { flexDirection: 'row', marginHorizontal: 8, }, button: { flex: 1, margin: 8, }, }); function ProfileButton(props: {| +ownUserId: UserId |}) { const navigation = useNavigation(); return ( <ZulipButton style={styles.button} secondary text="Full profile" onPress={() => { navigation.push('account-details', { userId: props.ownUserId }); }} /> ); } function SettingsButton(props: {||}) { const navigation = useNavigation(); return ( <ZulipButton style={styles.button} secondary text="Settings" onPress={() => { navigation.push('settings'); }} /> ); } function SwitchAccountButton(props: {||}) { const navigation = useNavigation(); return ( <ZulipButton style={styles.button} secondary text="Switch account" onPress={() => { navigation.push('account-pick'); }} /> ); } function LogoutButton(props: {||}) { const dispatch = useDispatch(); const _ = useContext(TranslationContext); const account = useSelector(getAccount); const identity = identityOfAccount(account); return ( <ZulipButton style={styles.button} secondary text="Log out" onPress={() => { showConfirmationDialog({ destructive: true, title: 'Log out', message: { text: 'This will log out {email} on {realmUrl} from the mobile app on this device.', values: { email: identity.email, realmUrl: identity.realm.toString() }, }, onPressConfirm: () => { dispatch(tryStopNotifications(account)); dispatch(logout()); }, _, }); }} /> ); } type Props = $ReadOnly<{| navigation: MainTabsNavigationProp<'profile'>, route: RouteProp<'profile', void>, |}>; /** * The profile/settings/account screen we offer among the main tabs of the app. */ export default function ProfileScreen(props: Props): Node { const navigation = useNavigation(); const auth = useSelector(getAuth); const zulipFeatureLevel = useSelector(getZulipFeatureLevel); const ownUser = useSelector(getOwnUser); const ownUserId = useSelector(getOwnUserId); const presenceEnabled = useSelector(state => getRealm(state).presenceEnabled); const awayStatus = useSelector(state => getUserStatus(state, ownUserId).away); const userStatus = useSelector(state => getUserStatus(state, ownUserId)); const { status_emoji, status_text } = userStatus; return ( <SafeAreaView mode="padding" edges={['top']} style={{ flex: 1 }}> <OfflineNoticePlaceholder /> <ScrollView> <AccountDetails user={ownUser} showEmail={false} showStatus={false} /> <NavRow leftElement={ status_emoji != null ? { type: 'emoji', emojiCode: status_emoji.emoji_code, emojiType: emojiTypeFromReactionType(status_emoji.reaction_type), } : undefined } title="Set your status" subtitle={status_text != null ? noTranslation(status_text) : undefined} onPress={() => { navigation.push('user-status'); }} /> {zulipFeatureLevel >= 148 ? ( <SwitchRow label="Invisible mode" /* $FlowIgnore[incompatible-cast] - Only null when FL is <89; see comment on RealmState['presenceEnabled'] */ value={!(presenceEnabled: boolean)} onValueChange={(newValue: boolean) => { api.updateUserSettings(auth, { presence_enabled: !newValue }, zulipFeatureLevel); }} /> ) : ( // TODO(server-6.0): Remove. <SwitchRow label="Set yourself to away" value={awayStatus} onValueChange={(away: boolean) => { api.updateUserStatus(auth, { away }); }} /> )} <View style={styles.buttonRow}> <ProfileButton ownUserId={ownUser.user_id} /> </View> <View style={styles.buttonRow}> <SettingsButton /> </View> <View style={styles.buttonRow}> <SwitchAccountButton /> <LogoutButton /> </View> </ScrollView> </SafeAreaView> ); } ```
/content/code_sandbox/src/account-info/ProfileScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,296
```javascript /* @flow strict-local */ import { EventTypes } from '../api/eventTypes'; import type { SubscriptionsState, PerAccountApplicableAction } from '../types'; import { ensureUnreachable } from '../types'; import { updateStreamProperties } from '../streams/streamsReducer'; import { EVENT_SUBSCRIPTION, REGISTER_COMPLETE, EVENT, RESET_ACCOUNT_DATA, } from '../actionConstants'; import { NULL_ARRAY } from '../nullObjects'; import { filterArray } from '../utils/immutability'; const initialState: SubscriptionsState = NULL_ARRAY; export default ( state: SubscriptionsState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, ): SubscriptionsState => { switch (action.type) { case RESET_ACCOUNT_DATA: return initialState; case REGISTER_COMPLETE: return action.data.subscriptions; case EVENT_SUBSCRIPTION: switch (action.op) { case 'add': return state.concat( action.subscriptions.filter(x => !state.find(y => x.stream_id === y.stream_id)), ); case 'remove': return filterArray( state, x => !action.subscriptions.find(y => x && y && x.stream_id === y.stream_id), ); case 'update': return state.map(sub => sub.stream_id === action.stream_id ? { ...sub, [action.property]: action.value } : sub, ); case 'peer_add': case 'peer_remove': // we currently do not track subscribers return state; default: ensureUnreachable(action); return state; } case EVENT: { const { event } = action; switch (event.type) { case EventTypes.stream: switch (event.op) { case 'update': return state.map(sub => // If inlining `updateStreamProperties` with plans to change // its logic, note that it has test coverage at its other // callsite, but not here, as of 2022-04-19. sub.stream_id === event.stream_id ? updateStreamProperties(sub, event) : sub, ); case 'delete': return filterArray( state, sub => !event.streams.find(stream => sub.stream_id === stream.stream_id), ); case 'create': case 'occupy': case 'vacate': return state; default: ensureUnreachable(event); return state; } default: return state; } } default: return state; } }; ```
/content/code_sandbox/src/subscriptions/subscriptionsReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
538
```javascript /* @flow strict-local */ import React, { useCallback, useMemo } from 'react'; import type { Node } from 'react'; import { FlatList } from 'react-native'; import Screen from '../common/Screen'; import type { RouteProp } from '../react-navigation'; import type { AppNavigationProp } from '../nav/AppNavigator'; import { createStyleSheet } from '../styles'; import { useDispatch, useSelector } from '../react-redux'; import ZulipButton from '../common/ZulipButton'; import SearchEmptyState from '../common/SearchEmptyState'; import * as api from '../api'; import { delay } from '../utils/async'; import { streamNarrow } from '../utils/narrow'; import { getAuth, getCanCreateStreams, getStreams } from '../selectors'; import { doNarrow } from '../actions'; import { caseInsensitiveCompareFunc } from '../utils/misc'; import StreamItem from '../streams/StreamItem'; import { getSubscriptionsById } from './subscriptionSelectors'; const styles = createStyleSheet({ button: { margin: 16, }, list: { flex: 1, flexDirection: 'column', }, }); type Props = $ReadOnly<{| navigation: AppNavigationProp<'all-streams'>, route: RouteProp<'all-streams', void>, |}>; export default function StreamListScreen(props: Props): Node { const { navigation } = props; const dispatch = useDispatch(); const auth = useSelector(getAuth); const canCreateStreams = useSelector(getCanCreateStreams); const subscriptions = useSelector(getSubscriptionsById); const streams = useSelector(getStreams); const sortedStreams = useMemo( () => streams.slice().sort((a, b) => caseInsensitiveCompareFunc(a.name, b.name)), [streams], ); const handleSubscribeButtonPressed = useCallback( (stream, value: boolean) => { if (value) { // This still uses a stream name (#3918) because the API method does; see there. api.subscriptionAdd(auth, [{ name: stream.name }]); } else { // This still uses a stream name (#3918) because the API method does; see there. api.subscriptionRemove(auth, [stream.name]); } }, [auth], ); const handleNarrow = useCallback( stream => dispatch(doNarrow(streamNarrow(stream.stream_id))), [dispatch], ); return ( <Screen scrollEnabled={false} title="All streams"> {canCreateStreams && ( <ZulipButton style={styles.button} secondary text="Create new stream" onPress={() => delay(() => { navigation.push('create-stream'); }) } /> )} {streams.length === 0 ? ( <SearchEmptyState text="No streams found" /> ) : ( <FlatList style={styles.list} data={sortedStreams} initialNumToRender={20} keyExtractor={item => item.stream_id.toString()} renderItem={({ item }) => ( <StreamItem streamId={item.stream_id} name={item.name} iconSize={16} isPrivate={item.invite_only} isWebPublic={item.is_web_public} description={item.description} color={ /* Even if the user happens to be subscribed to this stream, we don't show their subscription color. */ undefined } unreadCount={undefined} isMuted={ /* This stream may in reality be muted. But in this UI, we don't show that distinction. */ false } offersSubscribeButton isSubscribed={subscriptions.has(item.stream_id)} onPress={handleNarrow} onSubscribeButtonPressed={handleSubscribeButtonPressed} /> )} /> )} </Screen> ); } ```
/content/code_sandbox/src/subscriptions/StreamListScreen.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
816
```javascript /* @flow strict-local */ import { createSelector } from 'reselect'; import type { PerAccountState, Narrow, Selector, Stream, Subscription } from '../types'; import { isStreamOrTopicNarrow, streamIdOfNarrow } from '../utils/narrow'; import { getSubscriptions, getStreams } from '../directSelectors'; /** * All streams in the current realm, by ID. * * Prefer `getStreamForId` for all normal UI specific to a stream, and other * codepaths which relate to a single stream and assume it exists. * * This selector is appropriate when a stream might not exist, or multiple * streams are relevant. * * See also `getStreams` for the stream objects as an array. */ export const getStreamsById: Selector<Map<number, Stream>> = createSelector( getStreams, streams => new Map(streams.map(stream => [stream.stream_id, stream])), ); export const getStreamsByName: Selector<Map<string, Stream>> = createSelector( getStreams, streams => new Map(streams.map(stream => [stream.name, stream])), ); export const getSubscriptionsById: Selector<Map<number, Subscription>> = createSelector( getSubscriptions, subscriptions => new Map(subscriptions.map(subscription => [subscription.stream_id, subscription])), ); export const getIsActiveStreamSubscribed: Selector<boolean, Narrow> = createSelector( (state, narrow) => narrow, state => getSubscriptionsById(state), (narrow, subscriptions) => { if (!isStreamOrTopicNarrow(narrow)) { return true; } return subscriptions.get(streamIdOfNarrow(narrow)) !== undefined; }, ); /** * The stream with the given ID; throws if none. * * This is for use in all the normal UI specific to a stream, including * stream and topic narrows and stream messages, and other codepaths which * assume the given stream exists. * * See `getStreamsById` for use when a stream might not exist, or when * multiple streams are relevant. */ export const getStreamForId = (state: PerAccountState, streamId: number): Stream => { const stream = getStreamsById(state).get(streamId); if (!stream) { throw new Error(`getStreamForId: missing stream: id ${streamId}`); } return stream; }; export const getIsActiveStreamAnnouncementOnly: Selector<boolean, Narrow> = createSelector( (state, narrow) => narrow, state => getStreamsById(state), (narrow, streams) => { if (!isStreamOrTopicNarrow(narrow)) { return false; } const stream = streams.get(streamIdOfNarrow(narrow)); return stream ? stream.is_announcement_only : false; }, ); /** * The stream's color for the given stream or topic narrow. * * Gives undefined for narrows that are not stream or topic narrows. */ export const getStreamColorForNarrow = (state: PerAccountState, narrow: Narrow): string | void => { if (!isStreamOrTopicNarrow(narrow)) { return undefined; } const subscriptionsById = getSubscriptionsById(state); const streamId = streamIdOfNarrow(narrow); return subscriptionsById.get(streamId)?.color ?? 'gray'; }; ```
/content/code_sandbox/src/subscriptions/subscriptionSelectors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
700
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import { EventTypes } from '../../api/eventTypes'; import { EVENT_SUBSCRIPTION, EVENT } from '../../actionConstants'; import subscriptionsReducer from '../subscriptionsReducer'; import * as eg from '../../__tests__/lib/exampleData'; describe('subscriptionsReducer', () => { const stream1 = eg.makeStream({ name: 'stream1', description: 'my first stream' }); const sub1 = eg.makeSubscription({ stream: stream1 }); const stream2 = eg.makeStream({ name: 'stream2', description: 'my second stream' }); const sub2 = eg.makeSubscription({ stream: stream2 }); const stream3 = eg.makeStream({ name: 'stream3', description: 'my third stream' }); const sub3 = eg.makeSubscription({ stream: stream3 }); describe('REGISTER_COMPLETE', () => { test('when `subscriptions` data is provided init state with it', () => { const initialState = deepFreeze([]); const action = eg.mkActionRegisterComplete({ subscriptions: [sub1], }); const actualState = subscriptionsReducer(initialState, action); expect(actualState).toEqual([sub1]); }); test('when `subscriptions` is an empty array, reset state', () => { const initialState = deepFreeze([sub1]); const action = eg.mkActionRegisterComplete({ subscriptions: [], }); const expectedState = []; const actualState = subscriptionsReducer(initialState, action); expect(actualState).toEqual(expectedState); }); }); describe('EVENT_SUBSCRIPTION -> add', () => { test('if new subscriptions do not exist in state, add them', () => { const prevState = deepFreeze([]); const action = deepFreeze({ type: EVENT_SUBSCRIPTION, op: 'add', id: 1, subscriptions: [sub1, sub2], }); const expectedState = [sub1, sub2]; const newState = subscriptionsReducer(prevState, action); expect(newState).toEqual(expectedState); }); test('if some of subscriptions already exist, do not add them', () => { const prevState = deepFreeze([sub1]); const action = deepFreeze({ type: EVENT_SUBSCRIPTION, op: 'add', id: 1, subscriptions: [sub1, sub2], }); const expectedState = [sub1, sub2]; const newState = subscriptionsReducer(prevState, action); expect(newState).toEqual(expectedState); }); }); describe('EVENT_SUBSCRIPTION -> remove', () => { test('removes subscriptions from state', () => { const prevState = deepFreeze([sub1, sub2, sub3]); const action = deepFreeze({ type: EVENT_SUBSCRIPTION, op: 'remove', id: 1, subscriptions: [ { name: sub1.name, stream_id: sub1.stream_id }, { name: sub2.name, stream_id: sub2.stream_id }, ], }); const expectedState = [sub3]; const newState = subscriptionsReducer(prevState, action); expect(newState).toEqual(expectedState); }); test('removes subscriptions that exist, do nothing if not', () => { const prevState = deepFreeze([sub1]); const action = deepFreeze({ type: EVENT_SUBSCRIPTION, op: 'remove', id: 1, subscriptions: [ { name: sub1.name, stream_id: sub1.stream_id }, { name: sub2.name, stream_id: sub2.stream_id }, ], }); const expectedState = []; const newState = subscriptionsReducer(prevState, action); expect(newState).toEqual(expectedState); }); }); describe('EVENT_SUBSCRIPTION -> update', () => { test('Change the in_home_view property', () => { const subNotInHomeView = eg.makeSubscription({ stream: stream1, in_home_view: false }); const initialState = deepFreeze([subNotInHomeView, sub2, sub3]); const action = deepFreeze({ type: EVENT_SUBSCRIPTION, op: 'update', id: 2, stream_id: subNotInHomeView.stream_id, property: 'in_home_view', value: true, }); const actualState = subscriptionsReducer(initialState, action); const expectedState = [{ ...subNotInHomeView, in_home_view: true }, sub2, sub3]; expect(actualState).toEqual(expectedState); }); }); describe('EventTypes.stream, op: delete', () => { test('when a stream is delrted but user is not subscribed to it, do not change state', () => { const initialState = deepFreeze([sub3]); const action = deepFreeze({ type: EVENT, event: { type: EventTypes.stream, id: 1, op: 'delete', streams: [stream1], }, }); const actualState = subscriptionsReducer(initialState, action); expect(actualState).toBe(initialState); }); test('when a stream is deleted the user is unsubscribed', () => { const initialState = deepFreeze([sub1]); const action = deepFreeze({ type: EVENT, event: { type: EventTypes.stream, id: 1, op: 'delete', streams: [stream1, stream2], }, }); const expectedState = []; const actualState = subscriptionsReducer(initialState, action); expect(actualState).toEqual(expectedState); }); test('when multiple streams are deleted the user is unsubscribed from all of them', () => { const initialState = deepFreeze([sub1, sub2]); const action = deepFreeze({ type: EVENT, event: { type: EventTypes.stream, id: 1, op: 'delete', streams: [stream1, stream2], }, }); const expectedState = []; const actualState = subscriptionsReducer(initialState, action); expect(actualState).toEqual(expectedState); }); }); describe('RESET_ACCOUNT_DATA', () => { test('resets state to initial state', () => { const initialState = deepFreeze([sub1]); const expectedState = []; const actualState = subscriptionsReducer(initialState, eg.action.reset_account_data); expect(actualState).toEqual(expectedState); }); }); }); ```
/content/code_sandbox/src/subscriptions/__tests__/subscriptionsReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,396
```javascript // @flow strict-local import { getStreamsById, getSubscriptionsById, getIsActiveStreamSubscribed, getStreamColorForNarrow, } from '../subscriptionSelectors'; import { HOME_NARROW, streamNarrow, topicNarrow, pmNarrowFromUsersUnsafe, pm1to1NarrowFromUser, } from '../../utils/narrow'; import * as eg from '../../__tests__/lib/exampleData'; describe('getStreamsById', () => { test('returns empty map for an empty input', () => { const state = eg.reduxState({ streams: [] }); expect(getStreamsById(state)).toEqual(new Map()); }); test('returns a map with stream id as keys', () => { const state = eg.reduxState({ streams: [eg.stream, eg.otherStream] }); expect(getStreamsById(state)).toEqual( new Map([ [eg.stream.stream_id, eg.stream], [eg.otherStream.stream_id, eg.otherStream], ]), ); }); }); describe('getSubscriptionsById', () => { test('returns empty map for an empty input', () => { const state = eg.reduxState({ subscriptions: [] }); expect(getSubscriptionsById(state)).toEqual(new Map()); }); test('returns a map with stream id as keys', () => { const state = eg.reduxState({ subscriptions: [eg.subscription, eg.otherSubscription] }); expect(getSubscriptionsById(state)).toEqual( new Map([ [eg.subscription.stream_id, eg.subscription], [eg.otherSubscription.stream_id, eg.otherSubscription], ]), ); }); }); describe('getIsActiveStreamSubscribed', () => { const state = eg.reduxStatePlus({ subscriptions: [eg.subscription] }); test('return true for narrows other than stream and topic', () => { expect(getIsActiveStreamSubscribed(state, HOME_NARROW)).toBe(true); }); test('return true if current narrowed stream is subscribed', () => { const narrow = streamNarrow(eg.stream.stream_id); expect(getIsActiveStreamSubscribed(state, narrow)).toBe(true); }); test('return false if current narrowed stream is not subscribed', () => { const narrow = streamNarrow(eg.otherStream.stream_id); expect(getIsActiveStreamSubscribed(state, narrow)).toBe(false); }); test('return true if stream of current narrowed topic is subscribed', () => { const narrow = topicNarrow(eg.stream.stream_id, 'news'); expect(getIsActiveStreamSubscribed(state, narrow)).toBe(true); }); test('return false if stream of current narrowed topic is not subscribed', () => { const narrow = topicNarrow(eg.otherStream.stream_id, 'news'); expect(getIsActiveStreamSubscribed(state, narrow)).toBe(false); }); }); describe('getStreamColorForNarrow', () => { const exampleColor = '#fff'; const state = eg.reduxState({ subscriptions: [eg.makeSubscription({ stream: eg.stream, color: exampleColor })], }); test('return stream color for stream and topic narrow', () => { const narrow = streamNarrow(eg.stream.stream_id); expect(getStreamColorForNarrow(state, narrow)).toEqual(exampleColor); }); test('return null stream color for invalid stream or unknown subscriptions', () => { const unknownStream = eg.makeStream(); const narrow = streamNarrow(unknownStream.stream_id); expect(getStreamColorForNarrow(state, narrow)).toEqual('gray'); }); test('return undefined for non topic/stream narrow', () => { expect(getStreamColorForNarrow(state, pm1to1NarrowFromUser(eg.otherUser))).toEqual(undefined); const narrow = pmNarrowFromUsersUnsafe([eg.otherUser, eg.thirdUser]); expect(getStreamColorForNarrow(state, narrow)).toEqual(undefined); }); }); ```
/content/code_sandbox/src/subscriptions/__tests__/subscriptionSelectors-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
838
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import type { TextStyleProp } from 'react-native/Libraries/StyleSheet/StyleSheet'; import type { UserOrBot } from '../types'; import { useSelector } from '../react-redux'; import { getUserLastActiveAsRelativeTimeString } from '../presence/presenceModel'; import ZulipText from '../common/ZulipText'; type Props = $ReadOnly<{| style: TextStyleProp, user: UserOrBot, |}>; export default function ActivityText(props: Props): Node { const { style, user } = props; const activeTime = useSelector(state => getUserLastActiveAsRelativeTimeString(state, user, Date.now()), ); if (activeTime == null) { return null; } return <ZulipText style={style} text={`Active ${activeTime}`} />; } ```
/content/code_sandbox/src/title/ActivityText.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
192
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { caseNarrow } from '../utils/narrow'; import type { Narrow, EditMessage } from '../types'; import TitlePrivate from './TitlePrivate'; import TitleGroup from './TitleGroup'; import TitleSpecial from './TitleSpecial'; import TitleStream from './TitleStream'; import TitlePlain from './TitlePlain'; type Props = $ReadOnly<{| narrow: Narrow, color: string, editMessage: EditMessage | null, |}>; export default function Title(props: Props): Node { const { narrow, color, editMessage } = props; if (editMessage != null) { return <TitlePlain text="Edit message" color={color} />; } return caseNarrow(narrow, { home: () => <TitleSpecial code="home" color={color} />, starred: () => <TitleSpecial code="starred" color={color} />, mentioned: () => <TitleSpecial code="mentioned" color={color} />, allPrivate: () => <TitleSpecial code="private" color={color} />, stream: () => <TitleStream narrow={narrow} color={color} />, topic: () => <TitleStream narrow={narrow} color={color} />, pm: ids => ids.length === 1 ? ( <TitlePrivate userId={ids[0]} color={color} /> ) : ( <TitleGroup recipients={ids} /> ), search: () => null, }); } ```
/content/code_sandbox/src/title/Title.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
332
```javascript /* @flow strict-local */ import React, { useContext } from 'react'; import type { Node } from 'react'; import { Text, View, TouchableWithoutFeedback } from 'react-native'; // $FlowFixMe[untyped-import] import { useActionSheet } from '@expo/react-native-action-sheet'; import { TranslationContext } from '../boot/TranslationProvider'; import type { Narrow } from '../types'; import styles, { createStyleSheet } from '../styles'; import { useSelector, useDispatch } from '../react-redux'; import StreamIcon from '../streams/StreamIcon'; import { isTopicNarrow, streamIdOfNarrow, topicOfNarrow } from '../utils/narrow'; import { getAuth, getFlags, getSubscriptionsById, getStreamsById, getOwnUser, getStreamInNarrow, getSettings, getZulipFeatureLevel, } from '../selectors'; import { getMute, isTopicFollowed } from '../mute/muteModel'; import { showStreamActionSheet, showTopicActionSheet } from '../action-sheets'; import type { ShowActionSheetWithOptions } from '../action-sheets'; import { getUnread } from '../unread/unreadModel'; import { useNavigation } from '../react-navigation'; import { IconFollow } from '../common/Icons'; type Props = $ReadOnly<{| narrow: Narrow, color: string, |}>; const componentStyles = createStyleSheet({ outer: { flex: 1, flexDirection: 'column', alignItems: 'flex-start', justifyContent: 'center', height: '100%', }, streamRow: { flexDirection: 'row', alignItems: 'center', }, topicRow: { flexDirection: 'row', alignItems: 'center', }, followIcon: { paddingLeft: 4, opacity: 0.4, }, }); export default function TitleStream(props: Props): Node { const { narrow, color } = props; const dispatch = useDispatch(); const navigation = useNavigation(); const stream = useSelector(state => getStreamInNarrow(state, narrow)); const backgroundData = useSelector(state => { const ownUser = getOwnUser(state); return { auth: getAuth(state), mute: getMute(state), streams: getStreamsById(state), subscriptions: getSubscriptionsById(state), unread: getUnread(state), ownUser, ownUserRole: ownUser.role, flags: getFlags(state), userSettingStreamNotification: getSettings(state).streamNotification, zulipFeatureLevel: getZulipFeatureLevel(state), }; }); const showActionSheetWithOptions: ShowActionSheetWithOptions = useActionSheet().showActionSheetWithOptions; const _ = useContext(TranslationContext); const isFollowed = useSelector( state => isTopicNarrow(narrow) && isTopicFollowed(streamIdOfNarrow(narrow), topicOfNarrow(narrow), getMute(state)), ); return ( <TouchableWithoutFeedback onLongPress={ isTopicNarrow(narrow) ? () => { showTopicActionSheet({ showActionSheetWithOptions, callbacks: { dispatch, navigation, _ }, backgroundData, streamId: stream.stream_id, topic: topicOfNarrow(narrow), }); } : () => { showStreamActionSheet({ showActionSheetWithOptions, callbacks: { dispatch, navigation, _ }, backgroundData, streamId: stream.stream_id, }); } } > <View style={componentStyles.outer}> <View style={componentStyles.streamRow}> <StreamIcon style={styles.halfMarginRight} isMuted={!stream.in_home_view} isPrivate={stream.invite_only} isWebPublic={stream.is_web_public} color={color} size={styles.navTitle.fontSize} /> <Text style={[styles.navTitle, { flex: 1, color }]} numberOfLines={1} ellipsizeMode="tail" > {stream.name} </Text> </View> {isTopicNarrow(narrow) && ( <View style={componentStyles.topicRow}> <Text style={[styles.navSubtitle, { color }]} numberOfLines={1} ellipsizeMode="tail"> {topicOfNarrow(narrow)} </Text> {isFollowed && ( <IconFollow size={14} color={color} style={componentStyles.followIcon} /> )} </View> )} </View> </TouchableWithoutFeedback> ); } ```
/content/code_sandbox/src/title/TitleStream.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
997
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import { useSelector } from '../react-redux'; import { getOwnUserId } from '../selectors'; import { pmUiRecipientsFromKeyRecipients, type PmKeyRecipients } from '../utils/recipient'; import styles, { createStyleSheet } from '../styles'; import UserAvatarWithPresence from '../common/UserAvatarWithPresence'; import { useNavigation } from '../react-navigation'; type Props = $ReadOnly<{| recipients: PmKeyRecipients, |}>; const componentStyles = createStyleSheet({ titleAvatar: { marginRight: 16, }, }); export default function TitleGroup(props: Props): Node { const { recipients } = props; const ownUserId = useSelector(getOwnUserId); const userIds = pmUiRecipientsFromKeyRecipients(recipients, ownUserId); const navigation = useNavigation(); return ( <View style={styles.navWrapper}> {userIds.map(userId => ( <View key={userId} style={componentStyles.titleAvatar}> <UserAvatarWithPresence onPress={() => { navigation.push('account-details', { userId }); }} size={32} userId={userId} /> </View> ))} </View> ); } ```
/content/code_sandbox/src/title/TitleGroup.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
286
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import ZulipTextIntl from '../common/ZulipTextIntl'; import { Icon } from '../common/Icons'; import styles from '../styles'; const specials = { home: { name: 'Combined feed', icon: 'globe' }, private: { name: 'Direct messages', icon: 'mail' }, starred: { name: 'Starred', icon: 'star' }, mentioned: { name: 'Mentions', icon: 'at-sign' }, }; type Props = $ReadOnly<{| code: 'home' | 'private' | 'starred' | 'mentioned', color: string, |}>; export default function TitleSpecial(props: Props): Node { const { code, color } = props; const { name, icon } = specials[code]; return ( <View style={styles.navWrapper}> <Icon name={icon} size={20} color={color} style={styles.halfPaddingRight} /> <ZulipTextIntl style={[styles.navTitle, { flex: 1, color }]} text={name} /> </View> ); } ```
/content/code_sandbox/src/title/TitleSpecial.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
269
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { Text } from 'react-native'; import styles from '../styles'; type Props = $ReadOnly<{| text: string, color: string, |}>; export default function TitlePlain(props: Props): Node { const { text, color } = props; return <Text style={[styles.navTitle, styles.flexed, { color }]}>{text}</Text>; } ```
/content/code_sandbox/src/title/TitlePlain.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
102
```javascript /* @flow strict-local */ import React from 'react'; import type { Node } from 'react'; import { View } from 'react-native'; import type { UserId } from '../types'; import styles, { createStyleSheet } from '../styles'; import { useSelector } from '../react-redux'; import Touchable from '../common/Touchable'; import ViewPlaceholder from '../common/ViewPlaceholder'; import UserAvatarWithPresence from '../common/UserAvatarWithPresence'; import ActivityText from './ActivityText'; import { getFullNameReactText, tryGetUserForId } from '../users/userSelectors'; import { useNavigation } from '../react-navigation'; import ZulipTextIntl from '../common/ZulipTextIntl'; import { getRealm } from '../directSelectors'; type Props = $ReadOnly<{| userId: UserId, color: string, |}>; const componentStyles = createStyleSheet({ outer: { flex: 1 }, inner: { flexDirection: 'row', alignItems: 'center' }, textWrapper: { flex: 1 }, }); export default function TitlePrivate(props: Props): Node { const { userId, color } = props; const user = useSelector(state => tryGetUserForId(state, userId)); const enableGuestUserIndicator = useSelector(state => getRealm(state).enableGuestUserIndicator); const navigation = useNavigation(); if (!user) { return null; } return ( <Touchable onPress={() => { if (!user) { return; } navigation.push('account-details', { userId: user.user_id }); }} style={componentStyles.outer} > <View style={componentStyles.inner}> <UserAvatarWithPresence size={32} userId={user.user_id} /> <ViewPlaceholder width={8} /> <View style={componentStyles.textWrapper}> <ZulipTextIntl style={[styles.navTitle, { color }]} numberOfLines={1} ellipsizeMode="tail" text={getFullNameReactText({ user, enableGuestUserIndicator })} /> <ActivityText style={[styles.navSubtitle, { color }]} user={user} /> </View> </View> </Touchable> ); } ```
/content/code_sandbox/src/title/TitlePrivate.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
468
```javascript /* @flow strict-local */ import type { Auth } from './apiTypes'; import { isUrlOnRealm } from '../utils/url'; import getFileTemporaryUrl from './messages/getFileTemporaryUrl'; /** * Like getFileTemporaryUrl, but on error returns null instead of throwing. * * Validates `url` to give getFileTemporaryUrl the kind of input it expects * and returns null if validation fails. */ export default async (url: URL, auth: Auth): Promise<URL | null> => { if (!isUrlOnRealm(url, auth.realm)) { return null; } // A "path-absolute-URL string". // // When the unparsed `href` is a relative URL (i.e., one meant for the // realm), we've seen it with and without a leading slash: // path_to_url#narrow/stream/243-mobile-team/topic/Interpreting.20links.20in.20messages/near/1410903 // // With the slash, `href` is a "path-absolute-URL string". Without the // slash, it's a "path-relative-URL string" meant as relative to the root // path /. By using the URL parser with the root path as a base // (auth.realm should point to the root path), we normalize away that // difference: `.pathname` on a URL object gives the path-absolute string // starting with a slash. We also drop any query and fragment that might // have been in `href`. // // Quoted terms come from the URL spec: // path_to_url#url-writing const { pathname } = url; if (!/^\/user_uploads\/[0-9]+\/.+$/.test(pathname)) { return null; } try { return await getFileTemporaryUrl( auth, // This param wants a "'path-absolute-URL string' [] meant for the // realm, of the form `/user_uploads/{realm_id_str}/{filename}". See // above for how we ensure that. pathname, ); } catch { return null; } }; ```
/content/code_sandbox/src/api/tryGetFileTemporaryUrl.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
468
```javascript /** * Functions to interpret some data from the API. * * @flow strict-local */ import invariant from 'invariant'; import type { UpdateMessageEvent } from './eventTypes'; import * as logging from '../utils/logging'; export type MessageMove = $ReadOnly<{| orig_stream_id: number, new_stream_id: number, orig_topic: string, new_topic: string, |}>; /** * Determine if and where this edit moved the message. * * If a move did occur, returns the relevant information in a form with a * consistent naming convention. * * Returns null if the message stayed at the same conversation. */ export function messageMoved(event: UpdateMessageEvent): null | MessageMove { // The API uses "new" for the stream IDs and "orig" for the topics. // Put them both in a consistent naming convention. const orig_stream_id = event.stream_id; if (orig_stream_id == null) { // Not stream messages, or else a pure content edit (no stream/topic change.) // TODO(server-5.0): Simplify comment: since FL 112 this means it's // just not a stream message. return null; } const new_stream_id = event.new_stream_id ?? orig_stream_id; const orig_topic = event.orig_subject; const new_topic = event.subject ?? orig_topic; if (new_topic === orig_topic && new_stream_id === orig_stream_id) { // Stream and topic didn't change. return null; } if (orig_topic == null) { // `orig_subject` is documented to be present when either the // stream or topic changed. logging.warn('Got update_message event with stream/topic change and no orig_subject'); return null; } invariant(new_topic != null, 'new_topic must be non-nullish when orig_topic is, by `??`'); return { orig_stream_id, new_stream_id, orig_topic, new_topic }; } ```
/content/code_sandbox/src/api/misc.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
421
```javascript // @flow strict-local import { type UserId } from './idTypes'; // // Note: No code actually refers to these type definitions! // // The code that consumes this part of the API is in: // src/notification/extract.js // android/app/src/main/java/com/zulipmobile/notifications/FcmMessage.kt // of which the latter is used on Android, and the former on iOS. // // The Android-side code doesn't use these because it's not in JS. // (Moreover the data it receives is slightly different; see that code, or // the server at zerver/lib/push_notifications.py , for details.) // // The JS-side code has a signature taking an arbitrary JSON blob, so that // the type-checker can verify it systematically validates all the pieces it // uses. But these types describe the form of data it *expects* to receive. // This format is as of 2020-02, commit 3.0~3347. type BaseData = {| /** The realm URL, same as in the `/server_settings` response. */ +realm_uri: string, // The server and realm_id are an obsolete substitute for realm_uri. -server: string, // settings.EXTERNAL_HOST -realm_id: number, // server-internal realm identifier /** * The user this notification is addressed to; our self-user. * * (This lets us distinguish different accounts in the same realm.) */ // added 2.1-dev-540-g447a517e6f, release 2.1.0+ // TODO(server-2.1): Mark required; simplify comment. +user_id?: UserId, // The rest of the data is about the Zulip message we're being notified // about. +message_ids: [number], // single-element tuple! +sender_id: UserId, +sender_email: string, // (... And see StreamData and PmData below.) |}; /** For a notification about a stream message. */ type StreamData = {| ...BaseData, +recipient_type: 'stream', /** * The name of the message's stream. */ +stream: string, // TODO(server-5.0): Require stream_id (#3918). +stream_id?: number, +topic: string, |}; /** For a notification about a PM. */ type PmData = {| ...BaseData, +recipient_type: 'private', /** * The recipient user IDs, if this is a group PM; absent for 1:1 PMs. * * The user IDs are comma-separated ASCII decimal. * * (Does it include the self-user? Are they sorted? Unknown.) */ +pm_users?: string, |}; /** An APNs message sent by the Zulip server. */ // Note that no code actually refers to this type! Rather it serves as // documentation. See module comment. export type ApnsPayload = {| /** Our own data. */ +zulip: StreamData | PmData, /** * Various Apple-specified fields. * * Upstream docs here: * path_to_url */ +aps: { ... }, |}; ```
/content/code_sandbox/src/api/notificationTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
710
```javascript /* @flow strict-local */ /** * The code here in src/api is like a self-contained, independent * library that describes the server API. Therefore, it shouldn't * import code from outside src/api. We've made a few exceptions to * this rule -- we sometimes import functions from src/utils for * convenience -- but we're generally pretty consistent about it. */ import fetchServerEmojiData from './fetchServerEmojiData'; import queueMarkAsRead from './queueMarkAsRead'; import checkCompatibility from './checkCompatibility'; import devFetchApiKey from './devFetchApiKey'; import devListUsers from './devListUsers'; import fetchApiKey from './fetchApiKey'; import reportPresence from './reportPresence'; import getTopics from './getTopics'; import toggleMessageStarred from './messages/toggleMessageStarred'; import typing from './typing'; import pollForEvents from './pollForEvents'; import registerForEvents from './registerForEvents'; import uploadFile from './uploadFile'; import emojiReactionAdd from './emoji_reactions/emojiReactionAdd'; import emojiReactionRemove from './emoji_reactions/emojiReactionRemove'; import markAllAsRead from './mark_as_read/markAllAsRead'; import markStreamAsRead from './mark_as_read/markStreamAsRead'; import markTopicAsRead from './mark_as_read/markTopicAsRead'; import deleteMessage from './messages/deleteMessage'; import deleteTopic from './messages/deleteTopic'; import getRawMessageContent from './messages/getRawMessageContent'; import getMessages from './messages/getMessages'; import getSingleMessage from './messages/getSingleMessage'; import getMessageHistory from './messages/getMessageHistory'; import updateMessageFlags from './messages/updateMessageFlags'; import updateMessageFlagsForNarrow from './messages/updateMessageFlagsForNarrow'; import sendMessage from './messages/sendMessage'; import updateMessage from './messages/updateMessage'; import savePushToken from './notifications/savePushToken'; import forgetPushToken from './notifications/forgetPushToken'; import getServerSettings from './settings/getServerSettings'; import toggleMobilePushSettings from './settings/toggleMobilePushSettings'; import createStream from './streams/createStream'; import getStreams from './streams/getStreams'; import updateStream from './streams/updateStream'; import sendSubmessage from './submessages/sendSubmessage'; import getSubscriptions from './subscriptions/getSubscriptions'; import subscriptionAdd from './subscriptions/subscriptionAdd'; import subscriptionRemove from './subscriptions/subscriptionRemove'; import setSubscriptionProperty from './subscriptions/setSubscriptionProperty'; import getSubscriptionToStream from './subscriptions/getSubscriptionToStream'; import setTopicMute from './subscriptions/setTopicMute'; import updateUserTopic from './subscriptions/updateUserTopic'; import tryGetFileTemporaryUrl from './tryGetFileTemporaryUrl'; import getUsers from './users/getUsers'; import createUser from './users/createUser'; import getUserProfile from './users/getUserProfile'; import updateUserSettings from './users/updateUserSettings'; import updateUserStatus from './users/updateUserStatus'; import getFileTemporaryUrl from './messages/getFileTemporaryUrl'; import getReadReceipts from './messages/getReadReceipts'; import sendTestNotification from './notifications/sendTestNotification'; export { fetchServerEmojiData, queueMarkAsRead, checkCompatibility, devFetchApiKey, devListUsers, fetchApiKey, reportPresence, getTopics, toggleMessageStarred, typing, pollForEvents, registerForEvents, uploadFile, emojiReactionAdd, emojiReactionRemove, markAllAsRead, markStreamAsRead, markTopicAsRead, deleteMessage, deleteTopic, getRawMessageContent, getMessages, getSingleMessage, getMessageHistory, updateMessageFlags, updateMessageFlagsForNarrow, sendMessage, updateMessage, savePushToken, forgetPushToken, getServerSettings, toggleMobilePushSettings, createStream, getStreams, updateStream, sendSubmessage, getSubscriptions, setTopicMute, updateUserTopic, subscriptionAdd, subscriptionRemove, setSubscriptionProperty, getSubscriptionToStream, tryGetFileTemporaryUrl, getUsers, createUser, getUserProfile, updateUserSettings, updateUserStatus, getFileTemporaryUrl, getReadReceipts, sendTestNotification, }; ```
/content/code_sandbox/src/api/index.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
894
```javascript /* @flow strict-local */ import userAgent from '../utils/userAgent'; // check with server if current mobile app is compatible with latest backend // compatibility fails only if server responds with 400 (but not with 200 or 404) export default (): Promise<Response> => fetch('path_to_url { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', 'User-Agent': userAgent, }, }); ```
/content/code_sandbox/src/api/checkCompatibility.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
95
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from './transportTypes'; import { apiPost } from './apiFetch'; type TypingOperation = 'start' | 'stop'; /** See path_to_url */ export default (auth: Auth, recipients: string, operation: TypingOperation): Promise<ApiResponse> => apiPost(auth, 'typing', { to: recipients, op: operation, }); ```
/content/code_sandbox/src/api/typing.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
90
```javascript /* @flow strict-local */ import { ExtendableError } from '../utils/logging'; import type { ApiErrorCode, ApiResponseErrorData } from './transportTypes'; import { ZulipVersion } from '../utils/zulipVersion'; /** * Some kind of error from a Zulip API network request. * * This is an abstract class: every instance should be an instance of a * subclass. Rather than construct it directly, use a subclass's * constructor. * * See subclasses: {@link ApiError}, {@link NetworkError}, {@link ServerError}. */ // For why we just say "abstract" in the jsdoc without doing anything static // or dynamic to enforce that, see: // path_to_url#issuecomment-1433918758 export class RequestError extends ExtendableError { /** The HTTP status code in the response, if any. */ +httpStatus: number | void; /** * The JSON-decoded response body. * * In the subclass {@link ApiError}, this is a bit narrower; see there. * * If there was no HTTP response or no body, or the body was not parseable * as JSON, this value is `undefined`. */ +data: mixed; } /** * An error returned by the Zulip server API. * * This always represents a situation where the server said there was a * client-side error in the request, giving a 4xx HTTP status code, and * moreover sent a well-formed Zulip API error blob in the response. * * The error blob's contents are represented as follows: * * `result`: Always 'error', if we have an `ApiError` at all. * * `code`: This object's `.code`. * * `msg`: This object's `.message` (which the type inherits from`Error`). * * All other properties: This object's `.data`. * * See API docs: path_to_url */ export class ApiError extends RequestError { +code: ApiErrorCode; +httpStatus: number; /** * This error's data, if any, beyond the properties common to all errors. * * This consists of the properties in the (JSON-decoded) response other * than `result`, `code`, and `msg`. */ +data: $ReadOnly<{ ... }>; constructor(httpStatus: number, data: $ReadOnly<ApiResponseErrorData>) { // eslint-disable-next-line no-unused-vars const { result, code, msg, ...rest } = data; super(msg); this.data = rest; this.code = code; this.httpStatus = httpStatus; } } /** * A network-level error that prevented even getting an HTTP response. */ export class NetworkError extends RequestError {} /** * Some kind of server-side error in handling the request. * * This should always represent either some kind of operational issue on the * server, or a bug in the server where its responses don't agree with the * documented API. */ export class ServerError extends RequestError { +httpStatus: number; constructor(msg: string, httpStatus: number) { super(msg); this.httpStatus = httpStatus; } } /** * A server error, acknowledged by the server via a 5xx HTTP status code. */ export class Server5xxError extends ServerError { constructor(httpStatus: number) { // This text is looked for by the `ignoreErrors` we pass to `Sentry.init`. // If changing this text, update the pattern there to match it. super(`Network request failed: HTTP status ${httpStatus}`, httpStatus); } } /** * An error where the server's response doesn't match the general Zulip API. * * This means the server's response didn't contain appropriately-shaped JSON * as documented at the page path_to_url . */ export class MalformedResponseError extends ServerError { constructor(httpStatus: number, data: mixed) { super(`Server responded with invalid message; HTTP status ${httpStatus}`, httpStatus); this.data = data; } } /** * An error where the server gave an HTTP status it should never give. * * That is, the HTTP status wasn't one that the docs say the server may * give: path_to_url */ export class UnexpectedHttpStatusError extends ServerError { constructor(httpStatus: number, data: mixed) { super(`Server gave unexpected HTTP status: ${httpStatus}`, httpStatus); this.data = data; } } /** * Return the data on success; otherwise, throw a nice {@link RequestError}. */ // For the spec this is implementing, see: // path_to_url export const interpretApiResponse = (httpStatus: number, data: mixed): mixed => { if (httpStatus >= 200 && httpStatus <= 299) { // Status code says success if (data === undefined) { // but response couldn't be parsed as JSON. Seems like a server bug. throw new MalformedResponseError(httpStatus, data); } // and we got a JSON response, too. So we can return the data. return data; } if (httpStatus >= 500 && httpStatus <= 599) { // Server error. Ignore `data`; it's unlikely to be a well-formed Zulip // API error blob, and its meaning is undefined if it somehow is. throw new Server5xxError(httpStatus); } if (httpStatus >= 400 && httpStatus <= 499) { // Client error. We should have a Zulip API error blob. if (typeof data === 'object' && data !== null) { // For errors `code` should always be present, but there have been // bugs where it was missing; in particular, on rate-limit errors // until Zulip 4.0: path_to_url . // Fall back to `BAD_REQUEST`, the same thing the server uses when // nobody's made it more specific. // TODO(server-4.0): Drop this fallback. const { result, msg, code = 'BAD_REQUEST' } = data; if (result === 'error' && typeof msg === 'string' && typeof code === 'string') { // Hooray, we have a well-formed Zulip API error blob. Use that. throw new ApiError(httpStatus, { ...data, result, msg, code }); } } // No such luck. Seems like a server bug, then. throw new MalformedResponseError(httpStatus, data); } // HTTP status was none of 2xx, 4xx, or 5xx. That's a server bug -- // the API says that shouldn't happen. throw new UnexpectedHttpStatusError(httpStatus, data); }; /** * The Zulip Server version below which we should just refuse to connect. */ // This should lag a bit behind the threshold version for ServerCompatBanner // (kMinSupportedVersion), to give users time to see and act on the banner. export const kMinAllowedServerVersion: ZulipVersion = new ZulipVersion('4.0'); /** * An error we throw in API bindings on finding a server is too old. * * Handling code should: * - refuse to interact with the server except to check if it's been updated * - log out the user * - log to Sentry (so we have a sense of how often this happens) */ export class ServerTooOldError extends ExtendableError { version: ZulipVersion; constructor(version: ZulipVersion) { super(`Unsupported Zulip Server version: ${version.classify().coarse}`); this.version = version; } } ```
/content/code_sandbox/src/api/apiErrors.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,669
```javascript /* @flow strict-local */ import { networkActivityStart, networkActivityStop } from '../utils/networkActivity'; import { MalformedResponseError, NetworkError, Server5xxError, ServerError, UnexpectedHttpStatusError, } from './apiErrors'; import type { ServerEmojiData } from './modelTypes'; import { objectEntries } from '../flowPonyfill'; import userAgent from '../utils/userAgent'; /** * The unprocessed response from the server. * * Documented at `server_emoji_data_url` in * path_to_url * * We make a ServerEmojiData out of this, and return that. */ type ServerEmojiDataRaw = {| +code_to_names: {| +[emoji_code: string]: $ReadOnlyArray<string>, |}, |}; function tryTransform(raw: ServerEmojiDataRaw): ServerEmojiData | void { try { return { code_to_names: new Map(objectEntries(raw.code_to_names)) }; } catch { return undefined; } } /** * Fetch data from server_emoji_data_url, given in the /register response. * * See `server_emoji_data_url` in path_to_url * * Unauthenticated. * * Empirically, as of 2022-08, the HTTP headers are respected on both * platforms, and the caching works. * * Converts to a nicer shape, e.g., using JS Maps instead of objects-as-map. */ // Much of the implementation is similar to apiCall and // interpretApiResponse. But it's tailored to this nontraditional endpoint, // which doesn't conform to the usual Zulip API protocols, such as sending // { code, msg, result } // in a 4xx response. If servers grow more endpoints like this one, it'd // probably be good to refactor. export default async (emojiDataUrl: URL): Promise<ServerEmojiData> => { let response = undefined; networkActivityStart(false); try { response = await fetch(emojiDataUrl, { method: 'get', headers: { 'User-Agent': userAgent } }); } catch (errorIllTyped) { const e: mixed = errorIllTyped; // path_to_url if (e instanceof TypeError) { // This really is how `fetch` is supposed to signal a network error: // path_to_url#ref-for-concept-network-error throw new NetworkError(e.message); } throw e; } finally { networkActivityStop(false); } const httpStatus = response.status; if (httpStatus >= 400 && httpStatus <= 499) { // A client error, supposedly. // // If 404, maybe we had the wrong idea of what URL to request (unlikely, // but would be a client error). Or maybe the server failed to get // provisioned with the JSON file at the promised URL (a server error). // // Don't bother trying to make an ApiError by parsing JSON for `code`, // `msg`, or `result`; this endpoint doesn't give them. throw new ServerError('Could not get server emoji data', httpStatus); } else if (httpStatus >= 500 && httpStatus <= 599) { throw new Server5xxError(httpStatus); } else if (httpStatus <= 199 || (httpStatus >= 300 && httpStatus <= 399) || httpStatus >= 600) { // Seems like a server error; the endpoint doesn't document sending // these statuses. No reason to think parsing JSON would give anything // useful; just say `data` is undefined. throw new UnexpectedHttpStatusError(httpStatus, undefined); } let json = undefined; try { json = (await response.json(): ServerEmojiDataRaw); } catch { throw new MalformedResponseError(httpStatus, undefined); } const transformed = tryTransform(json); if (!transformed) { throw new MalformedResponseError(httpStatus, json); } return transformed; }; ```
/content/code_sandbox/src/api/fetchServerEmojiData.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
862
```javascript /* @flow strict-local */ import { typesEquivalent } from '../generics'; import { objectValues } from '../flowPonyfill'; /** * Organization-level role of a user. * * Described in the server API doc, e.g., at `.role` in `realm_users` at * path_to_url */ export enum Role { Owner = 100, Admin = 200, Moderator = 300, Member = 400, Guest = 600, } /** * This organization's policy for which users can create public streams, or * its policy for which users can create private streams. * * (These policies could be set differently, but their types are the same, * so it's convenient to have just one definition.) * * For the policy for web-public streams, see CreateWebPublicStreamPolicy. */ // eslint-disable-next-line ft-flow/type-id-match export type CreatePublicOrPrivateStreamPolicyT = 1 | 2 | 3 | 4; /** * An enum of all valid values for `CreatePublicOrPrivateStreamPolicyT`. * * See CreatePublicOrPrivateStreamPolicyValues for the list of values. */ // Ideally both the type and enum would have the simple name; but a type // and value sharing a name is one nice TS feature that Flow lacks. // Or we could leapfrog TS and make this a Flow enum: // path_to_url // (TS has its own enums, but they are a mess.) export const CreatePublicOrPrivateStreamPolicy = { MemberOrAbove: (1: 1), AdminOrAbove: (2: 2), FullMemberOrAbove: (3: 3), ModeratorOrAbove: (4: 4), }; // Check that the enum indeed has all and exactly the values of the type. typesEquivalent< CreatePublicOrPrivateStreamPolicyT, $Values<typeof CreatePublicOrPrivateStreamPolicy>, >(); /** * A list of all valid values for `CreatePublicOrPrivateStreamPolicyT`. * * See CreatePublicOrPrivateStreamPolicy for an enum to refer to these by * meaningful names. */ export const CreatePublicOrPrivateStreamPolicyValues: $ReadOnlyArray<CreatePublicOrPrivateStreamPolicyT> = objectValues(CreatePublicOrPrivateStreamPolicy); /** * The policy for which users can create web public streams in this * organization. Ignore if the server hasn't opted into the concept of * web-public streams. */ export enum CreateWebPublicStreamPolicy { AdminOrAbove = 2, ModeratorOrAbove = 4, Nobody = 6, OwnerOnly = 7, } /** * The policy for who in the organization has access to users' actual email */ export enum EmailAddressVisibility { Everyone = 1, Members = 2, Admins = 3, Nobody = 4, Moderators = 5, } ```
/content/code_sandbox/src/api/permissionsTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
613
```javascript /** * Types for events returned by the server. * * See server docs: * path_to_url * path_to_url * * NB this is just a start -- far from complete. * * @flow strict-local */ import type { BoundedDiff, SubsetProperties } from '../generics'; import { keyMirror } from '../utils/keyMirror'; import type { CustomProfileField, Message, UserOrBot, MutedUser, PropagateMode, Stream, UserId, UserMessageFlag, UserPresence, UserStatusUpdate, UserSettings, ClientPresence, UserTopic, } from './modelTypes'; import type { RealmDataForUpdate } from './realmDataTypes'; export const EventTypes = keyMirror({ alert_words: null, attachment: null, custom_profile_fields: null, default_stream_groups: null, default_streams: null, delete_message: null, drafts: null, has_zoom_token: null, heartbeat: null, hotspots: null, invites_changed: null, message: null, muted_topics: null, muted_users: null, // TODO(server-3.0): remove `pointer` event type, which server no longer sends pointer: null, presence: null, reaction: null, realm: null, realm_bot: null, realm_domains: null, realm_emoji: null, realm_export: null, realm_filters: null, realm_linkifiers: null, realm_playgrounds: null, realm_user: null, realm_user_settings_defaults: null, restart: null, stream: null, submessage: null, subscription: null, typing: null, update_display_settings: null, update_global_notifications: null, update_message: null, update_message_flags: null, user_group: null, user_settings: null, user_status: null, user_topic: null, }); export type EventType = $Keys<typeof EventTypes>; type EventCommon = $ReadOnly<{| id: number, |}>; /** A common supertype of all events, known or unknown. */ export type GeneralEvent = $ReadOnly<{ ...EventCommon, type: string, op?: string, // Note this is an inexact object type! There will be more properties. ... }>; export type HeartbeatEvent = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.heartbeat, |}>; /** path_to_url#custom_profile_fields */ export type CustomProfileFieldsEvent = {| ...EventCommon, type: typeof EventTypes.custom_profile_fields, fields: $ReadOnlyArray<CustomProfileField>, |}; export type MessageEvent = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.message, // TODO: This doesn't describe what we get from the server (see, e.g., // avatar_url). Write a type that does; perhaps it can go in // rawModelTypes.js. message: Message, /** See the same-named property on `Message`. */ flags?: $ReadOnlyArray<UserMessageFlag>, /** * When the message was sent by this client (with `queue_id` this queue), * matches `local_id` from send. * * Otherwise absent. */ local_message_id?: number, |}>; export type MutedUsersEvent = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.muted_users, muted_users: $ReadOnlyArray<MutedUser>, |}>; /** A new submessage. See the `Submessage` type for details. */ export type SubmessageEvent = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.submessage, submessage_id: number, message_id: number, sender_id: UserId, msg_type: 'widget', content: string, |}>; /** path_to_url#presence */ export type PresenceEvent = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.presence, email: string, server_timestamp: number, // Clients are asked to compute aggregated presence; the event doesn't // have it. presence: BoundedDiff<UserPresence, {| +aggregated: ClientPresence |}>, |}>; /** * New value for a user's chosen availability and/or text/emoji status * * path_to_url#user_status * * See InitialDataUserStatus for the corresponding initial data. */ export type UserStatusEvent = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.user_status, user_id: UserId, // How the status is updated from the old value. ...UserStatusUpdate, |}>; type StreamListEvent = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.stream, streams: $ReadOnlyArray<Stream>, |}>; type StreamUpdateEventBase<K: $Keys<Stream>> = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.stream, op: 'update', stream_id: number, name: string, property: K, value: Stream[K], |}>; // path_to_url#stream-update export type StreamUpdateEvent = | {| ...StreamUpdateEventBase<'name'> |} | {| ...StreamUpdateEventBase<'description'>, +rendered_description: Stream['rendered_description'], |} // TODO(server-4.0): New in FL 30. | {| ...StreamUpdateEventBase<'date_created'> |} | {| ...StreamUpdateEventBase<'invite_only'>, +history_public_to_subscribers: Stream['history_public_to_subscribers'], // TODO(server-5.0): New in FL 71. +is_web_public?: Stream['is_web_public'], |} | {| ...StreamUpdateEventBase<'rendered_description'> |} | {| ...StreamUpdateEventBase<'is_web_public'> |} // TODO(server-3.0): New in FL 1; expect is_announcement_only from older // servers. | {| ...StreamUpdateEventBase<'stream_post_policy'> |} // Special values are: // * null: default; inherits from org-level setting // * -1: unlimited retention // These special values differ from updateStream's and createStream's params; see // path_to_url#narrow/stream/412-api-documentation/topic/message_retention_days/near/1367895 // TODO(server-3.0): New in FL 17. | {| ...StreamUpdateEventBase<'message_retention_days'> |} | {| ...StreamUpdateEventBase<'history_public_to_subscribers'> |} | {| ...StreamUpdateEventBase<'first_message_id'> |} // TODO(server-3.0): Deprecated at FL 1; expect stream_post_policy from // newer servers. | {| ...StreamUpdateEventBase<'is_announcement_only'> |}; // prettier-ignore export type StreamEvent = | {| ...StreamListEvent, +op: 'create', |} | {| ...StreamListEvent, +op: 'delete', |} | {| ...StreamListEvent, +op: 'occupy', |} | {| ...StreamListEvent, +op: 'vacate', |} | StreamUpdateEvent; export type UpdateMessageFlagsMessageDetails = | {| type: 'stream', mentioned?: true, stream_id: number, topic: string |} | {| type: 'private', mentioned?: true, user_ids: $ReadOnlyArray<UserId> |}; // path_to_url#update_message_flags-add // path_to_url#update_message_flags-remove export type UpdateMessageFlagsEvent = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.update_message_flags, // Servers with feature level 32+ send `op`. Servers will eventually // stop sending `operation`; see #4238. // TODO(server-4.0): Simplify to just `op`. operation?: 'add' | 'remove', op?: 'add' | 'remove', flag: empty, // TODO fill in all: boolean, messages: $ReadOnlyArray<number>, message_details?: {| [string]: UpdateMessageFlagsMessageDetails, |}, |}>; // path_to_url#restart export type RestartEvent = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.restart, server_generation: number, immediate: boolean, // Servers at feature level 59 or above send these // (zulip/zulip@65c400e06). The fields describe the server after the // ugprade; handling an event that includes them is the fastest way // to learn about a server upgrade. // // They have the same shape and meaning as the same-named fields in // the /server_settings and /register responses. // TODO(server-4.0): Mark these as required. zulip_version?: string, zulip_feature_level?: number, |}>; // path_to_url#realm-update // We get events of this shape from the server. But when we dispatch Redux // actions for them, we construct the action so its shape matches the action // we dispatch for RealmUpdateDictEvent events. That way we don't have to // handle two different expressions of "a property has changed". export type RealmUpdateEvent = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.realm, op: 'update', // TODO(flow): `property` and `value` should correspond property: $Keys<RealmDataForUpdate>, value: RealmDataForUpdate[$Keys<RealmDataForUpdate>], extra_data: { +upload_quota?: number, ... }, |}>; // path_to_url#realm-update-dict export type RealmUpdateDictEvent = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.realm, op: 'update_dict', property: 'default', data: $Rest<RealmDataForUpdate, { ... }>, |}>; /** * path_to_url#user_settings-update * * New in Zulip 5.0, FL 89. */ export type UserSettingsUpdateEvent = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.user_settings, op: 'update', // TODO(flow): `property` and `value` should correspond property: $Keys<UserSettings>, value: $Values<UserSettings>, language_name?: string, |}>; /** * path_to_url#update_message * * See also `messageMoved` in `misc.js`. */ // This is current to feature level 132. // NB if this ever gains a feature of moving PMs, `messageMoved` needs updating. export type UpdateMessageEvent = $ReadOnly<{| ...EventCommon, type: typeof EventTypes.update_message, // Before FL 114, can be absent with the same meaning as null. // TODO(server-5.0): Make required. user_id?: UserId | null, // TODO(server-5.0): New in FL 114. On old servers, infer from `user_id`. rendering_only?: boolean, // Any content changes apply to just message_id. message_id: number, // Any stream/topic changes apply to all of message_ids, which is // guaranteed to include message_id. // TODO(server-future): It'd be nice for these to be sorted; NB they may // not be. As of server 5.0-dev-3868-gca17a452f (2022-02), there's no // guarantee of that in the API nor, apparently, in the implementation. message_ids: $ReadOnlyArray<number>, flags: $ReadOnlyArray<UserMessageFlag>, // TODO(server-5.0): Always present as of FL 114; make required. edit_timestamp?: number, stream_name?: string, // As of FL 112, present for all stream-message updates. // TODO(server-5.0): Remove comment but keep optional; absent for PMs. stream_id?: number, new_stream_id?: number, propagate_mode?: PropagateMode, orig_subject?: string, subject?: string, // TODO(server-4.0): Changed in feat. 46 to array-of-objects shape, from $ReadOnlyArray<string> topic_links?: $ReadOnlyArray<{| +text: string, +url: string |}> | $ReadOnlyArray<string>, // TODO(server-3.0): Replaced in feat. 1 by topic_links subject_links?: $ReadOnlyArray<string>, orig_content?: string, orig_rendered_content?: string, prev_rendered_content_version?: number, content?: string, rendered_content?: string, is_me_message?: boolean, |}>; type PersonCommon = | SubsetProperties<UserOrBot, {| +user_id: mixed, +full_name: mixed |}> | SubsetProperties< UserOrBot, {| +user_id: mixed, // -email?: mixed, // deprecated +timezone: mixed, |}, > | SubsetProperties<UserOrBot, {| +user_id: mixed, +bot_owner_id: mixed |}> | SubsetProperties<UserOrBot, {| +user_id: mixed, +role: mixed |}> | SubsetProperties<UserOrBot, {| +user_id: mixed, +is_billing_admin: mixed |}> | SubsetProperties<UserOrBot, {| +user_id: mixed, +delivery_email: mixed |}> | {| +user_id: UserOrBot['user_id'], +custom_profile_field: {| +id: number, +value: string | null, +rendered_value?: string |}, |} | {| +user_id: UserOrBot['user_id'], +new_email: string |}; /** * A realm_user update event, straight from the server. * * Doc: path_to_url#realm_user-update */ // Current to FL 129. export type RealmUserUpdateEventRaw = {| ...EventCommon, +type: typeof EventTypes.realm_user, +op: 'update', +person: | PersonCommon | {| ...SubsetProperties< UserOrBot, {| +user_id: mixed, // TODO: This is documented in the event. If handling, see if // the object at `avatar_url` needs to change to stay in sync. // avatar_version: number, |}, >, +avatar_url: string | null, // These are documented in the event, but they're not documented in // the collections of users and bots in the initial data. Ignore. // avatar_source: string, // avatar_url_medium: string, |}, |}; /** A realm_user update event, after we've processed it at the edge. */ export type RealmUserUpdateEvent = {| ...EventCommon, +type: typeof EventTypes.realm_user, +op: 'update', +person: | PersonCommon | {| ...SubsetProperties< UserOrBot, {| +user_id: mixed, +avatar_url: mixed, // TODO: This is documented in the event. If handling, see if // the object at `avatar_url` needs to change to stay in sync. // avatar_version: number, |}, >, // These are documented in the event, but they're not documented in // the collections of users and bots in the initial data. Ignore. // avatar_source: string, // avatar_url_medium: string, |}, |}; export type UserTopicEvent = {| ...EventCommon, +type: typeof EventTypes.user_topic, // The event comprises the whole new state of the user-topic relationship. ...UserTopic, |}; ```
/content/code_sandbox/src/api/eventTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
3,464
```javascript /* @flow strict-local */ import type { InitialDataRealm } from './initialDataTypes'; /** * Property-value map for data in `update` or `update_dict` realm events. * * Use this as a source where we define the actual types for those events. * * We use our type InitialDataRealm for how the data appears in the * /register response. The properties are named differently between here and * in the /register response (InitialDataRealm has lots of properties that * start with "realm_"). But we expect the values to be typed the same. */ /* prettier-ignore */ // Current to FL 237. export type RealmDataForUpdate = $ReadOnly<{ // // Keep alphabetical by the InitialDataRealm property. So by // realm_allow_edit_history, not by allow_edit_history, etc. // // If there's a property that exists in InitialDataRealm, but we don't use // it and the event doc doesn't mention it, write the InitialDataRealm // property in a code comment in the place where it would go here. // add_custom_emoji_policy: InitialDataRealm['realm_add_custom_emoji_policy'], allow_community_topic_editing: // deprecated InitialDataRealm['realm_allow_community_topic_editing'], allow_edit_history: InitialDataRealm['realm_allow_edit_history'], allow_message_editing: InitialDataRealm['realm_allow_message_editing'], authentication_methods: InitialDataRealm['realm_authentication_methods'], bot_creation_policy: InitialDataRealm['realm_bot_creation_policy'], can_access_all_users_group: InitialDataRealm['realm_can_access_all_users_group'], create_multiuse_invite_group: InitialDataRealm['realm_create_multiuse_invite_group'], create_private_stream_policy: InitialDataRealm['realm_create_private_stream_policy'], create_public_stream_policy: InitialDataRealm['realm_create_public_stream_policy'], create_web_public_stream_policy: InitialDataRealm['realm_create_web_public_stream_policy'], create_stream_policy: // deprecated InitialDataRealm['realm_create_stream_policy'], default_code_block_language: InitialDataRealm['realm_default_code_block_language'], default_language: InitialDataRealm['realm_default_language'], description: InitialDataRealm['realm_description'], digest_emails_enabled: InitialDataRealm['realm_digest_emails_enabled'], digest_weekday: InitialDataRealm['realm_digest_weekday'], disallow_disposable_email_addresses: InitialDataRealm['realm_disallow_disposable_email_addresses'], edit_topic_policy: InitialDataRealm['realm_edit_topic_policy'], email_address_visibility: // removed in feat. 163 InitialDataRealm['realm_email_address_visibility'], email_changes_disabled: InitialDataRealm['realm_email_changes_disabled'], emails_restricted_to_domains: InitialDataRealm['realm_emails_restricted_to_domains'], enable_guest_user_indicator: InitialDataRealm['realm_enable_guest_user_indicator'], enable_read_receipts: InitialDataRealm['realm_enable_read_receipts'], enable_spectator_access: InitialDataRealm['realm_enable_spectator_access'], giphy_rating: InitialDataRealm['realm_giphy_rating'], icon_source: InitialDataRealm['realm_icon_source'], icon_url: InitialDataRealm['realm_icon_url'], inline_image_preview: InitialDataRealm['realm_inline_image_preview'], inline_url_embed_preview: InitialDataRealm['realm_inline_url_embed_preview'], invite_by_admins_only: // deprecated InitialDataRealm['realm_invite_by_admins_only'], invite_required: InitialDataRealm['realm_invite_required'], invite_to_realm_policy: InitialDataRealm['realm_invite_to_realm_policy'], invite_to_stream_policy: InitialDataRealm['realm_invite_to_stream_policy'], jitsi_server_url: InitialDataRealm['realm_jitsi_server_url'], logo_source: InitialDataRealm['realm_logo_source'], logo_url: InitialDataRealm['realm_logo_url'], mandatory_topics: InitialDataRealm['realm_mandatory_topics'], message_content_allowed_in_email_notifications: InitialDataRealm['realm_message_content_allowed_in_email_notifications'], message_content_delete_limit_seconds: InitialDataRealm['realm_message_content_delete_limit_seconds'], message_content_edit_limit_seconds: InitialDataRealm['realm_message_content_edit_limit_seconds'], move_messages_between_streams_policy: InitialDataRealm['realm_move_messages_between_streams_policy'], move_messages_between_streams_limit_seconds: InitialDataRealm['realm_move_messages_between_streams_limit_seconds'], move_messages_within_stream_limit_seconds: InitialDataRealm['realm_move_messages_within_stream_limit_seconds'], name: InitialDataRealm['realm_name'], name_changes_disabled: InitialDataRealm['realm_name_changes_disabled'], night_logo_source: InitialDataRealm['realm_night_logo_source'], night_logo_url: InitialDataRealm['realm_night_logo_url'], notifications_stream_id: InitialDataRealm['realm_notifications_stream_id'], org_type: InitialDataRealm['realm_org_type'], plan_type: InitialDataRealm['realm_plan_type'], presence_disabled: InitialDataRealm['realm_presence_disabled'], private_message_policy: InitialDataRealm['realm_private_message_policy'], push_notifications_enabled: InitialDataRealm['realm_push_notifications_enabled'], push_notifications_enabled_end_timestamp: InitialDataRealm['realm_push_notifications_enabled_end_timestamp'], send_welcome_emails: InitialDataRealm['realm_send_welcome_emails'], signup_notifications_stream_id: InitialDataRealm['realm_signup_notifications_stream_id'], user_group_edit_policy: InitialDataRealm['realm_user_group_edit_policy'], video_chat_provider: InitialDataRealm['realm_video_chat_provider'], waiting_period_threshold: InitialDataRealm['realm_waiting_period_threshold'], want_advertise_in_communities_directory: InitialDataRealm['realm_want_advertise_in_communities_directory'], wildcard_mention_policy: InitialDataRealm['realm_wildcard_mention_policy'], // // Keep alphabetical by the InitialDataRealm property. So by // realm_allow_edit_history, not by allow_edit_history, etc. // ... }>; ```
/content/code_sandbox/src/api/realmDataTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,305
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from './transportTypes'; import type { Topic } from './apiTypes'; import { apiGet } from './apiFetch'; type ApiResponseTopics = {| ...$Exact<ApiResponseSuccess>, topics: $ReadOnlyArray<Topic>, |}; /** See path_to_url */ export default async (auth: Auth, streamId: number): Promise<ApiResponseTopics> => apiGet(auth, `users/me/${streamId}/topics`); ```
/content/code_sandbox/src/api/getTopics.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
104
```javascript /* @flow strict-local */ /** * A user ID. * * This is a number that identifies a particular Zulip user. Different * users on the same Zulip server will have different user IDs. On the * other hand, between different Zulip servers the same user ID may be used * to refer to completely unrelated users. * * In general, if something calls for a value of this type, then you should * be getting it from something that already has this type: like the * `user_id` property of a `User` object, or a data structure that stores * user IDs. * * The only other way to create a `UserId` is to call the `makeUserId` * function provided by this module. * * See also type `User`, for the thing that one of these identifies. */ // How this type works: it's an "opaque type alias" for simply a number. // See Flow docs: path_to_url // // This means that: // * At runtime, a `UserId` value is just a number. The use of `UserId` // involves zero runtime overhead compared with simply `number`. // * Because we've written a "bound" of `: number`, all code that has one // of these values can freely use it as if it were simply `number`. // * On the other hand, the only way to *create* such a value is to invoke // something from this module to do it for you. // // For more background discussion of opaque types, see `PmKeyRecipients`. export opaque type UserId: number = number; /** * Take a number, and declare that it truly is a user ID. * * This does nothing at all at runtime, just returning the value it's * passed. Its only effect is to inform the type-checker that it's OK to * use this value where a user ID is required. * * In general the only legitimate use case for this function, outside of * tests, is when parsing a user ID from a string. When getting a user ID * from any other source, if the values really are user IDs then the type of * that source should be adjusted to say so. */ export const makeUserId = (id: number): UserId => id; /* Possible future work: export opaque type StreamId: number = number; export opaque type MessageId: number = number; export const makeStreamId = (id: number): StreamId => id; export const makeMessageId = (id: number): MessageId => id; */ ```
/content/code_sandbox/src/api/idTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
553
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from './transportTypes'; import { apiPost } from './apiFetch'; type ApiResponseDevFetchApiKey = {| ...$Exact<ApiResponseSuccess>, api_key: string, |}; export default (auth: Auth, email: string): Promise<ApiResponseDevFetchApiKey> => apiPost(auth, 'dev_fetch_api_key', { username: email }); ```
/content/code_sandbox/src/api/devFetchApiKey.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
89
```javascript /* @flow strict-local */ /** * An identity, plus secret, authenticating this user in some Zulip org. * * This consists of all the information the API client library needs in * order to talk to the server on the user's behalf. All API functions * for making (authenticated) requests to the server require this as a * parameter. * * See also `Account` which the app uses to contain this information plus * other metadata. * * Prefer using `Identity` where possible, which identifies the user but * leaves out the secret API key; use `identityOfAuth` to extract one from * an `Auth`. */ export type Auth = $ReadOnly<{| realm: URL, /** The API key, or the empty string if the user has logged out. */ // TODO: Instead of the empty string, use null, to get more helpful // feedback from Flow. We can't express to Flow the type whose values // are all strings except the empty string. When making this change, be // sure to write a migration, and carefully track down all checks // against the empty string and convert them to checks against null. apiKey: string, // TODO: Follow changes in the user's email address, whether while we're // event polling or not. email: string, |}>; /** * The type shared by all Zulip API responses. * * See docs: path_to_url * * For more specific types, see: * * {@link ApiResponseSuccess} * * {@link ApiResponseErrorData} */ export type ApiResponse = $ReadOnly<{ result: string, msg: string, ... }>; /** * The type shared by all non-error Zulip API responses. * * See docs: path_to_url * * See also: * * {@link ApiResponse} * * {@link ApiResponseErrorData} */ export type ApiResponseSuccess = $ReadOnly<{ result: 'success', msg: '', ... }>; /** * An identifier-like string identifying a Zulip API error. * * See API docs on error handling: * path_to_url * * (And at present, 2022-01, those are rather buggy. So see also: * path_to_url#narrow/stream/378-api-design/topic/error.20docs/near/1308989 * ) * * A list of current error codes can be found at: * path_to_url * * Note that most possible values of `code` are not documented in the API, * and may change in future versions. This is especially likely when an * error gives the generic `code: 'BAD_REQUEST'`. When writing logic to * rely on a `code` value, it's best to make sure it gets written into the * API documentation. */ // It's tempting to make ApiErrorCode an enumerated type, but: when // connecting to newer Zulip servers, we may see values of `code` not known // to this version of the client! // // (Note that "newer" here doesn't necessarily mean "newer than this client", // but "newer than the last time someone updated the error code list from the // server". We have no mechanism in place to share the set of error codes -- // and, given the facts above, it's not clear that the existence of such a // mechanism would be helpful anyway.) export type ApiErrorCode = string; /** * Response from the API in case of an error. * * @prop code - A string error code, one of several predefined values. Defaults * to 'BAD_REQUEST'. See {@link ApiErrorCode} for details. * @prop msg - Human-readable error message. May be localized, and so is not * suitable for programmatic use; use 'code' instead. * * This type is not exact: some error responses may contain additional data. */ export type ApiResponseErrorData = $ReadOnly<{ code: ApiErrorCode, msg: string, result: 'error', ... }>; ```
/content/code_sandbox/src/api/transportTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
869
```javascript /* @flow strict-local */ import type { Identity } from '../types'; import type { PmMessage, StreamMessage, Message, MessageEdit, UserId } from './modelTypes'; import { AvatarURL } from '../utils/avatar'; /** * The elements of Message.edit_history found in a fetch-message(s) response. * * Accurate for supported servers before and after FL 118. For convenience, * we drop objects of this type if the FL is <118, so that the modern shape * at Message.edit_history is the only shape we store in Redux; see there. */ // TODO(server-5.0): Simplify this away. export type FetchedMessageEdit = $ReadOnly<{| prev_content?: string, prev_rendered_content?: string, prev_rendered_content_version?: number, prev_stream?: number, prev_topic?: string, // New in FL 118, replacing `prev_subject`. prev_subject?: string, // Replaced in FL 118 by `prev_topic`. stream?: number, // New in FL 118. timestamp: number, topic?: string, // New in FL 118. user_id: UserId | null, |}>; // How `FetchedMessage` relates to `Message`, in a way that applies // uniformly to `Message`'s subtypes. type FetchedMessageOf<M: Message> = $ReadOnly<{| ...$Exact<M>, avatar_url: string | null, // Unlike Message['edit_history'], this can't be `null`. edit_history?: $ReadOnlyArray<FetchedMessageEdit>, |}>; export type FetchedMessage = FetchedMessageOf<PmMessage> | FetchedMessageOf<StreamMessage>; /** * Make a `Message` from `GET /messages` or `GET /message/{message_id}` */ export const transformFetchedMessage = <M: Message>( message: FetchedMessageOf<M>, identity: Identity, zulipFeatureLevel: number, allowEditHistory: boolean, ): M => ({ ...message, avatar_url: AvatarURL.fromUserOrBotData({ rawAvatarUrl: message.avatar_url, email: message.sender_email, userId: message.sender_id, realm: identity.realm, }), // Why condition on allowEditHistory? See MessageBase['edit_history']. // Why FL 118 condition? See MessageEdit type. edit_history: /* eslint-disable operator-linebreak */ allowEditHistory && zulipFeatureLevel >= 118 ? // $FlowIgnore[incompatible-cast] - See MessageEdit type (message.edit_history: $ReadOnlyArray<MessageEdit> | void) : null, }); ```
/content/code_sandbox/src/api/rawModelTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
568
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from './transportTypes'; import { apiPost } from './apiFetch'; type ApiResponseFetchApiKey = {| ...$Exact<ApiResponseSuccess>, email: string, api_key: string, |}; export default (auth: Auth, email: string, password: string): Promise<ApiResponseFetchApiKey> => apiPost(auth, 'fetch_api_key', { username: email, password }); ```
/content/code_sandbox/src/api/fetchApiKey.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
97
```javascript /* @flow strict-local */ /** * The topic servers understand to mean "there is no topic". * * This should match * path_to_url#L940 * or similar logic at the latest `main`. */ // This is hardcoded in the server, and therefore untranslated; that's // zulip/zulip#3639. export const kNoTopicTopic: string = '(no topic)'; /** * The notification bot's email address on a typical production server. * * Helpful for identifying which cross-realm bot is the notification bot, or * knowing if a message was sent by the notification bot. * * Of course, this won't be much use if the server we're dealing with isn't * typical and uses a custom value for the email address. */ // Copied from // path_to_url#L231 . // The web app also makes the assumption that Notification Bot has this email: // path_to_url#L22-L26 // TODO: Make all servers give us a way to identify the notification bot, or // at least the messages it sends. E.g., the mooted "message type" concept: // path_to_url#narrow/stream/378-api-design/topic/message.20type.20field/near/1230581 export const kNotificationBotEmail: string = 'notification-bot@zulip.com'; ```
/content/code_sandbox/src/api/constants.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
290
```javascript /** * Types for things in the Zulip data model, as seen in the API. * * @flow strict-local */ import { typesEquivalent } from '../generics'; import { objectValues } from '../flowPonyfill'; import type { AvatarURL } from '../utils/avatar'; import type { UserId } from './idTypes'; import type { Role } from './permissionsTypes'; export type * from './idTypes'; // // // // =================================================================== // Data attached to the realm or the server. // // /** * See CustomProfileField for semantics. * * See also CustomProfileFieldType for an enum with meaningful names, and * CustomProfileFieldTypeValues for a list of values. */ // This is an enum; see discussion on other enums. // eslint-disable-next-line ft-flow/type-id-match export type CustomProfileFieldTypeT = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; /** * An enum of all valid values for CustomProfileFieldTypeT. * * See CustomProfileFieldTypeValues for a list of values, * and CustomProfileField for semantics. */ export const CustomProfileFieldType = { // The names are from a mix of the descriptions on custom_profile_fields // itself, and the names in custom_profile_field_types: // path_to_url ShortText: (1: 1), LongText: (2: 2), Choice: (3: 3), Date: (4: 4), Link: (5: 5), User: (6: 6), ExternalAccount: (7: 7), Pronouns: (8: 8), }; // Check that the enum indeed has all and only the values of the type. typesEquivalent<CustomProfileFieldTypeT, $Values<typeof CustomProfileFieldType>>(); /** * A list of all valid values for CustomProfileFieldTypeT. * * See CustomProfileFieldType for an enum to refer to these by meaningful * names. */ export const CustomProfileFieldTypeValues: $ReadOnlyArray<CustomProfileFieldTypeT> = objectValues(CustomProfileFieldType); /** * A custom profile field available to users in this org. * * See event doc: path_to_url#custom_profile_fields */ export type CustomProfileField = {| +id: number, +type: CustomProfileFieldTypeT, +order: number, +name: string, +hint: string, /** * Some data in a format determined by the custom profile field's `type`. * * Empirically this is an empty string for field types that don't use it. * * Docs wrongly say it's a "JSON dictionary" for type 3; the example shows * it's a string, one serializing a JSON object. */ +field_data: string, +display_in_profile_summary?: true, |}; export type RealmEmoji = $ReadOnly<{| author?: $ReadOnly<{| email: string, full_name: string, id: number, |}>, deactivated: boolean, id?: number, code: string, name: string, source_url: string, |}>; export type RealmEmojiById = $ReadOnly<{| [id: string]: RealmEmoji, |}>; export type ImageEmoji = {| ...RealmEmoji, +reaction_type: ReactionType, // eslint-disable-line no-use-before-define |}; export type ImageEmojiById = $ReadOnly<{| [id: string]: ImageEmoji, |}>; /** * The server's record of available Unicode emojis, with primary names and * aliases. * * See `server_emoji_data_url` at path_to_url */ export type ServerEmojiData = {| +code_to_names: Map< // `emoji_code` for an available Unicode emoji: a "dash-separated hex // encoding of the sequence of Unicode codepoints that define this emoji // in the Unicode specification." string, // `emoji_name`s for the Unicode emoji. The canonical name appears // first, followed by any aliases. $ReadOnlyArray<string>, >, |}; /** * The only way servers before feature level 54 represent linkifiers. */ // TODO(server-4.0): Delete this. export type RealmFilter = [string, string, number]; /** * The way servers at feature level 54+ can represent linkifiers. * * Currently, this new format can be converted to the old without loss of * information, so we do that at the edge and continue to represent the data * internally with the old format. */ // TODO: // - When we've moved to a shared markdown implementation (#4242), // change our internal representation to be the new // `realm_linkifiers` format. (When doing so, also don't forget to // change various variable and type definition names to be like // `realm_linkifiers`.) // - TODO(server-4.0): When we drop support for servers older than 54, we // can remove all our code that knows about the `realm_filters` format. export type RealmLinkifier = $ReadOnly<{| id: number, pattern: string, url_format: string, |}>; // // // // =================================================================== // Data attached to the current user on the realm. // // /** * The user settings, stored on the server. * * See: * - PATCH /settings doc: path_to_url * - POST /register doc: path_to_url */ // Assumes FL 89+, because servers added user_settings to the /register // response in FL 89. // // Current to FL 152; property ordering follows the /register doc. See the // "Current to" notes in the two places we use this, and update them as // needed: // - InitialDataUserSettings (for POST /register response) // - api.updateUserSettings (for the PATCH /settings endpoint) // // TODO(server-5.0): Remove FL 89+ comment. export type UserSettings = {| +twenty_four_hour_time: boolean, +dense_mode: boolean, +starred_message_counts: boolean, +fluid_layout_width: boolean, +high_contrast_mode: boolean, +color_scheme: 1 | 2 | 3, +translate_emoticons: boolean, // TODO(server-6.0): New in FL 125. +display_emoji_reaction_users?: boolean, +default_language: string, +default_view: 'recent_topics' | 'all_messages', // TODO(server-5.0): New in FL 107. +escape_navigates_to_default_view?: boolean, +left_side_userlist: boolean, +emojiset: 'google' | 'google-blob' | 'twitter' | 'text', +demote_inactive_streams: 1 | 2 | 3, // TODO(server-6.0): New in FL 141. +user_list_style: 1 | 2 | 3, +timezone: string, +enter_sends: boolean, +enable_drafts_synchronization: boolean, +enable_stream_desktop_notifications: boolean, +enable_stream_email_notifications: boolean, +enable_stream_push_notifications: boolean, +enable_stream_audible_notifications: boolean, +notification_sound: string, +enable_desktop_notifications: boolean, +enable_sounds: boolean, +email_notifications_batching_period_seconds: number, +enable_offline_email_notifications: boolean, +enable_offline_push_notifications: boolean, +enable_online_push_notifications: boolean, +enable_digest_emails: boolean, +enable_marketing_emails: boolean, +enable_login_emails: boolean, +message_content_in_email_notifications: boolean, +pm_content_in_desktop_notifications: boolean, +wildcard_mentions_notify: boolean, +desktop_icon_count_display: 1 | 2 | 3, +realm_name_in_notifications: boolean, +presence_enabled: boolean, // TODO(server-5.0): New in FL 105. +send_private_typing_notifications?: boolean, // TODO(server-5.0): New in FL 105. +send_stream_typing_notifications?: boolean, // TODO(server-5.0): New in FL 105. +send_read_receipts?: boolean, |}; // // // // =================================================================== // Users and data about them. // // export type DevUser = $ReadOnly<{| realm_uri: string, email: string, |}>; /** * A Zulip user, which might be a human or a bot, as found in one realm. * * This is a user object as found in properties `realm_users` and * `realm_non_active_users` of a `/register` response. See the API doc: * path_to_url * * See also: * * `CrossRealmBot` for another type of bot user, found in a * different part of a `/register` response * * `UserOrBot` for a convenience union of the two */ export type User = {| // Property ordering follows the doc. // Current to feature level (FL) 121. +user_id: UserId, // Currently `delivery_email` is always `string` if present. A planned // future API may make it sometimes `null`, to explicitly indicate that no // delivery email for this user is visible to us: // path_to_url#narrow/stream/378-api-design/topic/email.20address.20visibility/near/1296132 +delivery_email?: string | null, +email: string, +full_name: string, // We expect ISO 8601; that's in the doc's example response. +date_joined: string, // is_active never appears in `/register` responses, at least up through // FL 121. The doc wrongly says it always appears. See // path_to_url#narrow/stream/412-api-documentation/topic/.60is_active.60.20in.20.60.2Fregister.60.20response/near/1371606 // TODO(server-5.0): New in FL 73 +is_billing_admin?: boolean, // For background on the "*bot*" fields, see user docs on bots: // path_to_url // Note that certain bots are represented by a different type entirely, // namely `CrossRealmBot`. +is_bot: boolean, +bot_type: number | null, // TODO(server-3.0): New in FL 1, replacing bot_owner +bot_owner_id?: number | null, // TODO(server-3.0): Replaced in FL 1 by bot_owner_id +bot_owner?: string, +role: Role, // The ? is for future-proofing. Greg explains in 2020-02, at // path_to_url#discussion_r378554698 , // that both human and bot Users will likely end up having a missing // timezone instead of an empty string. +timezone?: string, /** * Present under EVENT_USER_ADD, RealmUserUpdateEvent (if change * indicated), under REGISTER_COMPLETE, and in `state.users`, all as an * AvatarURL, because we translate into that form at the edge. * * For how it appears at the edge (and how we translate) see * AvatarURL.fromUserOrBotData. */ +avatar_url: AvatarURL, // If we use this, avoid `avatar_url` falling out of sync with it. -avatar_version: number, +profile_data?: {| +[id: string]: {| +value: string, // New in server 2.0, server commit e3aed0f7b. // TODO(server-2.0): Delete the server-2.0 comment, but keep the type // optional; only some custom profile field types support Markdown. +rendered_value?: string, |}, |}, |}; /** * A "cross-realm bot", a bot user shared across the realms on a Zulip server. * * Cross-realm bots are used for a handful of bots defined in the Zulip * server code, like Welcome Bot. They're found in the `cross_realm_bots` * property of a `/register` response, represented with this type. Doc: * path_to_url * * See also: * * `User` and its property `is_bot`. Bot users that appear in a single * realm are, like human users, represented by a `User` value. * * `UserOrBot`, a convenience union */ export type CrossRealmBot = {| // Property ordering follows the doc. // Current to feature level (FL) 121. +user_id: UserId, +delivery_email?: string | null, +email: string, +full_name: string, // We expect ISO 8601; that's in the doc's example response. +date_joined: string, // is_active never appears in `/register` responses, at least up through // FL 121. The doc wrongly says it always appears. See // path_to_url#narrow/stream/412-api-documentation/topic/.60is_active.60.20in.20.60.2Fregister.60.20response/near/1371606 // TODO(server-5.0): New in FL 73 +is_billing_admin?: boolean, // We assume this is `true`. +is_bot: true, // We assume this can't be `null`. +bot_type: number, // We assume this is `null` when present. (Cross-realm bots don't have // owners.) // TODO(server-3.0): New in FL 1, replacing bot_owner +bot_owner_id?: null, // We assume bot_owner is never present, even on old servers. (Cross-realm // bots don't have owners.) // TODO(server-3.0): Replaced in FL 1 by bot_owner_id // +bot_owner?: string, +role: Role, // The ? is for future-proofing. For bots it's always '': // path_to_url#issuecomment-581218576 // so a future version may omit it to reduce payload sizes. See comment // on the same field in User. +timezone?: string, /** * See note for this property on User. */ +avatar_url: AvatarURL, // If we use this, avoid `avatar_url` falling out of sync with it. -avatar_version: number, // (We could be more specific here; but in the interest of reducing // differences between CrossRealmBot and User, just follow the latter.) +profile_data?: User['profile_data'], // We assume this is `true` when present. // TODO(server-5.0): New in FL 83, replacing is_cross_realm_bot +is_system_bot?: true, // We assume this is `true` when present. // TODO(server-5.0): Replaced in FL 83 by is_system_bot +is_cross_realm_bot?: true, |}; /** * A Zulip user/account, which might be a cross-realm bot. */ export type UserOrBot = User | CrossRealmBot; /** * For @-mentioning multiple users at once. * * When you @-mention a user group, everyone in the group is notified as * though they were individually mentioned. See user-facing docs: * path_to_url * * This feature is not related to group PMs. */ export type UserGroup = $ReadOnly<{| description: string, id: number, members: $ReadOnlyArray<UserId>, name: string, |}>; /** * A user's chosen availability and text/emoji statuses. */ export type UserStatus = $ReadOnly<{| // true/false: User unavailable/available. // // Deprecated: "invisible mode", new in FL 148, doesn't involve this: // path_to_url#narrow/stream/2-general/topic/.22unavailable.22.20status/near/1454779 // Don't use it except for servers <148. // TODO(server-6.0): Remove. away: boolean, // "foo": User's status text is "foo". // null: User's status text is unset. status_text: string | null, // null: User's status emoji is unset. status_emoji: null | {| // These three properties point to an emoji in the same way the same-named // properties point to an emoji in the Reaction type; see there. +emoji_name: string, +reaction_type: ReactionType, // eslint-disable-line no-use-before-define +emoji_code: string, |}, |}>; /** * The server's representation of the diff between two user-status records. * * A value is mentioned only when it's changed. * * N.B., emoji statuses are new in 5.0 (feature level 86), so they'll never * be present before then. But "unchanged" is still appropriate semantics * and will lead to correct behavior. * * For the strings, the empty string means that component of the user's * status is unset. */ // TODO(server-5.0): Simplify jsdoc. // TODO(docs): All this is observed empirically; update the doc. See // path_to_url#narrow/stream/412-api-documentation/topic/Emoji.20statuses.20in.20zulip.2Eyaml/near/1322329 export type UserStatusUpdate = $ReadOnly<{| away?: boolean, status_text?: string, // These three properties point to an emoji in the same way the same-named // properties point to an emoji in the Reaction type; see there. emoji_name?: string, emoji_code?: string, reaction_type?: ReactionType | '', // eslint-disable-line no-use-before-define |}>; /** See ClientPresence, and the doc linked there. */ export type PresenceStatus = 'active' | 'idle' | 'offline'; /** * A user's presence status, as reported by a specific client. * * For an explanation of the Zulip presence model and how to interpret * `status` and `timestamp`, see the subsystem doc: * path_to_url * * @prop timestamp - When the server last heard from this client. * @prop status - See the presence subsystem doc. * @prop client * @prop pushable - Legacy; unused. */ export type ClientPresence = $ReadOnly<{| status: PresenceStatus, timestamp: number, client: string, /** * Indicates if the client can receive push notifications. This property * was intended for showing a user's presence status as "on mobile" if * they are inactive on all devices but can receive push notifications * (see zulip/zulip bd20a756f9). However, this property doesn't seem to be * used anywhere on the web app or the mobile client, and can be * considered legacy. * * Empirically this is `boolean` on at least some clients, and absent on * `aggregated`. By writing `empty` we make it an error to actually use it. */ pushable?: empty, |}>; /** * A user's presence status, including all information from all their clients. * * The `aggregated` property equals one of the others. For details, see: * path_to_url * * See also the app's `getAggregatedPresence`, which reimplements a version * of the logic to compute `aggregated`. */ export type UserPresence = $ReadOnly<{| aggregated: ClientPresence, [client: string]: ClientPresence, |}>; /** * A snapshot of the presence status of all users. * * See `UserPresence` and `ClientPresence` for more, and links. */ export type PresenceSnapshot = {| +[email: string]: UserPresence |}; /** This is what appears in the `muted_users` server event. * See path_to_url#muted_users for details. */ export type MutedUser = $ReadOnly<{| id: UserId, timestamp: number, |}>; // // // // =================================================================== // Streams, topics, and stuff about them. // // export type Stream = {| // Based on `streams` in the /register response, current to FL 121: // path_to_url // Property ordering follows that doc. +stream_id: number, +name: string, +description: string, // TODO(server-4.0): New in FL 30. +date_created?: number, // Note: updateStream controls this with its `is_private` param. +invite_only: boolean, +rendered_description: string, // TODO(server-2.1): is_web_public was added in Zulip version 2.1; // absence implies the stream is not web-public. +is_web_public?: boolean, // TODO(server-3.0): Added in FL 1; if absent, use is_announcement_only. +stream_post_policy?: 1 | 2 | 3 | 4, // Special values are: // * null: default; inherits from org-level setting // * -1: unlimited retention // These special values differ from updateStream's and createStream's params; see // path_to_url#narrow/stream/412-api-documentation/topic/message_retention_days/near/1367895 // TODO(server-3.0): New in FL 17. +message_retention_days?: number | null, +history_public_to_subscribers: boolean, +first_message_id: number | null, // TODO(server-3.0): Deprecated at FL 1; use stream_post_policy instead +is_announcement_only: boolean, |}; export type Subscription = {| ...Stream, +color: string, +in_home_view: boolean, +pin_to_top: boolean, +email_address: string, +is_old_stream: boolean, +stream_weekly_traffic: number, /** (To interpret this value, see `getIsNotificationEnabled`.) */ +push_notifications: null | boolean, // To meaningfully interpret these, we'll need logic similar to that for // `push_notifications`. Pending that, the `-` ensures we don't read them. -audible_notifications: boolean, -desktop_notifications: boolean, |}; export type Topic = $ReadOnly<{| name: string, max_id: number, |}>; /** * A user's policy for whether and how to see a particular topic. * * See `visibility_policy` at: path_to_url#user_topic */ export enum UserTopicVisibilityPolicy { None = 0, Muted = 1, Unmuted = 2, // Not in the API docs yet. But it is, uh, in the server implementation: // path_to_url#L2794-L2797 // TODO(server): delete this comment once documented Followed = 3, } /** * A user's relationship to a topic; in particular, muting. * * Found in the initial data at `user_topics`, and in `user_topic` events: * path_to_url#user_topic */ export type UserTopic = {| +stream_id: number, +topic_name: string, +last_updated: number, +visibility_policy: UserTopicVisibilityPolicy, |}; /** * A muted topic. * * Found in the initial data, and in `muted_topics` events. * * The elements are the stream name, then topic, then possibly timestamp. */ // Server issue for using stream IDs (#3918) for muted topics, not names: // path_to_url // TODO(server-3.0): Simplify away the no-timestamp version, new in FL 1. // TODO(server-6.0): Remove, in favor of UserTopic. export type MutedTopicTuple = [string, string] | [string, string, number]; // // // // =================================================================== // Narrows. // // // See docs: path_to_url // prettier-ignore /* eslint-disable semi-style */ export type NarrowElement = | {| +operator: 'is' | 'in' | 'topic' | 'search', +operand: string |} // The server started accepting numeric user IDs and stream IDs in 2.1: // * `stream` since 2.1-dev-2302-g3680393b4 // * `group-pm-with` since 2.1-dev-1813-gb338fd130 // * `sender` since 2.1-dev-1812-gc067c155a // * `pm-with` since 2.1-dev-1350-gd7b4de234 // TODO(server-2.1): Stop sending stream names (#3918) or user emails (#3764) here. | {| +operator: 'stream', +operand: string | number |} // stream ID | {| +operator: 'pm-with', +operand: string | $ReadOnlyArray<UserId> |} | {| +operator: 'sender', +operand: string | UserId |} | {| +operator: 'near' | 'id', +operand: number |} // message ID // ('group-pm-with' was accepted at least through server 6.x, but support // will be dropped: path_to_url ) ; /** * A narrow, in the form used in the Zulip API at get-messages. * * See also `Narrow` in the non-API app code, which describes how we * represent narrows within the app. */ export type ApiNarrow = $ReadOnlyArray<NarrowElement>; // // // // =================================================================== // Messages and things attached to them. // // /** * Type of an emoji reaction to a message. * * These correspond to the values allowed for Reaction.reaction_type in the * server's models. The values are: * * unicode_emoji: An emoji found in Unicode, corresponding to a sequence * of Unicode code points. The list of these depends on the Zulip * server's version. * * realm_emoji: A custom emoji uploaded by some user on a given realm. * * zulip_extra_emoji: An emoji distributed with Zulip, like :zulip:. * * See `Reaction` which uses this. */ export type ReactionType = 'unicode_emoji' | 'realm_emoji' | 'zulip_extra_emoji'; /** * An emoji reaction to a message. * * The raw JSON from the server may have a different structure, but we * normalize it to this form. */ export type Reaction = $ReadOnly<{| user_id: UserId, emoji_name: string, reaction_type: ReactionType, /** * A string that uniquely identifies a particular emoji. * * The format varies with `reaction_type`, and can be subtle. * See the comment on Reaction.emoji_code here: * path_to_url */ emoji_code: string, |}>; /** * "Snapshot" objects from path_to_url . * * See also `MessageEdit`. */ // TODO: Probably not current? Sync with the doc. export type MessageSnapshot = $ReadOnly<{| user_id: UserId, timestamp: number, /** Docs unclear but suggest absent if only content edited. */ topic?: string, /** * Docs unclear, but suggest these five absent if only topic edited. * They definitely say "prev"/"diff" properties absent on the first snapshot. */ content?: string, rendered_content?: string, prev_content?: string, prev_rendered_content?: string, content_html_diff?: string, |}>; /** * Found in the history within a `Message` object, from servers with FL 118+. * * Servers older than 118 send edit-history data in a different shape that's * awkward to work with. In that case we drop the data on the floor, not * storing it in Redux, so we can focus on handling the new, better shape. * * See also `MessageSnapshot`. */ export type MessageEdit = $ReadOnly<{| prev_content?: string, prev_rendered_content?: string, prev_rendered_content_version?: number, prev_stream?: number, prev_topic?: string, stream?: number, timestamp: number, topic?: string, user_id: UserId | null, |}>; /** A user, as seen in the `display_recipient` of a PM `Message`. */ export type PmRecipientUser = $ReadOnly<{| // These five fields (id, email, full_name, short_name, is_mirror_dummy) // have all been present since server commit 6b13f4a3c, in 2014. id: UserId, email: string, full_name: string, // We mark short_name and is_mirror_dummy optional so we can leave them // out of Outbox values; we never rely on them anyway. short_name?: string, is_mirror_dummy?: boolean, |}>; /** * The data encoded in a submessage to make the message a widget. * * Note that future server versions might introduce new types of widgets, so * `widget_type` could be a value not included here. But when it is one of * these values, the rest of the object will follow this type. */ // Ideally we'd be able to express both the known and the unknown widget // types: we'd have another branch of this union which looked like // | {| +widget_type: (string *other than* those above), +extra_data?: { ... } |} // But there doesn't seem to be a way to express that in Flow. export type WidgetData = | {| +widget_type: 'poll', +extra_data?: {| +question?: string, +options?: $ReadOnlyArray<string> |}, |} // We can write these down more specifically when we implement these widgets. | {| +widget_type: 'todo', +extra_data?: { ... } |} | {| +widget_type: 'zform', +extra_data?: { ... } |}; /** * The data encoded in a submessage that acts on a widget. * * The interpretation of this data, including the meaning of the `type` * field, is specific to each widget type. * * We delegate actually processing these to shared code, so we don't specify * the details further. */ export type WidgetEventData = { +type: string, ... }; /** * The data encoded in a `Submessage`. * * For widgets (the only existing use of submessages), the submessages array * consists of: * * One submessage with `WidgetData`; then * * Zero or more submessages with `WidgetEventData`. */ export type SubmessageData = WidgetData | WidgetEventData; /** * Submessages are items containing extra data that can be added to a * message. Despite what their name might suggest, they are not a subtype * of the `Message` type, nor do they share almost any fields with it. * * Submessages are used by Widgets: * path_to_url * * Normally a message contains an empty array of these. We differentiate * between a normal message and a widget by the length of `submessages` * array property. Widgets will have 1 or more submessages. */ export type Submessage = $ReadOnly<{| id: number, message_id: number, sender_id: UserId, msg_type: 'widget', // only this type is currently available /** A `SubmessageData` object, JSON-encoded. */ content: string, |}>; /** * A flag that can be set on a message for a user. * * See: * path_to_url#available-flags */ export type UserMessageFlag = | 'read' | 'starred' | 'collapsed' | 'mentioned' | 'wildcard_mentioned' | 'has_alert_word' | 'historical'; /** * Properties in common among the two different flavors of a * `Message`: `PmMessage` and `StreamMessage`. */ type MessageBase = $ReadOnly<{| // // Properties on `event.message` in `message` events. Order follows the // doc: path_to_url#message // See comment on Message for how up-to-date these are. // /** * Present under EVENT_NEW_MESSAGE and under MESSAGE_FETCH_COMPLETE, * and in `state.messages`, all as an AvatarURL, because we * translate into that form at the edge. * * For how it appears at the edge (and how we translate) see * AvatarURL.fromUserOrBotData. */ avatar_url: AvatarURL, client: string, content: string, content_type: | 'text/html' // message requested with apply_markdown true | 'text/x-markdown', // message requested with apply_markdown false // display_recipient handled on PmMessage and StreamMessage separately /** * A view of the message's edit history, if available. * * This is null if it's coming from a server with FL <118; see comment on * MessageEdit. * * Null if the realm doesn't allow viewing edit history. * * Missing/undefined if the message had no edit history when we added it * to the state. */ // TODO: Keep current: // - Handle changes to the allow_edit_history setting: // - Treat an allow_edit_history change similar to a restart event (in // particular, a restart event where the server version changed, which // could mean any number of subtle changes in server behavior), and do // a re-fetch of server data soon after it. // // TODO(server-5.0): Remove FL <118 condition // // (Why optional and `| void`? We convert missing to undefined at the // edge, but that's incidental and could easily change.) edit_history?: $ReadOnlyArray<MessageEdit> | null | void, id: number, is_me_message: boolean, last_edit_timestamp?: number, reactions: $ReadOnlyArray<Reaction>, /** Deprecated; a server implementation detail not useful in a client. */ // recipient_id: number, sender_email: string, sender_full_name: string, sender_id: UserId, sender_realm_str: string, // Don't use. Likely removed everywhere in FL 26, but the changelog only // mentions GET /messages: path_to_url#changes-in-zulip-31 // TODO(server-3.1): Remove. sender_short_name?: string, // stream_id handled on StreamMessage // subject handled on StreamMessage /** Servers <1.9.0 omit this; when omitted, equivalent to empty array. */ // The doc is wrong to say this is (string)[]; see // path_to_url#narrow/stream/412-api-documentation/topic/.60.2Esubmessages.60.20on.20message.20objects/near/1389473 // TODO(server-1.9): Make required. submessages?: $ReadOnlyArray<Submessage>, timestamp: number, // topic_links handled on StreamMessage // type handled on PmMessage and StreamMessage separately // // Special-case properties; see comments // /** * The `flags` story is a bit complicated: * * Absent in `event.message` for a `message` event... but instead * (confusingly) there is an `event.flags`. * * Present under `EVENT_NEW_MESSAGE`. * * Present under `MESSAGE_FETCH_COMPLETE`, and in the server `/message` * response that action is based on. * * Absent in the Redux `state.messages`; we move the information to a * separate subtree `state.flags`. */ flags?: $ReadOnlyArray<UserMessageFlag>, /** Our own flag; if true, really type `Outbox`. */ isOutbox?: false, /** * These don't appear in `message` events, but they appear in a `/message` * response when a search is involved. */ match_content?: string, match_subject?: string, |}>; export type PmMessage = $ReadOnly<{| ...MessageBase, type: 'private', // Notes from studying the server code: // * Notes are primarily from the server as of 2020-04 at cb85763c7, but // this logic is very stable; confirmed all points about behavior as of // 1.8.0 (from 2018-04), too. // // * This field is ultimately computed (for both events and /messages // results) in MessageDict.hydrate_recipient_info, with most of the // work done earlier, in bulk_fetch_display_recipients in // zerver/lib/display_recipient.py. // // * Ordering of users in the list: // * For 1:1 PMs, sorted by email. (Right in hydrate_recipient_info.) // * For group PMs, sorted by user ID. (In bulk_get_huddle_user_ids, // invoked from bulk_fetch_display_recipients.) // * If we were to write down an API guarantee here, we'd surely make // it sorted by user ID; so, best not to assume current behavior. // /** * The set of all users in the thread. * * This lists the sender as well as all (other) recipients, and it * lists each user just once. In particular the self-user is always * included. * * The ordering is less well specified; if it matters, sort first. */ display_recipient: $ReadOnlyArray<PmRecipientUser>, /** * PMs have (as far as we know) always had the empty string at this * field. Though the doc warns that this might change if Zulip adds * support for topics in PMs; see * path_to_url#narrow/stream/19-documentation/topic/.60subject.60.20on.20messages/near/1125819. */ subject: '', |}>; export type StreamMessage = $ReadOnly<{| ...MessageBase, type: 'stream', /** * The stream name. * * Prefer `stream_id`; see #3918. */ display_recipient: string, stream_id: number, /** * The topic. * * No stream message can be stored (and thus arrive on our doorstep) * with an empty-string subject: * path_to_url#narrow/stream/19-documentation/topic/.60orig_subject.60.20in.20.60update_message.60.20events/near/1112709 * (see point 4). We assume this has always been the case. */ subject: string, // We don't actually use this property. If and when we do, we'll probably // want in our internal model to canonicalize it to the newest form (with // the name topic_links rather than subject_links, and newest type.) // TODO(server-4.0): Changed in feat. 46 to array-of-objects shape, from $ReadOnlyArray<string> // TODO(server-3.0): New in FL 1, replacing subject_links. topic_links?: $ReadOnlyArray<{| +text: string, +url: string |}> | $ReadOnlyArray<string>, // TODO(server-3.0): Replaced in feat. 1 by topic_links subject_links?: $ReadOnlyArray<string>, |}>; /** * A Zulip message. * * This type is mainly intended to represent the data the server sends as * the `message` property of an event of type `message`. Caveat lector: we * pass these around to a lot of places, and do a lot of further munging, so * this type may not quite represent that. Any differences should * definitely be commented, and perhaps refactored. * * Major appearances of this type include * * `message: Message` on a server event of type `message`, and our * `EVENT_NEW_MESSAGE` Redux action for the event; * * `messages: Message[]` in a `/messages` (our `getMessages`) response, * and our resulting `MESSAGE_FETCH_COMPLETE` Redux action; * * `messages: Map<number, Message>` in our global Redux state. * * See also `Outbox`, which is deliberately similar so that we can use * the type `Message | Outbox` in many places. * * See also `MessagesState` for discussion of how we fetch and store message * data. */ // Up-to-date with the `message` event doc to FL 132: // path_to_url#message export type Message = PmMessage | StreamMessage; // // // // =================================================================== // Summaries of messages and conversations. // // /** * Whether and how an edit moving a message applies to others in its conversation. * * See: * path_to_url#update_message * path_to_url#parameter-propagate_mode */ export type PropagateMode = 'change_one' | 'change_later' | 'change_all'; /** * Describes a single recent PM conversation. * * See API documentation under `recent_private_conversations` at: * path_to_url * * Note that `user_ids` does not contain the `user_id` of the current user. * Consequently, a user's conversation with themselves will be listed here * as [], which is unlike the behaviour found in some other parts of the * codebase. */ export type RecentPrivateConversation = $ReadOnly<{| max_message_id: number, // When received from the server, these are guaranteed to be sorted only after // 2.2-dev-53-g405a529340. To be safe, we always sort them on receipt. // TODO(server-3.0): Stop sorting these ourselves. ("2.2" became 3.0.) user_ids: $ReadOnlyArray<UserId>, |}>; ```
/content/code_sandbox/src/api/modelTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
9,290
```javascript /* @flow strict-local */ import type { ApiResponseSuccess, Auth } from './transportTypes'; import type { GeneralEvent } from './eventTypes'; import { apiGet } from './apiFetch'; type ApiResponsePollEvents = {| ...$Exact<ApiResponseSuccess>, events: $ReadOnlyArray<GeneralEvent>, |}; /** See path_to_url */ // TODO: Handle downgrading server across kThresholdVersion, which we'd hear // about in `restart` events, by throwing a ServerTooOldError. This case // seems pretty rare but is possible. export default (auth: Auth, queueId: string, lastEventId: number): Promise<ApiResponsePollEvents> => apiGet( auth, 'events', { queue_id: queueId, last_event_id: lastEventId, }, true, ); ```
/content/code_sandbox/src/api/pollForEvents.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
181
```javascript /* @flow strict-local */ import * as Sentry from '@sentry/react-native'; import type { UrlParams } from '../utils/url'; import type { Auth } from './transportTypes'; import { getAuthHeaders } from './transport'; import { encodeParamsForUrl } from '../utils/url'; import userAgent from '../utils/userAgent'; import { networkActivityStart, networkActivityStop } from '../utils/networkActivity'; import { interpretApiResponse, MalformedResponseError, NetworkError, RequestError, } from './apiErrors'; import { type JSONable } from '../utils/jsonable'; import * as logging from '../utils/logging'; const apiVersion = 'api/v1'; export const getFetchParams = <P: $Diff<$Exact<RequestOptions>, {| headers: mixed |}>>( auth: Auth, params: P, ): RequestOptions => { const { body } = params; const contentType = body instanceof FormData ? 'multipart/form-data' : 'application/x-www-form-urlencoded; charset=utf-8'; return { headers: { 'Content-Type': contentType, 'User-Agent': userAgent, ...getAuthHeaders(auth), }, ...params, }; }; const apiFetch = async ( auth: Auth, route: string, params: $Diff<$Exact<RequestOptions>, {| headers: mixed |}>, ): Promise<Response> => fetch(new URL(`/${apiVersion}/${route}`, auth.realm).toString(), getFetchParams(auth, params)); /** * (Caller beware! Return type has `$FlowFixMe`/`any`. The shape of the * return value is highly specific to the caller.) */ export const apiCall = async ( auth: Auth, route: string, params: $Diff<$Exact<RequestOptions>, {| headers: mixed |}>, isSilent: boolean = false, ): Promise<$FlowFixMe> => { try { networkActivityStart(isSilent); let response: void | Response = undefined; let json: void | JSONable = undefined; try { response = await apiFetch(auth, route, params); json = await response.json().catch(() => undefined); } catch (errorIllTyped) { const error: mixed = errorIllTyped; // path_to_url if (error instanceof TypeError) { // This really is how `fetch` is supposed to signal a network error: // path_to_url#ref-for-concept-network-error throw new NetworkError(error.message); } throw error; } const result = interpretApiResponse(response.status, json); return result; } catch (errorIllTyped) { const error: mixed = errorIllTyped; // path_to_url if (!(error instanceof Error)) { throw new Error('Unexpected non-error thrown in apiCall'); } const { httpStatus, data } = error instanceof RequestError ? error : {}; const response = data !== undefined ? data : '(none, or not valid JSON)'; logging.info({ route, params, httpStatus, response }); Sentry.addBreadcrumb({ category: 'api', level: 'info', data: { route, params, httpStatus, response, errorName: error.name, errorMessage: error.message, }, }); if (error instanceof MalformedResponseError) { logging.warn(`Bad response from server: ${JSON.stringify(data) ?? 'undefined'}`); } throw error; } finally { networkActivityStop(isSilent); } }; export const apiGet = async ( auth: Auth, route: string, params: UrlParams = {}, isSilent: boolean = false, ): Promise<$FlowFixMe> => apiCall( auth, `${route}?${encodeParamsForUrl(params)}`, { method: 'get', }, isSilent, ); export const apiPost = async ( auth: Auth, route: string, params: UrlParams = {}, ): Promise<$FlowFixMe> => apiCall(auth, route, { method: 'post', body: encodeParamsForUrl(params), }); export const apiFile = async (auth: Auth, route: string, body: FormData): Promise<$FlowFixMe> => apiCall(auth, route, { method: 'post', body, }); export const apiPut = async ( auth: Auth, route: string, params: UrlParams = {}, ): Promise<$FlowFixMe> => apiCall(auth, route, { method: 'put', body: encodeParamsForUrl(params), }); export const apiDelete = async ( auth: Auth, route: string, params: UrlParams = {}, ): Promise<$FlowFixMe> => apiCall(auth, route, { method: 'delete', body: encodeParamsForUrl(params), }); export const apiPatch = async ( auth: Auth, route: string, params: UrlParams = {}, ): Promise<$FlowFixMe> => apiCall(auth, route, { method: 'patch', body: encodeParamsForUrl(params), }); export const apiHead = async ( auth: Auth, route: string, params: UrlParams = {}, ): Promise<$FlowFixMe> => apiCall(auth, `${route}?${encodeParamsForUrl(params)}`, { method: 'head', }); ```
/content/code_sandbox/src/api/apiFetch.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,161
```javascript /* @flow strict-local */ export type * from './transportTypes'; export type * from './modelTypes'; export type * from './eventTypes'; export type * from './initialDataTypes'; export type * from './permissionsTypes'; ```
/content/code_sandbox/src/api/apiTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
48
```javascript /* @flow strict-local */ import invariant from 'invariant'; import type { RawInitialData, InitialData } from './initialDataTypes'; import type { Auth } from './transportTypes'; import type { CrossRealmBot, User } from './modelTypes'; import { apiPost } from './apiFetch'; import { AvatarURL } from '../utils/avatar'; import { ZulipVersion } from '../utils/zulipVersion'; import { ServerTooOldError, kMinAllowedServerVersion } from './apiErrors'; const transformUser = (rawUser: {| ...User, avatar_url?: string | null |}, realm: URL): User => { const { avatar_url: rawAvatarUrl, email } = rawUser; return { ...rawUser, avatar_url: AvatarURL.fromUserOrBotData({ rawAvatarUrl, email, userId: rawUser.user_id, realm, }), }; }; const transformCrossRealmBot = ( rawCrossRealmBot: {| ...CrossRealmBot, avatar_url?: string | null |}, realm: URL, ): CrossRealmBot => { const { avatar_url: rawAvatarUrl, user_id: userId, email } = rawCrossRealmBot; return { ...rawCrossRealmBot, avatar_url: AvatarURL.fromUserOrBotData({ rawAvatarUrl, userId, email, realm }), }; }; const transform = (rawInitialData: RawInitialData, auth: Auth): InitialData => { // (Even ancient servers have `zulip_version` in the initial data.) const zulipVersion = new ZulipVersion(rawInitialData.zulip_version); // Do this at the top, before we can accidentally trip on some later code // that's insensitive to ancient servers' behavior. if (!zulipVersion.isAtLeast(kMinAllowedServerVersion)) { throw new ServerTooOldError(zulipVersion); } return { ...rawInitialData, zulip_feature_level: rawInitialData.zulip_feature_level ?? 0, zulip_version: zulipVersion, // Transform the newer `realm_linkifiers` format, if present, to the // older `realm_filters` format. We do the same transformation on // 'realm_linkifiers' events. // TODO(server-4.0): Switch to new format, if we haven't already; // and drop conversion. realm_filters: rawInitialData.realm_linkifiers ? rawInitialData.realm_linkifiers.map(({ pattern, url_format, id }) => [ pattern, url_format, id, ]) : rawInitialData.realm_filters, // In 5.0 (feature level 100), the representation the server sends for "no // limit" changed from 0 to `null`. // // It's convenient to emulate Server 5.0's representation in our own data // structures. To get a correct initial value, it's sufficient to coerce // `0` to null here, without even looking at the server feature level. // That's because, in addition to the documented change in 5.0, there was // another: 0 became an invalid value, which means we don't have to // anticipate servers 5.0+ using it to mean anything, such as "0 seconds": // path_to_url#L1482. // // TODO(server-5.0) Remove this conditional. realm_message_content_delete_limit_seconds: rawInitialData.realm_message_content_delete_limit_seconds === 0 ? null : rawInitialData.realm_message_content_delete_limit_seconds, realm_users: rawInitialData.realm_users.map(rawUser => transformUser(rawUser, auth.realm)), realm_non_active_users: rawInitialData.realm_non_active_users.map(rawNonActiveUser => transformUser(rawNonActiveUser, auth.realm), ), cross_realm_bots: rawInitialData.cross_realm_bots.map(rawCrossRealmBot => transformCrossRealmBot(rawCrossRealmBot, auth.realm), ), // The doc says the field will be removed in a future release. So, while // we're still consuming it, fill it in if missing, with instructions from // the doc: // // > Its value will always equal // > `can_create_public_streams || can_create_private_streams`. // // TODO(server-5.0): Only use `can_create_public_streams` and // `can_create_private_streams`, and simplify this away. can_create_streams: rawInitialData.can_create_streams ?? (() => { const canCreatePublicStreams = rawInitialData.can_create_public_streams; const canCreatePrivateStreams = rawInitialData.can_create_private_streams; invariant( canCreatePublicStreams != null && canCreatePrivateStreams != null, 'these are both present if can_create_streams is missing; see doc', ); return canCreatePublicStreams || canCreatePrivateStreams; })(), }; }; /** See path_to_url */ export default async ( auth: Auth, params?: {| queue_lifespan_secs?: number, |}, ): Promise<InitialData> => { const rawInitialData: RawInitialData = await apiPost(auth, 'register', { ...params, // These parameters affect the types of what we receive from the // server, which means that the types described in these API bindings // assume these are the values we pass. So we fix them here, inside the // API bindings. (If there were a need for these API bindings to be // used in situations with some of these parameters varying, we could // solve that problem, but we haven't yet had a need to.) // // If we ever condition one of these parameters on the server's version // or feature level, take care that either that data is up to date or // it's OK that it isn't. This is where we set up the event queue that // would keep us up to date on that, so it's much easier for it to be // stale here than for most other API endpoints. apply_markdown: true, client_gravatar: true, client_capabilities: JSON.stringify({ notification_settings_null: true, bulk_message_deletion: true, user_avatar_url_field_optional: true, user_settings_object: true, }), include_subscribers: false, fetch_event_types: JSON.stringify([ // Event types not supported by the server are ignored; see // path_to_url#parameter-fetch_event_types. 'alert_words', 'custom_profile_fields', 'message', 'muted_topics', // TODO(server-6.0): Stop requesting, in favor of user_topic 'muted_users', 'presence', 'realm', 'realm_emoji', 'realm_filters', 'realm_linkifiers', 'realm_user', 'realm_user_groups', 'recent_private_conversations', 'stream', 'subscription', // TODO(server-5.0): Remove these two when all supported servers can // handle the `user_settings_object` client capability (FL 89). 'update_display_settings', 'update_global_notifications', 'update_message_flags', 'user_settings', 'user_status', 'user_topic', 'zulip_version', ]), // These parameters can be useful for bots, but the choices encoded in // `fetch_event_types` above aren't designed for such bots. So // flexibility here is unlikely to be useful without flexibility there. // Until/unless we have a use case for such flexibility in these API // bindings, we simplify the interface by leaving them out. // // narrow: , // all_public_streams: , }); return transform(rawInitialData, auth); }; ```
/content/code_sandbox/src/api/registerForEvents.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,699
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from './transportTypes'; import { apiDelete } from './apiFetch'; /** See path_to_url */ export default (auth: Auth, queueId: string): Promise<ApiResponseSuccess> => apiDelete(auth, 'events', { queue_id: queueId, }); ```
/content/code_sandbox/src/api/deleteEventQueue.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
72
```javascript /* @flow strict-local */ import type { Auth } from './transportTypes'; import { base64Utf8Encode } from '../utils/encoding'; export const getAuthHeaders = (auth: Auth): {| Authorization?: string |} => // The `Object.freeze`` in the `:` case avoids a Flow issue: // path_to_url#issuecomment-695064325 auth.apiKey ? { Authorization: `Basic ${base64Utf8Encode(`${auth.email}:${auth.apiKey}`)}` } : Object.freeze({}); ```
/content/code_sandbox/src/api/transport.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
113
```javascript /* @flow strict-local */ import type { Auth } from './transportTypes'; import updateMessageFlags from './messages/updateMessageFlags'; /** We batch up requests to avoid sending them twice in this much time. */ const debouncePeriodMs = 500; const batchSize = 1000; let unsentMessageIds: number[] = []; let lastSentTime = -Infinity; let timeout = null; /** Private; exported only for tests. */ export const resetAll = () => { unsentMessageIds = []; lastSentTime = -Infinity; timeout = null; }; const processQueue = async (auth: Auth) => { if (timeout !== null || unsentMessageIds.length === 0) { return; } const remainingMs = lastSentTime + debouncePeriodMs - Date.now(); if (remainingMs > 0) { timeout = setTimeout(() => { timeout = null; processQueue(auth); }, remainingMs); return; } lastSentTime = Date.now(); const toSend = unsentMessageIds.slice(0, batchSize); await updateMessageFlags(auth, toSend, 'add', 'read'); const sent = new Set(toSend); unsentMessageIds = unsentMessageIds.filter(id => !sent.has(id)); }; export default (auth: Auth, messageIds: $ReadOnlyArray<number>): void => { unsentMessageIds.push(...messageIds); processQueue(auth); }; ```
/content/code_sandbox/src/api/queueMarkAsRead.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
308
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from './transportTypes'; import { apiFile } from './apiFetch'; import { getFileExtension, getMimeTypeFromFileExtension } from '../utils/url'; type ApiResponseUploadFile = {| ...$Exact<ApiResponseSuccess>, uri: string, |}; export default (auth: Auth, uri: string, name: string): Promise<ApiResponseUploadFile> => { const formData = new FormData(); const extension = getFileExtension(name); const type = getMimeTypeFromFileExtension(extension); // $FlowFixMe[incompatible-call] formData.append('file', { uri, name, type, extension }); return apiFile(auth, 'user_uploads', formData); }; ```
/content/code_sandbox/src/api/uploadFile.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
154
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from './transportTypes'; import type { DevUser } from './apiTypes'; import { apiGet } from './apiFetch'; type ApiResponseDevListUsers = {| ...$Exact<ApiResponseSuccess>, direct_admins: $ReadOnlyArray<DevUser>, direct_users: $ReadOnlyArray<DevUser>, |}; export default (auth: Auth): Promise<ApiResponseDevListUsers> => apiGet(auth, 'dev_list_users'); ```
/content/code_sandbox/src/api/devListUsers.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
106
```javascript /* @flow strict-local */ import type { ApiResponseSuccess, Auth } from './transportTypes'; import type { PresenceSnapshot } from './apiTypes'; import { apiPost } from './apiFetch'; type ApiResponseWithPresence = {| ...$Exact<ApiResponseSuccess>, server_timestamp: number, presences: PresenceSnapshot, |}; /** See path_to_url . */ export default ( auth: Auth, isActive: boolean = true, newUserInput: boolean = false, ): Promise<ApiResponseWithPresence> => apiPost(auth, 'users/me/presence', { status: isActive ? 'active' : 'idle', new_user_input: newUserInput, }); ```
/content/code_sandbox/src/api/reportPresence.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
144
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from '../transportTypes'; import type { Stream } from '../apiTypes'; import { apiGet } from '../apiFetch'; type ApiResponseStreams = {| ...$Exact<ApiResponseSuccess>, streams: $ReadOnlyArray<Stream>, |}; /** See path_to_url */ export default async (auth: Auth): Promise<ApiResponseStreams> => apiGet(auth, 'streams'); ```
/content/code_sandbox/src/api/streams/getStreams.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
92
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import type { Stream } from '../modelTypes'; import { apiPatch } from '../apiFetch'; /** * path_to_url * * NB the caller must adapt for old-server compatibility; see comments. */ // Current to FL 121; property ordering follows the doc. export default ( auth: Auth, id: number, params: $ReadOnly<{| // TODO(#4659): Once we pass the feature level to API methods, this one // should encapsulate a switch at FL 64 related to these two parameters. // See call sites. description?: Stream['description'], new_name?: Stream['name'], // controls the invite_only property is_private?: Stream['invite_only'], // TODO(server-5.0): New in FL 98. is_web_public?: Stream['is_web_public'], // TODO(server-3.0): New in FL 1; for older servers, pass is_announcement_only. stream_post_policy?: Stream['stream_post_policy'], // N.B.: Don't pass this without also passing is_web_public; see // path_to_url#narrow/stream/378-api-design/topic/PATCH.20.2Fstreams.2F.7Bstream_id.7D/near/1383984 history_public_to_subscribers?: Stream['history_public_to_subscribers'], // Doesn't take the same special values as Stream.message_retention_days! // path_to_url#narrow/stream/412-api-documentation/topic/message_retention_days/near/1367895 // TODO(server-3.0): New in FL 17 message_retention_days?: | number | 'realm_default' // TODO(server-5.0): Added in FL 91, replacing 'forever'. | 'unlimited' // TODO(server-5.0): Replaced in FL 91 by 'unlimited'. | 'forever', // TODO(server-3.0): Replaced in FL 1 by 'stream_post_policy'. is_announcement_only?: Stream['is_announcement_only'], |}>, ): Promise<ApiResponse> => apiPatch(auth, `streams/${id}`, params); ```
/content/code_sandbox/src/api/streams/updateStream.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
489
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import type { Stream } from '../modelTypes'; import { apiPost } from '../apiFetch'; /** * See path_to_url * * NB the caller must adapt for old-server compatibility; see comments. */ // Current to FL 121. // TODO(#4659): Once we pass the feature level to API methods, this one // should encapsulate various feature-level switches; see comments. export default ( auth: Auth, streamAttributes: $ReadOnly<{| // Ordered by their appearance in the doc. name: Stream['name'], description?: Stream['description'], invite_only?: Stream['invite_only'], // TODO(server-5.0): New in FL 98 is_web_public?: Stream['is_web_public'], history_public_to_subscribers?: Stream['history_public_to_subscribers'], // TODO(server-3.0): New in FL 1; for older servers, pass is_announcement_only. stream_post_policy?: Stream['stream_post_policy'], // Doesn't take the same special values as Stream.message_retention_days! // path_to_url#narrow/stream/412-api-documentation/topic/message_retention_days/near/1367895 // TODO(server-3.0): New in FL 17 message_retention_days?: | number | 'realm_default' // TODO(server-5.0): New in FL 91, replacing 'forever'. | 'unlimited' // TODO(server-5.0): Replaced in FL 91 by 'unlimited'. | 'forever', // TODO(server-3.0): Replaced in FL 1 by 'stream_post_policy'. // Commented out because this isn't actually in the doc. It probably // exists though? Copied from api.updateStream. // is_announcement_only?: Stream['is_announcement_only'], |}>, options?: $ReadOnly<{| // TODO(server-3.0): Send numeric user IDs (#3764), not emails. principals?: $ReadOnlyArray<string>, authorization_errors_fatal?: boolean, announce?: boolean, |}>, ): Promise<ApiResponse> => { const { name, description, ...restAttributes } = streamAttributes; const { principals, ...restOptions } = options ?? {}; return apiPost(auth, 'users/me/subscriptions', { subscriptions: JSON.stringify([{ name, description }]), ...restAttributes, principals: JSON.stringify(principals), ...restOptions, }); }; ```
/content/code_sandbox/src/api/streams/createStream.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
555
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from '../transportTypes'; import { apiGet } from '../apiFetch'; type ApiResponseStreamId = {| ...$Exact<ApiResponseSuccess>, stream_id: number, |}; /** See path_to_url */ export default async (auth: Auth, stream: string): Promise<ApiResponseStreamId> => apiGet(auth, 'get_stream_id', { stream }); ```
/content/code_sandbox/src/api/streams/getStreamId.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
91
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from '../transportTypes'; import type { MessageSnapshot } from '../apiTypes'; import { apiGet } from '../apiFetch'; type ApiResponseMessageHistory = {| ...$Exact<ApiResponseSuccess>, message_history: $ReadOnlyArray<MessageSnapshot>, |}; /** See path_to_url */ export default async (auth: Auth, messageId: number): Promise<ApiResponseMessageHistory> => apiGet(auth, `messages/${messageId}/history`, { message_id: messageId, }); ```
/content/code_sandbox/src/api/messages/getMessageHistory.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
115
```javascript /* @flow strict-local */ import type { CrossRealmBot, CustomProfileField, MutedTopicTuple, MutedUser, PresenceSnapshot, RealmEmojiById, RealmFilter, RealmLinkifier, RecentPrivateConversation, Stream, Subscription, User, UserGroup, UserId, UserSettings, UserStatusUpdate, UserTopic, } from './modelTypes'; import type { CreatePublicOrPrivateStreamPolicyT, CreateWebPublicStreamPolicy, EmailAddressVisibility, } from './permissionsTypes'; import type { ZulipVersion } from '../utils/zulipVersion'; import type { JSONableDict } from '../utils/jsonable'; /* The types in this file are organized by which `fetch_event_types` values cause the server to send them to us. See comments at `InitialData`, at the bottom, for details. */ export type RawInitialDataBase = $ReadOnly<{| last_event_id: number, msg: string, queue_id: string, // The feature level and server version, below, are included // unconditionally as of 3.0 (zulip/zulip@2c6313019), which is why we put // them in `InitialDataBase`. To get them from servers older than that, we // have to pass `zulip_version` in `fetch_event_types`, which we do. // // TODO(server-3.0): We can stop passing `zulip_version` in // `fetch_event_types` and remove this comment. /** * Added in server version 3.0, feature level 1. * Same meaning as in the server_settings response: * path_to_url See also the comment above. */ // TODO(server-3.0): Mark as required; remove missing-to-zero transform zulip_feature_level?: number, /** * Should be present as far back as 1.6.0 (zulip/zulip@d9b10727f). Same * meaning as in the server_settings response: * path_to_url See also the comment above * `zulip_feature_level`, above. */ zulip_version: string, |}>; /** * The parts of the `/register` response sent regardless of `fetch_event_types`. * * Post-transformation. For what we expect directly from the server, see * RawInitialDataBase. * * See `InitialData` for more discussion. */ export type InitialDataBase = $ReadOnly<{| ...RawInitialDataBase, zulip_feature_level: number, // filled in with zero if missing zulip_version: ZulipVersion, // parsed from string |}>; export type InitialDataAlertWords = $ReadOnly<{| alert_words: $ReadOnlyArray<string>, |}>; export type InitialDataCustomProfileFields = {| +custom_profile_fields: $ReadOnlyArray<CustomProfileField>, // +custom_profile_field_types: mixed, // Only used in admin settings UI |}; export type InitialDataMessage = $ReadOnly<{| max_message_id: number, |}>; export type InitialDataMutedTopics = $ReadOnly<{| /** Omitted by new servers that send `user_topics`; read that instead. */ // TODO(server-6.0): Remove; gone in FL 134 (given that we request `user_topic`). muted_topics?: $ReadOnlyArray<MutedTopicTuple>, |}>; export type InitialDataMutedUsers = $ReadOnly<{| /** (When absent, treat as empty. Added in server version 4.0, feature level 48.) */ muted_users?: $ReadOnlyArray<MutedUser>, |}>; export type InitialDataPresence = $ReadOnly<{| presences: PresenceSnapshot, |}>; export type AvailableVideoChatProviders = $ReadOnly<{| [providerName: string]: $ReadOnly<{| name: string, id: number |}>, |}>; // This is current to feature level 237. export type InitialDataRealm = $ReadOnly<{| // // Keep alphabetical order. When changing this, also change our type for // `realm op: update` and `realm op: update_dict` events. // development_environment: boolean, // TODO(server-5.0): Added, at feat. 74. event_queue_longpoll_timeout_seconds?: number, jitsi_server_url?: string, // deprecated max_avatar_file_size_mib: number, max_file_upload_size_mib: number, // TODO(server-5.0): Replaced in feat. 72 by max_icon_file_size_mib max_icon_file_size?: number, // TODO(server-5.0): Added in feat. 72, replacing max_icon_file_size max_icon_file_size_mib?: number, // TODO(server-5.0): Replaced in feat. 72 by max_logo_file_size_mib max_logo_file_size?: number, // TODO(server-5.0): Added in feat. 72, replacing max_logo_file_size max_logo_file_size_mib?: number, // TODO(server-4.0): Added in feat. 53 max_message_length?: number, // TODO(server-4.0): Added in feat. 53 max_stream_description_length?: number, // TODO(server-4.0): Added in feat. 53 max_stream_name_length?: number, // TODO(server-4.0): Added in feat. 53 max_topic_length?: number, password_min_length: number, password_min_guesses: number, // TODO(server-5.0): Added in feat. 85, replacing realm_add_emoji_by_admins_only realm_add_custom_emoji_policy?: number, // TODO(server-5.0): Replaced in feat. 85 by realm_add_custom_emoji_policy realm_add_emoji_by_admins_only?: boolean, // TODO(server-5.0): Replaced in feat. 75 by realm_edit_topic_policy realm_allow_community_topic_editing?: boolean, realm_allow_edit_history: boolean, // TODO(server-5.0): Replaced in feat. 101 by realm_delete_own_message_policy realm_allow_message_deleting?: boolean, realm_allow_message_editing: boolean, realm_authentication_methods: $ReadOnly<{ GitHub: true, Email: true, Google: true, ... }>, realm_available_video_chat_providers: AvailableVideoChatProviders, realm_avatar_changes_disabled: boolean, realm_bot_creation_policy: number, realm_bot_domain: string, // TODO(server-8.0): Added in feat. 225 realm_can_access_all_users_group?: boolean, // TODO(server-8.0): Added in feat. 209 realm_create_multiuse_invite_group?: number, // TODO(server-5.0): Added in feat. 102, replacing // realm_create_stream_policy for private streams realm_create_private_stream_policy?: CreatePublicOrPrivateStreamPolicyT, // TODO(server-5.0): Added in feat. 102, replacing // realm_create_stream_policy for public streams realm_create_public_stream_policy?: CreatePublicOrPrivateStreamPolicyT, // TODO(server-5.0): Replaced in feat. 102 by // realm_create_private_stream_policy and realm_create_public_stream_policy // TODO(?): Do we support any servers released before this was added? (No // entry in API doc or changelog.) realm_create_stream_policy?: CreatePublicOrPrivateStreamPolicyT, // TODO(server-5.0): Added in feat. 103; when absent, treat as // CreateWebPublicStreamPolicy.Nobody. realm_create_web_public_stream_policy?: CreateWebPublicStreamPolicy, // TODO(server-8.0): In feat. 195+, just `string`, not `string | null`. realm_default_code_block_language: string | null, // TODO(server-2.1): Added in commit 2.1.0-rc1~1382. realm_default_external_accounts?: {| +[site_name: string]: {| +name: string, +text: string, +hint: string, +url_pattern: string, |}, |}, realm_default_language: string, // TODO(server-5.0): Replaced in feat. 99 by // realm_user_settings_defaults.twenty_four_hour_time; there, only present // if realm_user_settings_defaults is given in fetch_event_types realm_default_twenty_four_hour_time?: boolean, // TODO(server-5.0): Added in feat. 101, replacing realm_allow_message_deleting realm_delete_own_message_policy?: number, realm_description: string, realm_digest_emails_enabled: boolean, realm_digest_weekday: number, realm_disallow_disposable_email_addresses: boolean, // TODO(server-5.0): Added in feat. 75, replacing realm_allow_community_topic_editing realm_edit_topic_policy?: number, // TODO(server-7.0): Removed in feat. 163 realm_email_address_visibility?: EmailAddressVisibility, realm_email_auth_enabled: boolean, realm_email_changes_disabled: boolean, realm_emails_restricted_to_domains: boolean, // TODO(server-8.0): Added in feat. 216 realm_enable_guest_user_indicator?: boolean, // TODO(server-6.0): Added in feat. 137; if absent, treat as false. realm_enable_read_receipts?: boolean, // TODO(server-5.0): Added in feat. 109; if absent, treat as false. realm_enable_spectator_access?: boolean, // TODO(server-4.0): Added in feat. 55. realm_giphy_rating?: number, realm_icon_source: 'G' | 'U', realm_icon_url: string, realm_inline_image_preview: boolean, realm_inline_url_embed_preview: boolean, // TODO(server-4.0): Replaced in feat. 50 by realm_invite_to_realm_policy realm_invite_by_admins_only?: boolean, realm_invite_required: boolean, // TODO(server-4.0): Added in feat. 50, replacing realm_invite_by_admins_only realm_invite_to_realm_policy?: number, realm_invite_to_stream_policy: number, realm_is_zephyr_mirror_realm: boolean, // TODO(server-8.0): Added in feat. 212 realm_jitsi_server_url?: string | null, realm_logo_source: 'D' | 'U', realm_logo_url: string, realm_mandatory_topics: boolean, realm_message_content_allowed_in_email_notifications: boolean, // In 5.0 (feature level 100), the representation the server sends for "no // limit" changed from 0 to `null`, and 0 became an invalid value. (For // the invalid-value part, see zulip/zulip#20131.) realm_message_content_delete_limit_seconds: number | null, // In 6.0 (feature level 138), the representation the server sends for "no // limit" changed from 0 to `null`, and 0 became an invalid value. realm_message_content_edit_limit_seconds: number, // TODO(server-3.0): Special value `null` replaced with -1 in feat. 22 realm_message_retention_days: number | null, // TODO(server-4.0): Added in feat. 56 realm_move_messages_between_streams_policy?: number, // TODO(server-7.0): Added in feat. 162 realm_move_messages_between_streams_limit_seconds?: number | null, // TODO(server-7.0): Added in feat. 162 realm_move_messages_within_stream_limit_seconds?: number | null, realm_name: string, realm_name_changes_disabled: boolean, realm_night_logo_source: 'D' | 'U', realm_night_logo_url: string, realm_notifications_stream_id: number, // TODO(server-6.0): Added in feat. 128 realm_org_type?: 0 | 10 | 20 | 30 | 35 | 40 | 50 | 60 | 70 | 80 | 90 | 1000, realm_password_auth_enabled: boolean, realm_plan_type: number, realm_presence_disabled: boolean, realm_private_message_policy: number, realm_push_notifications_enabled: boolean, // TODO(server-8.0): Added in feat. 231 realm_push_notifications_enabled_end_timestamp?: number | null, realm_send_welcome_emails: boolean, realm_signup_notifications_stream_id: number, // TODO(server-5.0): Replaced in feat. 72 by realm_upload_quota_mib realm_upload_quota?: number, // TODO(server-5.0): Added in feat. 72, replacing realm_upload_quota realm_upload_quota_mib?: number, realm_user_group_edit_policy: number, realm_uri: string, realm_video_chat_provider: number, realm_waiting_period_threshold: number, // TODO(server-6.0): Added in feat. 129 realm_want_advertise_in_communities_directory?: boolean, // TODO(server-4.0): Added in feat. 33. Updated with moderators option in // feat. 62 (Zulip 4.0). // TODO(server-6.0): Stream administrators option removed in feat. 133. realm_wildcard_mention_policy?: number, server_avatar_changes_disabled: boolean, // TODO(server-6.0): Added in feat. 140. server_emoji_data_url?: string, server_generation: number, server_inline_image_preview: boolean, server_inline_url_embed_preview: boolean, // TODO(server-8.0): Added in feat. 212 server_jitsi_server_url?: string | null, server_name_changes_disabled: boolean, // TODO(server-5.0): Added in feat. 74 server_needs_upgrade?: boolean, // Use 140 when absent. // TODO(server-7.0): Added in feat. 164. (Remove comment about using 140.) server_presence_offline_threshold_seconds?: number, // Use 60 when absent. // TODO(server-7.0): Added in feat. 164. (Remove comment about using 60.) server_presence_ping_interval_seconds?: number, // TODO(server-8.0): Added in feat. 221 server_supported_permission_settings?: JSONableDict, // unstable // TODO(server-8.0): Added in feat. 204 server_typing_started_expiry_period_milliseconds?: number, // TODO(server-8.0): Added in feat. 204 server_typing_started_wait_period_milliseconds?: number, // TODO(server-8.0): Added in feat. 204 server_typing_stopped_wait_period_milliseconds?: number, // TODO(server-5.0): Added in feat. 110; if absent, treat as false. server_web_public_streams_enabled?: boolean, settings_send_digest_emails: boolean, upgrade_text_for_wide_organization_logo: string, zulip_plan_is_not_limited: boolean, // // Keep alphabetical order. When changing this, also change our type for // `realm op: update` and `realm op: update_dict` events. // |}>; export type InitialDataRealmEmoji = $ReadOnly<{| realm_emoji: RealmEmojiById, |}>; export type RawInitialDataRealmFilters = $ReadOnly<{| // We still request this, since not all servers can provide the // newer `realm_linkifiers` format. // TODO(server-4.0): Drop this. realm_filters?: $ReadOnlyArray<RealmFilter>, |}>; /** * The realm_filters/realm_linkifiers data, post-transformation. * * If we got the newer `realm_linkifiers` format, this is the result of * transforming that into the older `realm_filters` format. Otherwise, it's * just what we received in the `realm_filters` format. So, named after * realm_filters. * * See notes on `RealmFilter` and `RealmLinkifier`. */ export type InitialDataRealmFilters = $ReadOnly<{| realm_filters: $ReadOnlyArray<RealmFilter>, |}>; export type InitialDataRealmLinkifiers = $ReadOnly<{| // Possibly absent: Not all servers can provide this. See // `InitialDataRealmFilters`. realm_linkifiers?: $ReadOnlyArray<RealmLinkifier>, |}>; export type RawInitialDataRealmUser = {| // Property ordering follows the doc. +realm_users: $ReadOnlyArray<{| ...User, avatar_url?: string | null |}>, +realm_non_active_users: $ReadOnlyArray<{| ...User, avatar_url?: string | null |}>, +avatar_source: 'G', +avatar_url_medium: string, +avatar_url: string | null, // TODO(server-5.0): Replaced in FL 102 by can_create_public_streams and // can_create_private_streams. +can_create_streams?: boolean, // TODO(server-5.0): New in FL 102, replacing can_create_streams. +can_create_public_streams?: boolean, // TODO(server-5.0): New in FL 102, replacing can_create_streams. +can_create_private_streams?: boolean, // TODO(server-5.0): New in FL 103. +can_create_web_public_streams?: boolean, +can_subscribe_other_users: boolean, // TODO(server-4.0): New in FL 51. +can_invite_others_to_realm?: boolean, +is_admin: boolean, +is_owner: boolean, // TODO(server-5.0): New in FL 73. +is_billing_admin?: boolean, // TODO(server-4.0): New in FL 60. +is_moderator?: boolean, +is_guest: boolean, +user_id: UserId, +email: string, +delivery_email: string, +full_name: string, +cross_realm_bots: $ReadOnlyArray<{| ...CrossRealmBot, +avatar_url?: string | null |}>, |}; // TODO(#5250): Sync with the doc. export type InitialDataRealmUser = $ReadOnly<{| ...RawInitialDataRealmUser, realm_users: $ReadOnlyArray<User>, realm_non_active_users: $ReadOnlyArray<User>, can_create_streams: boolean, cross_realm_bots: $ReadOnlyArray<CrossRealmBot>, |}>; export type InitialDataRealmUserGroups = $ReadOnly<{| realm_user_groups: $ReadOnlyArray<UserGroup>, |}>; export type InitialDataRecentPmConversations = $ReadOnly<{| // * Added in server commit 2.1-dev-384-g4c3c669b41. // TODO(server-2.1): Mark this required. See MIN_RECENTPMS_SERVER_VERSION. // * `user_id` fields are sorted as of commit 2.2-dev-53-g405a529340, which // was backported to 2.1.1-50-gd452ad31e0 -- meaning that they are _not_ // sorted in either v2.1.0 or v2.1.1. // TODO(server-3.0): Simply say these are sorted. ("2.2" became 3.0.) recent_private_conversations?: $ReadOnlyArray<RecentPrivateConversation>, |}>; type NeverSubscribedStream = $ReadOnly<{| description: string, invite_only: boolean, is_old_stream: boolean, name: string, stream_id: number, |}>; export type InitialDataStream = $ReadOnly<{| streams: $ReadOnlyArray<Stream>, |}>; export type InitialDataSubscription = $ReadOnly<{| never_subscribed: $ReadOnlyArray<NeverSubscribedStream>, /** * All servers, at least as far back as zulip/zulip@7a930af, in * 2017-02-20 (that's server 1.6.0), send this, as long as you've * specified `subscription` as a desired event type in the * `/register` call, which we do. * * This investigation is reported at * path_to_url#discussion_r414901766. */ subscriptions: $ReadOnlyArray<Subscription>, unsubscribed: $ReadOnlyArray<Subscription>, |}>; // Deprecated. Use only as fallback for InitialDataUserSettings, new in 5.0. // // All properties optional. They will be present from servers that don't // support the user_settings_object client capability, and absent from those // that do. (We declare the capability.) See doc on each property: // path_to_url // > Present if `update_display_settings` is present in `fetch_event_types` // > and only for clients that did not include `user_settings_object` in // > their `client_capabilities` when registering the event queue. // and see // path_to_url#parameter-client_capabilities . // TODO(server-5.0): Remove, when all supported servers can handle the // `user_settings_object` client capability (FL 89). export type InitialDataUpdateDisplaySettings = {| // Write-only properties commented out to handle a suspected Flow bug: // path_to_url#discussion_r871938749 // // -default_language?: string, // -emojiset?: string, // -emojiset_choices?: $ReadOnly<{| [string]: string |}>, // -enter_sends?: boolean, // -high_contrast_mode?: boolean, // -left_side_userlist?: boolean, // -timezone?: string, // -translate_emoticons?: boolean, +twenty_four_hour_time?: boolean, |}; // Deprecated. Use only as fallback for InitialDataUserSettings, new in 5.0. // // All properties optional. They will be present from servers that don't // support the user_settings_object client capability, and absent from those // that do. (We declare the capability.) See doc on each property: // path_to_url // > Present if `update_global_notifications` is present in `fetch_event_types` // > and only for clients that did not include `user_settings_object` in // > their `client_capabilities` when registering the event queue. // and see // path_to_url#parameter-client_capabilities . // TODO(server-5.0): Remove, when all supported servers can handle the // `user_settings_object` client capability (FL 89). export type InitialDataUpdateGlobalNotifications = {| // Write-only properties commented out to handle a suspected Flow bug: // path_to_url#discussion_r871938749 // // -enable_desktop_notifications?: boolean, // -enable_digest_emails?: boolean, // -enable_offline_email_notifications?: boolean, +enable_offline_push_notifications?: boolean, +enable_online_push_notifications?: boolean, // -enable_sounds?: boolean, // -enable_stream_desktop_notifications?: boolean, // -enable_stream_email_notifications?: boolean, +enable_stream_push_notifications?: boolean, // -message_content_in_email_notifications?: boolean, // -pm_content_in_desktop_notifications?: boolean, // -realm_name_in_notifications?: boolean, |}; export type StreamUnreadItem = $ReadOnly<{| stream_id: number, topic: string, // Sorted. unread_message_ids: $ReadOnlyArray<number>, /** All distinct senders of these messages; sorted. */ // sender_ids: $ReadOnlyArray<UserId>, |}>; export type HuddlesUnreadItem = $ReadOnly<{| /** All users, including self; numerically sorted, comma-separated. */ user_ids_string: string, // Sorted. unread_message_ids: $ReadOnlyArray<number>, |}>; /** The unreads in a 1:1 PM thread, as represented in `unread_msgs`. */ export type PmsUnreadItem = $ReadOnly<{| /** * Misnamed; really the *other* user, or self for a self-PM. * * This is almost always the same as the message's sender. The case where * it isn't is where a (1:1) message you yourself sent is nevertheless * unread. That case can happen if you send it through the API (though * the normal thing even then would be to make a bot user to send the * messages as.) See server commit ca74cd6e3. */ sender_id: UserId, // Sorted. unread_message_ids: $ReadOnlyArray<number>, |}>; /** Initial data for `update_message_flags` events. */ export type InitialDataUpdateMessageFlags = $ReadOnly<{| /** * A summary of (almost) all unread messages, even those we don't have. * * This data structure contains a variety of sets of message IDs, all of * them unread messages: it has (almost) all unread messages' IDs, broken * out by conversation (stream + topic, or PM thread), plus unread * @-mentions. * * The valuable thing this gives us is that, at `/register` time, the * server looks deep into the user's message history to give us this data * on far more messages, if applicable, than we'd want to actually fetch * up front in full. (Thanks to the handy PostgreSQL feature of "partial * indexes", it can have the database answer this question quite * efficiently.) * * The "almost" caveat is that there is an upper bound on this summary. * But it's giant -- starting with server commit 1.9.0-rc1~206, the * latest 50000 unread messages are included. * * This whole feature was new in Zulip 1.7.0. */ // This is computed by `aggregate_unread_data` and its helper // `aggregate_message_dict`, consuming data supplied by // `get_raw_unread_data`, all found in `zerver/lib/message.py`. unread_msgs: $ReadOnly<{| /** * Unread stream messages. * * NB this includes messages to muted streams and topics. */ streams: $ReadOnlyArray<StreamUnreadItem>, /** Unread group PM messages, i.e. with >=3 participants. */ // "huddle" is the server's internal term for a group PM conversation. huddles: $ReadOnlyArray<HuddlesUnreadItem>, /** Unread 1:1 PM messages. */ pms: $ReadOnlyArray<PmsUnreadItem>, /** Unread @-mentions. */ // Unlike other lists of message IDs here, `mentions` is *not* sorted. mentions: $ReadOnlyArray<number>, /** * Total *unmuted* unreads. * * NB this may be much less than the total number of message IDs in the * `streams`, `huddles`, and `pms` fields, because it excludes stream * messages that are muted. */ count: number, |}>, |}>; /** * Initial data for `user_settings` events. * * Replaces various toplevel properties in the register response; see #4933. */ // Assumes FL 89+ because this was added in FL 89. // // Current to FL 152. See the "Current to" note on the UserSettings type and // update that as needed too. // // TODO(server-5.0): Remove FL 89+ comment. export type InitialDataUserSettings = {| // TODO(server-5.0): New in FL 89, for requesting clients, so assumes 89. +user_settings?: {| ...UserSettings, // These appear here even though they aren't really user settings at // all. We're hoping to drop them from here because of that: // path_to_url#narrow/stream/378-api-design/topic/User.20settings.20discrepancies/near/1456533 +available_notification_sounds: $ReadOnlyArray<string>, +emojiset_choices: $ReadOnlyArray<{| +key: string, +text: string |}>, |}, |}; /** * Users' chosen availability and text/emoji statuses. * * See UserStatusEvent for the event that carries updates to this data. */ // TODO(?): Find out if servers ignore any users (e.g., deactivated ones) when // assembling this. export type InitialDataUserStatus = $ReadOnly<{| /** * Each user's status, expressed relative to a "zero" status. * * The zero status is: * { away: false, status_text: '', * emoji_name: '', reaction_type: '', emoji_code: '' } * * For the corresponding value in our model in the app, see * `kUserStatusZero`. For discussion of the "zero value" concept, see: * path_to_url#discussion_r808451105 * * When the update for a given user would be empty (i.e., when their * status is the zero status), the server may omit that user's record * entirely. * * New in Zulip 2.0. Older servers don't send this, so it's natural * to treat them as if all users have the zero status; and that gives * correct behavior for this feature. * * See UserStatusEvent for the event that carries updates to this data. */ // TODO(server-2.0): Make required. user_status?: $ReadOnly<{| // Keys are UserId encoded as strings (just because JS objects are // string-keyed). [userId: string]: UserStatusUpdate, |}>, |}>; /** Initial data for the `user_topic` event type. */ export type InitialDataUserTopic = {| /** * When absent (on older servers), read `muted_topics` instead. * * For user-topic pairs not found here, the value is implicitly a * zero value: `visibility_policy` is `UserTopicVisibilityPolicy.None`. */ // TODO(server-6.0): Introduced in FL 134. +user_topics?: $ReadOnlyArray<UserTopic>, |}; /** * The initial data snapshot sent on `/register`. * * See API docs: * path_to_url#response * * Most properties are sent only if the client includes a particular item in * the `fetch_event_types` list. This type is meant to reflect the * properties that appear when sending the `fetch_event_types` that this * client sends, which is more or less all of them. * * This is the version after some processing. See `RawInitialData` for the * raw form sent by the server. */ export type InitialData = {| // To give a bit of organization to this very large object type, we group // the properties by which event type in `fetch_event_types` causes the // server to send them. The properties elicited by `realm_user` are // grouped together as a type called `InitialDataRealmUser`, and so on. // // For the server-side implementation, see zerver/lib/events.py at // fetch_initial_state_data. (But see the API docs first; if you need to // consult the server implementation, that's a bug in the API docs.) ...InitialDataBase, ...InitialDataAlertWords, ...InitialDataCustomProfileFields, ...InitialDataMessage, ...InitialDataMutedTopics, ...InitialDataMutedUsers, ...InitialDataPresence, ...InitialDataRealm, ...InitialDataRealmEmoji, ...InitialDataRealmFilters, ...InitialDataRealmLinkifiers, ...InitialDataRealmUser, ...InitialDataRealmUserGroups, ...InitialDataRecentPmConversations, ...InitialDataStream, ...InitialDataSubscription, ...InitialDataUpdateDisplaySettings, ...InitialDataUpdateGlobalNotifications, ...InitialDataUpdateMessageFlags, ...InitialDataUserSettings, ...InitialDataUserStatus, ...InitialDataUserTopic, |}; /** * Raw form of the initial data snapshot sent on `/register`. * * See API docs: * path_to_url#response * * This represents the raw JSON-decoding of the response from the server. * See `InitialData` for a slightly processed form. */ export type RawInitialData = $ReadOnly<{| ...InitialData, ...RawInitialDataBase, ...RawInitialDataRealmUser, ...RawInitialDataRealmFilters, |}>; ```
/content/code_sandbox/src/api/initialDataTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
7,162
```javascript // @flow strict-local import type { ApiNarrow, UserMessageFlag } from '../modelTypes'; import type { ApiResponseSuccess, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; // TODO(server-3.0): Move `Anchor` to modelTypes and share with getMessages. type Anchor = number | 'newest' | 'oldest' | 'first_unread'; type ApiResponseUpdateMessageFlagsForNarrow = {| ...$Exact<ApiResponseSuccess>, processed_count: number, updated_count: number, first_processed_id: number | null, last_processed_id: number | null, found_oldest: boolean, found_newest: boolean, |}; /** path_to_url */ export default function updateMessageFlagsForNarrow( auth: Auth, args: {| narrow: ApiNarrow, anchor: Anchor, include_anchor?: boolean, num_before: number, num_after: number, op: 'add' | 'remove', flag: UserMessageFlag, |}, ): Promise<ApiResponseUpdateMessageFlagsForNarrow> { return apiPost(auth, '/messages/flags/narrow', { ...args, narrow: JSON.stringify(args.narrow) }); } ```
/content/code_sandbox/src/api/messages/updateMessageFlagsForNarrow.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
267
```javascript /* @flow strict-local */ import invariant from 'invariant'; import type { Auth, ApiResponseSuccess } from '../transportTypes'; import { apiGet } from '../apiFetch'; import type { UserId } from '../idTypes'; type ServerApiResponseReadReceipts = {| ...$Exact<ApiResponseSuccess>, +user_ids: $ReadOnlyArray<UserId>, |}; /** * See path_to_url * * Should only be called for servers with FL 137+. */ // TODO(server-6.0): Stop mentioning a FL 137 condition. export default async ( auth: Auth, args: {| +message_id: number, |}, // TODO(#4659): Don't get this from callers. zulipFeatureLevel: number, ): Promise<$ReadOnlyArray<UserId>> => { invariant(zulipFeatureLevel >= 137, 'api.getReadReceipts called for unsupporting server'); const { message_id } = args; const response: ServerApiResponseReadReceipts = await apiGet( auth, `messages/${message_id}/read_receipts`, ); return response.user_ids; }; ```
/content/code_sandbox/src/api/messages/getReadReceipts.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
242
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from '../transportTypes'; import type { Identity } from '../../types'; import type { Message, ApiNarrow } from '../apiTypes'; import { transformFetchedMessage, type FetchedMessage } from '../rawModelTypes'; import { apiGet } from '../apiFetch'; import { identityOfAuth } from '../../account/accountMisc'; type ApiResponseMessages = {| ...$Exact<ApiResponseSuccess>, anchor: number, found_anchor: boolean, found_newest: boolean, found_oldest: boolean, messages: $ReadOnlyArray<Message>, |}; // The actual response from the server. We convert the data from this to // `ApiResponseMessages` before returning it to application code. type ServerApiResponseMessages = {| ...ApiResponseMessages, messages: $ReadOnlyArray<FetchedMessage>, |}; const migrateResponse = (response, identity: Identity, zulipFeatureLevel, allowEditHistory) => { const { messages, ...restResponse } = response; return { ...restResponse, messages: messages.map(message => transformFetchedMessage<Message>(message, identity, zulipFeatureLevel, allowEditHistory), ), }; }; /** * See path_to_url */ export default async ( auth: Auth, args: {| narrow: ApiNarrow, // TODO(server-3.0): Accept 'newest', 'oldest', and 'first_unread' anchor: number, // TODO(server-6.0): Also accept include_anchor (added at FL 155). numBefore: number, numAfter: number, // TODO(server-3.0): Stop sending use_first_unread_anchor. useFirstUnread?: boolean, |}, // TODO(#4659): Don't get this from callers. zulipFeatureLevel: number, // TODO(#4659): Don't get this from callers? allowEditHistory: boolean, ): Promise<ApiResponseMessages> => { const { narrow, anchor, numBefore, numAfter, useFirstUnread = false } = args; const response: ServerApiResponseMessages = await apiGet(auth, 'messages', { narrow: JSON.stringify(narrow), anchor, num_before: numBefore, num_after: numAfter, apply_markdown: true, use_first_unread_anchor: useFirstUnread, client_gravatar: true, }); return migrateResponse(response, identityOfAuth(auth), zulipFeatureLevel, allowEditHistory); }; ```
/content/code_sandbox/src/api/messages/getMessages.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
547
```javascript /* @flow strict-local */ import type { ApiResponseSuccess, Auth } from '../transportTypes'; import type { UserMessageFlag } from '../modelTypes'; import { apiPost } from '../apiFetch'; export type ApiResponseUpdateMessageFlags = {| ...$Exact<ApiResponseSuccess>, // The `messages` property is deprecated. See discussion: // path_to_url#narrow/stream/378-api-design/topic/mark-as-unread.20request/near/1463920 -messages: $ReadOnlyArray<number>, |}; /** path_to_url */ export default ( auth: Auth, messageIds: $ReadOnlyArray<number>, op: 'add' | 'remove', flag: UserMessageFlag, ): Promise<ApiResponseUpdateMessageFlags> => apiPost(auth, 'messages/flags', { messages: JSON.stringify(messageIds), flag, op }); ```
/content/code_sandbox/src/api/messages/updateMessageFlags.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
184
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import type { PropagateMode } from '../modelTypes'; import { apiPatch } from '../apiFetch'; /** * path_to_url * * NB the caller must manage old-server compatibility: * `send_notification_to_old_thread` and `send_notification_to_new_thread` * are available only starting with FL 9. */ // TODO(#4659): Once we pass the feature level to API methods, this one // should encapsulate dropping send_notification_* when unsupported. // TODO(server-3.0): Simplify that away. export default async ( auth: Auth, messageId: number, params: $ReadOnly<{| // TODO(server-2.0): Say "topic", not "subject" subject?: string, propagate_mode?: PropagateMode, content?: string, send_notification_to_old_thread?: boolean, send_notification_to_new_thread?: boolean, |}>, ): Promise<ApiResponse> => apiPatch(auth, `messages/${messageId}`, params); ```
/content/code_sandbox/src/api/messages/updateMessage.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
225
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiPatch } from '../apiFetch'; // TODO(#4701): Make an API method for DELETE /messages/{id}. Use it to // implement the permanent message deletion capability: // path_to_url // To do so, we'll need input from realm_delete_own_message_policy, // realm_message_content_delete_limit_seconds, the user's role, the current // time, and maybe more; we'll want #3898 if we can. export default async (auth: Auth, id: number): Promise<ApiResponse> => apiPatch(auth, `messages/${id}`, { content: '', }); ```
/content/code_sandbox/src/api/messages/deleteMessage.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
147
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from '../transportTypes'; import { apiGet } from '../apiFetch'; type ApiResponseTempFileUrl = {| ...$Exact<ApiResponseSuccess>, url: string, |}; /** * Get a temporary, authless partial URL to a realm-uploaded file. * * This endpoint was introduced in zulip/zulip@9e72fbe3f. The URL returned * allows a file to be viewed immediately without requiring a fresh login, but * it also does not include secrets like the API key. Currently, this URL * remains valid for 60 seconds. It can be used in various places in the app * where we open files in the browser, saving user's time. * * This endpoint is not in the Zulip API docs on the web, but it is * documented in our OpenAPI description: * path_to_url * under the name `get_file_temporary_url`. * * @param auth Authentication info of the current user. * @param filePath The location of the uploaded file, as a * "path-absolute-URL string" * (path_to_url#path-absolute-url-string) meant for the * realm, of the form `/user_uploads/{realm_id_str}/{filename}`. */ export default async (auth: Auth, filePath: string): Promise<URL> => { const response: ApiResponseTempFileUrl = await apiGet( auth, // Remove leading slash so apiGet doesn't duplicate it. filePath.substring(1), ); return new URL(response.url, auth.realm); }; ```
/content/code_sandbox/src/api/messages/getFileTemporaryUrl.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
346
```javascript /* @flow strict-local */ import type { Auth } from '../transportTypes'; import updateMessageFlags from './updateMessageFlags'; import type { ApiResponseUpdateMessageFlags } from './updateMessageFlags'; export default ( auth: Auth, messageIds: $ReadOnlyArray<number>, starMessage: boolean, ): Promise<ApiResponseUpdateMessageFlags> => updateMessageFlags(auth, messageIds, starMessage ? 'add' : 'remove', 'starred'); ```
/content/code_sandbox/src/api/messages/toggleMessageStarred.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
96
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from '../transportTypes'; import { type FetchedMessage } from '../rawModelTypes'; import { apiGet } from '../apiFetch'; // The actual response from a (current) server. We convert the message to a // proper Message before looking at its contents. type ServerApiResponseSingleMessage = {| ...$Exact<ApiResponseSuccess>, -raw_content: string, // deprecated // Until we narrow FetchedMessage into its FL 120+ form, FetchedMessage // will be a bit less precise than we could be here. That's because we // only get this field from servers FL 120+. +message: FetchedMessage, |}; // The response from a pre-FL 120 server. type ResponsePre120 = {| ...$Exact<ApiResponseSuccess>, +raw_content: string, // deprecated |}; /** * A wrapper for path_to_url that just gives a * message's raw Markdown content. * * See also api.getSingleMessage to get a whole Message object. * * Uses `.message.content` in the response when available, i.e., from * servers with FL 120+. Otherwise uses the top-level `.raw_content`. */ // TODO(server-5.0): Simplify FL-120 condition in jsdoc and implementation. export default async ( auth: Auth, args: {| +message_id: number, |}, // TODO(#4659): Don't get this from callers. zulipFeatureLevel: number, ): Promise<string> => { const { message_id } = args; if (zulipFeatureLevel >= 120) { const response: ServerApiResponseSingleMessage = await apiGet(auth, `messages/${message_id}`, { apply_markdown: false, }); return response.message.content; } else { const response: ResponsePre120 = await apiGet(auth, `messages/${message_id}`); return response.raw_content; } }; ```
/content/code_sandbox/src/api/messages/getRawMessageContent.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
432
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from '../transportTypes'; import type { Message } from '../apiTypes'; import { transformFetchedMessage, type FetchedMessage } from '../rawModelTypes'; import { apiGet } from '../apiFetch'; import { identityOfAuth } from '../../account/accountMisc'; // The actual response from the server. We convert the message to a proper // Message before returning it to application code. type ServerApiResponseSingleMessage = {| ...$Exact<ApiResponseSuccess>, -raw_content: string, // deprecated // Until we narrow FetchedMessage into its FL 120+ form, FetchedMessage // will be a bit less precise than we could be here. That's because we // only get this field from servers FL 120+. // TODO(server-5.0): Make this field required, and remove FL-120 comment. +message?: FetchedMessage, |}; /** * See path_to_url * * Throws an error if the message doesn't exist at all, or isn't visible to * our user. * * Otherwise, gives undefined on old servers (FL <120) where this API * endpoint doesn't return a `message` field. */ // TODO(server-5.0): Simplify FL-120 condition in jsdoc and implementation. export default async ( auth: Auth, args: {| +message_id: number, |}, // TODO(#4659): Don't get this from callers. zulipFeatureLevel: number, // TODO(#4659): Don't get this from callers? allowEditHistory: boolean, ): Promise<Message | void> => { const { message_id } = args; const response: ServerApiResponseSingleMessage = await apiGet(auth, `messages/${message_id}`, { apply_markdown: true, }); return ( response.message && transformFetchedMessage<Message>( response.message, identityOfAuth(auth), zulipFeatureLevel, allowEditHistory, ) ); }; ```
/content/code_sandbox/src/api/messages/getSingleMessage.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
443
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; /** * Delete all messages in a stream for a given topic. */ export default async (auth: Auth, streamId: number, topicName: string): Promise<ApiResponse> => apiPost(auth, `streams/${streamId}/delete_topic`, { topic_name: topicName, }); ```
/content/code_sandbox/src/api/messages/deleteTopic.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
90
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; /** See path_to_url */ export default async ( auth: Auth, params: {| type: 'private' | 'stream', to: string, // TODO(server-2.0): Say "topic", not "subject" subject?: string, content: string, localId?: number, eventQueueId?: string, |}, ): Promise<ApiResponse> => apiPost(auth, 'messages', { type: params.type, to: params.to, subject: params.subject, content: params.content, local_id: params.localId, queue_id: params.eventQueueId, }); ```
/content/code_sandbox/src/api/messages/sendMessage.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
165
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from '../transportTypes'; import type { User } from '../apiTypes'; import { apiGet } from '../apiFetch'; type ApiResponseUsers = {| ...$Exact<ApiResponseSuccess>, members: $ReadOnlyArray<{| ...User, avatar_url: string | null |}>, |}; // TODO: If we start to use this, we need to convert `.avatar_url` to // an AvatarURL instance, like we do in `registerForEvents` and // `EVENT_USER_ADD` and RealmUserUpdateEvent. /** See path_to_url */ export default (auth: Auth): Promise<ApiResponseUsers> => apiGet(auth, 'users', { client_gravatar: true }); ```
/content/code_sandbox/src/api/users/getUsers.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
159
```javascript /* @flow strict-local */ import invariant from 'invariant'; import type { UserSettings } from '../modelTypes'; import type { ApiResponseSuccess, Auth } from '../transportTypes'; import { apiPatch } from '../apiFetch'; // Assumes FL 89+ because the UserSettings type does; see note there. // // Current to FL 152. See the "Current to" note on the UserSettings type and // update that as needed too. // // TODO(server-5.0): Remove FL 89+ comment. type Args = {| ...$Rest<UserSettings, { ... }>, // These might move to a different endpoint in the future; see // path_to_url#narrow/stream/378-api-design/topic/User.20settings.20discrepancies/near/1457451 +full_name?: string, +email?: string, +old_password?: string, +new_password?: string, |}; /** * path_to_url * * NOTE: Only supports servers at feature level 89+ because UserSettings * assumes 89+; see there. */ // TODO(server-5.0): Simplify FL 89+ requirement export default ( auth: Auth, args: Args, // TODO(#4659): Don't get this from callers. zulipFeatureLevel: number, ): Promise<ApiResponseSuccess> => { invariant(zulipFeatureLevel >= 89, 'api.updateUserSettings not supported with FL <89'); return apiPatch(auth, 'settings', args); }; ```
/content/code_sandbox/src/api/users/updateUserSettings.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
330
```javascript /* @flow strict-local */ import type { UserStatus } from '../modelTypes'; import type { ApiResponseSuccess, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; /** * path_to_url * * See doc for important requirements, like a character limit on the status * text. */ export default ( auth: Auth, partialUserStatus: $Rest<UserStatus, { ... }>, ): Promise<ApiResponseSuccess> => { const { away, status_text, status_emoji } = partialUserStatus; const params = {}; if (away !== undefined) { params.away = away; } if (status_text !== undefined) { params.status_text = status_text ?? ''; } if (status_emoji !== undefined) { params.emoji_name = status_emoji?.emoji_name ?? ''; params.emoji_code = status_emoji?.emoji_code ?? ''; params.reaction_type = status_emoji?.reaction_type ?? ''; } return apiPost(auth, 'users/me/status', params); }; ```
/content/code_sandbox/src/api/users/updateUserStatus.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
224
```javascript /* @flow strict-local */ import type { ApiResponseSuccess, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; /** * See path_to_url * Note: The requesting user must be an administrator. */ export default ( auth: Auth, email: string, password: string, fullName: string, shortName: string, ): Promise<ApiResponseSuccess> => apiPost(auth, 'users', { email, password, full_name: fullName, short_name: shortName, }); ```
/content/code_sandbox/src/api/users/createUser.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
115
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from '../transportTypes'; import { type UserId } from '../idTypes'; import { apiGet } from '../apiFetch'; type ApiResponseUserProfile = {| ...$Exact<ApiResponseSuccess>, client_id: string, email: string, full_name: string, is_admin: boolean, is_bot: boolean, max_message_id: number, short_name: string, user_id: UserId, // pointer: number, /* deprecated 2020-02; see zulip/zulip#8994 */ |}; /** See path_to_url */ export default (auth: Auth, clientGravatar: boolean = true): Promise<ApiResponseUserProfile> => apiGet(auth, 'users/me'); ```
/content/code_sandbox/src/api/users/getUserProfile.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
165
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiPatch } from '../apiFetch'; const getRequestBody = (opp, value) => { const data = {}; if (opp === 'offline_notification_change') { data.enable_offline_push_notifications = value; } else if (opp === 'online_notification_change') { data.enable_online_push_notifications = value; } else if (opp === 'stream_notification_change') { data.enable_stream_push_notifications = value; } return data; }; export default async ({ auth, opp, value, }: {| auth: Auth, opp: string, value: boolean, |}): Promise<ApiResponse> => apiPatch(auth, 'settings/notifications', { ...getRequestBody(opp, value), }); ```
/content/code_sandbox/src/api/settings/toggleMobilePushSettings.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
177
```javascript /* @flow strict-local */ import type { Auth, ApiResponse } from '../transportTypes'; import { apiDelete } from '../apiFetch'; export default ( auth: Auth, messageId: number, reactionType: string, emojiCode: string, emojiName: string, ): Promise<ApiResponse> => apiDelete(auth, `messages/${messageId}/reactions`, { reaction_type: reactionType, emoji_code: emojiCode, emoji_name: emojiName, }); ```
/content/code_sandbox/src/api/emoji_reactions/emojiReactionRemove.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
104
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; export default ( auth: Auth, messageId: number, reactionType: string, emojiCode: string, emojiName: string, ): Promise<ApiResponse> => apiPost(auth, `messages/${messageId}/reactions`, { reaction_type: reactionType, emoji_code: emojiCode, emoji_name: emojiName, }); ```
/content/code_sandbox/src/api/emoji_reactions/emojiReactionAdd.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
104
```javascript /* @flow strict-local */ import type { ApiResponseSuccess } from '../transportTypes'; import { apiGet } from '../apiFetch'; import { ApiError, ServerTooOldError, kMinAllowedServerVersion } from '../apiErrors'; import { ZulipVersion } from '../../utils/zulipVersion'; // This corresponds to AUTHENTICATION_FLAGS in zulip/zulip:zerver/models.py . export type AuthenticationMethods = { dev?: boolean, github?: boolean, google?: boolean, ldap?: boolean, password?: boolean, azuread?: boolean, remoteuser?: boolean, ... }; export type ExternalAuthenticationMethod = {| name: string, display_name: string, display_icon: string | null, login_url: string, signup_url: string, |}; /** path_to_url */ // Current to FL 121. type ApiResponseServerSettings = {| ...$Exact<ApiResponseSuccess>, authentication_methods: AuthenticationMethods, external_authentication_methods: $ReadOnlyArray<ExternalAuthenticationMethod>, // TODO(server-3.0): New in FL 1. When absent, equivalent to 0. zulip_feature_level?: number, zulip_version: string, // TODO(server-5.0): New in FL 88. zulip_merge_base?: string, push_notifications_enabled: boolean, is_incompatible: boolean, email_auth_enabled: boolean, require_email_format_usernames: boolean, realm_uri: string, // When missing, the user requested the root domain of a Zulip server, but // there is no realm there. User error. // // (Also, the server has `ROOT_DOMAIN_LANDING_PAGE = False`, the default. // But the mobile client doesn't care about that; we just care that there // isn't a realm at the root.) // // Discussion: // path_to_url#narrow/stream/412-api-documentation/topic/.2Fserver_settings.3A.20.60realm_name.60.2C.20etc.2E/near/1334042 // // TODO(server-future): Expect the error to be encoded in a proper error // response instead of this missing property. // TODO(server-future): Then, when all supported servers give that error, // make this property required. realm_name?: string, realm_icon: string, realm_description: string, // TODO(server-5.0): New in FL 116. realm_web_public_access_enabled?: boolean, |}; export type ServerSettings = $ReadOnly<{| ...ApiResponseServerSettings, +zulip_feature_level: number, +zulip_version: ZulipVersion, +realm_uri: URL, +realm_name: string, +realm_web_public_access_enabled: boolean, |}>; /** * Make a ServerSettings from a raw API response. */ function transform(raw: ApiResponseServerSettings): ServerSettings { // (Even ancient servers have `zulip_version` in the response.) const zulipVersion = new ZulipVersion(raw.zulip_version); // Do this at the top, before we can accidentally trip on some later code // that's insensitive to ancient servers' behavior. if (!zulipVersion.isAtLeast(kMinAllowedServerVersion)) { throw new ServerTooOldError(zulipVersion); } const { realm_name } = raw; if (realm_name == null) { // See comment on realm_name in ApiResponseServerSettings. // // This error copies the proper error that servers *sometimes* give when // the root domain is requested and there's no realm there. [1] // Specifically, servers give this when // `ROOT_DOMAIN_LANDING_PAGE = True`. That circumstance makes no // difference to mobile. // // [1] Observed empirically. For details, see // path_to_url#narrow/stream/412-api-documentation/topic/.2Fserver_settings.3A.20.60realm_name.60.2C.20etc.2E/near/1332900 . throw new ApiError(400, { code: 'BAD_REQUEST', msg: 'Subdomain required', result: 'error' }); } return { ...raw, zulip_feature_level: raw.zulip_feature_level ?? 0, zulip_version: zulipVersion, realm_uri: new URL(raw.realm_uri), realm_name, realm_web_public_access_enabled: raw.realm_web_public_access_enabled ?? false, }; } /** See path_to_url */ export default async (realm: URL): Promise<ServerSettings> => { const result: ApiResponseServerSettings = await apiGet( { apiKey: '', email: '', realm }, 'server_settings', ); return transform(result); }; ```
/content/code_sandbox/src/api/settings/getServerSettings.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,051
```javascript /* @flow strict-local */ import { transformFetchedMessage, type FetchedMessage } from '../rawModelTypes'; import { identityOfAuth } from '../../account/accountMisc'; import * as eg from '../../__tests__/lib/exampleData'; import type { Message } from '../modelTypes'; import { GravatarURL } from '../../utils/avatar'; describe('transformFetchedMessage', () => { const fetchedMessage: FetchedMessage = { ...eg.streamMessage(), reactions: [eg.unicodeEmojiReaction], avatar_url: null, edit_history: [ { prev_content: 'foo', prev_rendered_content: '<p>foo</p>', prev_stream: eg.stream.stream_id, prev_topic: 'bar', stream: eg.otherStream.stream_id, timestamp: 0, topic: 'bar!', user_id: eg.selfUser.user_id, }, ], }; describe('recent server', () => { const input: FetchedMessage = fetchedMessage; const expectedOutput: Message = { ...fetchedMessage, avatar_url: GravatarURL.validateAndConstructInstance({ email: fetchedMessage.sender_email }), edit_history: // $FlowIgnore[incompatible-cast] - See MessageEdit type (fetchedMessage.edit_history: Message['edit_history']), }; const actualOutput: Message = transformFetchedMessage<Message>( input, identityOfAuth(eg.selfAuth), eg.recentZulipFeatureLevel, true, ); test('Converts avatar_url correctly', () => { expect(actualOutput.avatar_url).toEqual(expectedOutput.avatar_url); }); test('Keeps edit_history, if allowEditHistory is true', () => { expect(actualOutput.edit_history).toEqual(expectedOutput.edit_history); }); test('Drops edit_history, if allowEditHistory is false', () => { expect( transformFetchedMessage<Message>( input, identityOfAuth(eg.selfAuth), eg.recentZulipFeatureLevel, false, ).edit_history, ).toEqual(null); }); }); describe('drops edit_history from pre-118 server', () => { expect( transformFetchedMessage<Message>( { ...fetchedMessage, edit_history: [ { prev_content: 'foo', prev_rendered_content: '<p>foo</p>', prev_stream: eg.stream.stream_id, prev_subject: 'bar', timestamp: 0, user_id: eg.selfUser.user_id, }, ], }, identityOfAuth(eg.selfAuth), 117, true, ).edit_history, ).toEqual(null); }); }); ```
/content/code_sandbox/src/api/__tests__/rawModelTypes-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
575
```javascript import { getFetchParams } from '../apiFetch'; global.FormData = jest.fn(); describe('getFetchParams', () => { test('creates a `header` key with authorization data', () => { const auth = { email: 'john@example.com', apiKey: 'some_key', }; const params = {}; const actualResult = getFetchParams(auth, params); expect(actualResult.headers).toBeTruthy(); expect(actualResult.headers.Authorization).toBeTruthy(); }); test('merges `headers` key and all given params into a new object', () => { const auth = { email: 'john@example.com', apiKey: 'some_key', }; const params = { key: 'value', }; const actualResult = getFetchParams(auth, params); expect(actualResult.key).toBe('value'); }); test('when no apiKey provided does not return `Authorization` headers key', () => { const auth = { email: 'john@example.com', apiKey: '', }; const params = {}; const actualResult = getFetchParams(auth, params); expect(actualResult.headers).toBeTruthy(); expect(actualResult.headers.Authorization).toBeUndefined(); }); }); ```
/content/code_sandbox/src/api/__tests__/apiFetch-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
258
```javascript /* @flow strict-local */ import queueMarkAsRead, { resetAll } from '../queueMarkAsRead'; import * as updateMessageFlags from '../messages/updateMessageFlags'; import * as eg from '../../__tests__/lib/exampleData'; // $FlowFixMe[cannot-write] Make flow understand about mocking updateMessageFlags.default = jest.fn( (auth, ids, op, flag) => new Promise((resolve, reject) => { resolve({ messages: ids, msg: '', result: 'success' }); }), ); describe('queueMarkAsRead', () => { afterEach(() => { jest.clearAllMocks(); jest.clearAllTimers(); resetAll(); }); test('should not call updateMessageFlags on consecutive calls of queueMarkAsRead, setTimout on further calls', () => { queueMarkAsRead(eg.selfAuth, [1, 2, 3]); queueMarkAsRead(eg.selfAuth, [4, 5, 6]); queueMarkAsRead(eg.selfAuth, [7, 8, 9]); queueMarkAsRead(eg.selfAuth, [10, 11, 12]); expect(jest.getTimerCount()).toBe(1); expect(updateMessageFlags.default).toHaveBeenCalledTimes(1); }); test('should call updateMessageFlags, if calls to queueMarkAsRead are 2s apart', () => { queueMarkAsRead(eg.selfAuth, [13, 14, 15]); jest.advanceTimersByTime(2100); queueMarkAsRead(eg.selfAuth, [16, 17, 18]); expect(updateMessageFlags.default).toHaveBeenCalledTimes(2); }); test('should set timeout for time remaining for next API call to clear queue', () => { queueMarkAsRead(eg.selfAuth, [1, 2, 3]); jest.advanceTimersByTime(1900); queueMarkAsRead(eg.selfAuth, [4, 5, 6]); jest.runOnlyPendingTimers(); expect(updateMessageFlags.default).toHaveBeenCalledTimes(2); }); test('empty array should not cause anything to happen', () => { queueMarkAsRead(eg.selfAuth, []); jest.advanceTimersByTime(2500); jest.runOnlyPendingTimers(); expect(updateMessageFlags.default).toHaveBeenCalledTimes(0); }); }); ```
/content/code_sandbox/src/api/__tests__/queueMarkAsRead-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
513
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; export default async (auth: Auth, streamId: number): Promise<ApiResponse> => apiPost(auth, 'mark_stream_as_read', { stream_id: streamId, }); ```
/content/code_sandbox/src/api/mark_as_read/markStreamAsRead.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
68
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from '../transportTypes'; import { apiPost } from '../apiFetch'; type ApiResponseRealmCreateFilters = {| ...$Exact<ApiResponseSuccess>, id: number, |}; /** path_to_url */ export default async ( auth: Auth, pattern: string, urlFormatString: string, ): Promise<ApiResponseRealmCreateFilters> => apiPost(auth, 'realm/filters', { pattern, url_format_string: urlFormatString }); ```
/content/code_sandbox/src/api/realm/createRealmFilter.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
109
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; export default async (auth: Auth, streamId: number, topic: string): Promise<ApiResponse> => apiPost(auth, 'mark_topic_as_read', { stream_id: streamId, topic_name: topic, }); ```
/content/code_sandbox/src/api/mark_as_read/markTopicAsRead.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
78
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; export default async (auth: Auth): Promise<ApiResponse> => apiPost(auth, 'mark_all_as_read'); ```
/content/code_sandbox/src/api/mark_as_read/markAllAsRead.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
52
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiDelete } from '../apiFetch'; /** See path_to_url */ export default ( auth: Auth, // TODO(server-future): This should use a stream ID (#3918), not stream name. // Server issue: path_to_url subscriptions: $ReadOnlyArray<string>, // TODO(server-3.0): Send numeric user IDs (#3764), not emails. principals?: $ReadOnlyArray<string>, ): Promise<ApiResponse> => apiDelete(auth, 'users/me/subscriptions', { subscriptions: JSON.stringify(subscriptions), principals: JSON.stringify(principals), }); ```
/content/code_sandbox/src/api/subscriptions/subscriptionRemove.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
147
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiPatch } from '../apiFetch'; /** See path_to_url */ export default async ( auth: Auth, // TODO(server-2.0): Switch to stream ID (#3918), instead of name. // (The version that was introduced in isn't documented: // path_to_url#issuecomment-1033046851 // but see: // path_to_url#issuecomment-840200325 // ) stream: string, topic: string, value: boolean, ): Promise<ApiResponse> => apiPatch(auth, 'users/me/subscriptions/muted_topics', { stream, topic, op: value ? 'add' : 'remove', }); ```
/content/code_sandbox/src/api/subscriptions/setTopicMute.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
174
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from '../transportTypes'; import type { Subscription } from '../apiTypes'; import { apiGet } from '../apiFetch'; type ApiResponseSubscriptions = {| ...$Exact<ApiResponseSuccess>, subscriptions: $ReadOnlyArray<Subscription>, |}; /** See path_to_url */ export default (auth: Auth): Promise<ApiResponseSubscriptions> => apiGet(auth, 'users/me/subscriptions'); ```
/content/code_sandbox/src/api/subscriptions/getSubscriptions.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
97
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; export type SubscriptionProperty = 'is_muted' | 'pin_to_top' | 'push_notifications'; /** See path_to_url */ export default async ( auth: Auth, streamId: number, property: SubscriptionProperty, value: boolean, ): Promise<ApiResponse> => apiPost(auth, 'users/me/subscriptions/properties', { subscription_data: JSON.stringify([ { stream_id: streamId, // Let callers use the modern property, 'is_muted', but give // the server the older, confusingly named property // 'in_home_view' with the opposite value. // // TODO(server-2.1): 'is_muted' is said to be new in Zulip 2.1, // released 2019-12-12. Switch to sending that, once we can. ...(property === 'is_muted' ? { property: 'in_home_view', value: !value } : { property, value }), }, ]), }); ```
/content/code_sandbox/src/api/subscriptions/setSubscriptionProperty.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
248
```javascript /* @flow strict-local */ import type { Auth, ApiResponseSuccess } from '../transportTypes'; import { type UserId } from '../idTypes'; import { apiGet } from '../apiFetch'; type ApiResponseSubscriptionStatus = {| ...$Exact<ApiResponseSuccess>, is_subscribed: boolean, |}; /** * Get whether a user is subscribed to a particular stream. * * See path_to_url for * documentation of this endpoint. */ export default ( auth: Auth, userId: UserId, streamId: number, ): Promise<ApiResponseSubscriptionStatus> => apiGet(auth, `users/${userId}/subscriptions/${streamId}`); ```
/content/code_sandbox/src/api/subscriptions/getSubscriptionToStream.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
134
```javascript // @flow strict-local import type { UserTopicVisibilityPolicy } from '../modelTypes'; import type { ApiResponseSuccess, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; /** path_to_url */ export default function updateUserTopic( auth: Auth, stream_id: number, topic: string, visibility_policy: UserTopicVisibilityPolicy, ): Promise<ApiResponseSuccess> { return apiPost(auth, '/user_topics', { stream_id, topic, visibility_policy: (visibility_policy: number), }); } ```
/content/code_sandbox/src/api/subscriptions/updateUserTopic.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
117
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; type SubscriptionObj = {| // TODO(server-future): This should use a stream ID (#3918), not stream name. // Server issue: path_to_url name: string, |}; /** See path_to_url */ export default ( auth: Auth, subscriptions: $ReadOnlyArray<SubscriptionObj>, // TODO(server-3.0): Send numeric user IDs (#3764), not emails. principals?: $ReadOnlyArray<string>, ): Promise<ApiResponse> => apiPost(auth, 'users/me/subscriptions', { subscriptions: JSON.stringify(subscriptions), principals: JSON.stringify(principals), }); ```
/content/code_sandbox/src/api/subscriptions/subscriptionAdd.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
162
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; /** See path_to_url#poll-todo-lists-and-games */ // `msg_type` only exists as widget at the moment, see #3205. export default async (auth: Auth, messageId: number, content: string): Promise<ApiResponse> => apiPost(auth, 'submessage', { message_id: messageId, msg_type: 'widget', content, }); ```
/content/code_sandbox/src/api/submessages/sendSubmessage.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
111
```javascript /* @flow strict-local */ import type { Auth } from '../transportTypes'; import { apiDelete } from '../apiFetch'; /** * Tell the server to forget this device token for push notifications. * * @param mobileOS - Choose the server-side API intended for iOS or Android clients. */ export default (auth: Auth, mobileOS: 'ios' | 'android', token: string): Promise<mixed> => { const routeName = mobileOS === 'android' ? 'android_gcm_reg_id' : 'apns_device_token'; return apiDelete(auth, `users/me/${routeName}`, { token }); }; ```
/content/code_sandbox/src/api/notifications/forgetPushToken.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
131
```javascript /* @flow strict-local */ import type { Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; /** * Tell the server our device token for push notifications. * * @param mobileOS - Choose the server-side API intended for iOS or Android clients. */ export default async (auth: Auth, mobileOS: 'ios' | 'android', token: string): Promise<mixed> => { const routeName = mobileOS === 'android' ? 'android_gcm_reg_id' : 'apns_device_token'; const extraParams = // The `Object.freeze` is to work around a Flow issue: // path_to_url#issuecomment-695064325 mobileOS === 'android' ? Object.freeze({}) : { appid: 'org.zulip.Zulip' }; return apiPost(auth, `users/me/${routeName}`, { token, ...extraParams, }); }; ```
/content/code_sandbox/src/api/notifications/savePushToken.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
199
```javascript /* @flow strict-local */ import type { ApiResponse, Auth } from '../transportTypes'; import { apiPost } from '../apiFetch'; /** See path_to_url */ export default async ( auth: Auth, params: {| token: string, |}, ): Promise<ApiResponse> => apiPost(auth, 'mobile_push/test_notification', { token: params.token, }); ```
/content/code_sandbox/src/api/notifications/sendTestNotification.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
83
```javascript /* @flow strict-local */ import Immutable from 'immutable'; import type { MutedUsersState, PerAccountApplicableAction, UserId } from '../types'; import { REGISTER_COMPLETE, EVENT_MUTED_USERS, RESET_ACCOUNT_DATA } from '../actionConstants'; import type { MutedUser } from '../api/apiTypes'; const initialState: MutedUsersState = Immutable.Map(); function mutedUsersToMap(muted_users: $ReadOnlyArray<MutedUser>): Immutable.Map<UserId, number> { return Immutable.Map(muted_users.map(muted_user => [muted_user.id, muted_user.timestamp])); } export default ( state: MutedUsersState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, ): MutedUsersState => { switch (action.type) { case RESET_ACCOUNT_DATA: return initialState; case REGISTER_COMPLETE: return mutedUsersToMap(action.data.muted_users ?? []); case EVENT_MUTED_USERS: return mutedUsersToMap(action.muted_users); default: return state; } }; ```
/content/code_sandbox/src/mute/mutedUsersReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
223
```javascript // @flow strict-local import Immutable from 'immutable'; import { type UserTopicVisibilityPolicy } from '../api/modelTypes'; /** * The "visibility policy" our user has chosen for each topic. * * See jsdoc of UserTopicVisibilityPolicy for background. * * In this data structure, the keys are stream ID and then topic name. * Values of `UserTopicVisibilityPolicy.None` are represented by absence, * and streams where the map would be empty are also omitted. */ // TODO(#5381): Ideally we'd call this UserTopicState and `state.userTopic`. // But it's currently a pain to actually rename a state subtree: #5381. export type MuteState = Immutable.Map< number, // stream ID Immutable.Map< string, // topic name UserTopicVisibilityPolicy, >, >; ```
/content/code_sandbox/src/mute/muteModelTypes.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
177
```javascript /* @flow strict-local */ import { reducer } from '../muteModel'; import type { MuteState } from '../muteModelTypes'; import { type Stream, type UserTopic, UserTopicVisibilityPolicy } from '../../api/modelTypes'; import * as eg from '../../__tests__/lib/exampleData'; export const makeUserTopic = ( stream: Stream, topic: string, visibility_policy: UserTopicVisibilityPolicy, ): UserTopic => ({ stream_id: stream.stream_id, topic_name: topic, visibility_policy, last_updated: 12345, // arbitrary value; we ignore last_updated here }); /** * Convenience constructor for a MuteState. * * The tuples are (stream, topic, policy). * The policy defaults to UserTopicVisibilityPolicy.Muted. */ export const makeMuteState = ( data: $ReadOnlyArray<[Stream, string] | [Stream, string, UserTopicVisibilityPolicy]>, ): MuteState => reducer( undefined, eg.mkActionRegisterComplete({ user_topics: data.map(args => { // $FlowIgnore[invalid-tuple-index]: we're supplying a default const [stream, topic, policy = UserTopicVisibilityPolicy.Muted] = args; return makeUserTopic(stream, topic, policy); }), }), eg.reduxState(), ); ```
/content/code_sandbox/src/mute/__tests__/mute-testlib.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
282
```javascript /* @flow strict-local */ import Immutable from 'immutable'; import type { MuteState, PerAccountApplicableAction, PerAccountState, Subscription, } from '../types'; import { UserTopicVisibilityPolicy } from '../api/modelTypes'; import { EventTypes } from '../api/eventTypes'; import { REGISTER_COMPLETE, EVENT_MUTED_TOPICS, RESET_ACCOUNT_DATA, EVENT, } from '../actionConstants'; import { getStreamsByName } from '../subscriptions/subscriptionSelectors'; import * as logging from '../utils/logging'; import DefaultMap from '../utils/DefaultMap'; import { updateAndPrune } from '../immutableUtils'; import { getZulipFeatureLevel } from '../account/accountsSelectors'; // // // Selectors. // export const getMute = (state: PerAccountState): MuteState => state.mute; // // // Getters. // export function getTopicVisibilityPolicy( mute: MuteState, streamId: number, topic: string, ): UserTopicVisibilityPolicy { return mute.get(streamId)?.get(topic) ?? UserTopicVisibilityPolicy.None; } /** * Whether this topic should appear when already focusing on its stream. * * This is false if the user's visibility policy for the topic is Muted, * and true if the policy is Unmuted or None. * * This function is appropriate for muting calculations in UI contexts that * are already specific to a stream: for example the stream's unread count, * or the message list in the stream's narrow. * * For UI contexts that are not specific to a particular stream, see * `isTopicVisible`. */ export function isTopicVisibleInStream(streamId: number, topic: string, mute: MuteState): boolean { const policy = getTopicVisibilityPolicy(mute, streamId, topic); switch (policy) { case UserTopicVisibilityPolicy.None: return true; case UserTopicVisibilityPolicy.Muted: return false; case UserTopicVisibilityPolicy.Unmuted: case UserTopicVisibilityPolicy.Followed: return true; } } /** * Whether this topic should appear when not specifically focusing on this stream. * * This takes into account the user's visibility policy for the stream * overall, as well as their policy for this topic. * * For UI contexts that are specific to a particular stream, see * `isTopicVisibleInStream`. */ export function isTopicVisible( streamId: number, topic: string, subscription: Subscription, mute: MuteState, ): boolean { switch (getTopicVisibilityPolicy(mute, streamId, topic)) { case UserTopicVisibilityPolicy.None: { const streamMuted = !subscription.in_home_view; return !streamMuted; } case UserTopicVisibilityPolicy.Muted: return false; case UserTopicVisibilityPolicy.Unmuted: case UserTopicVisibilityPolicy.Followed: return true; } } /** * Whether the user is following this topic. */ export function isTopicFollowed(streamId: number, topic: string, mute: MuteState): boolean { switch (getTopicVisibilityPolicy(mute, streamId, topic)) { case UserTopicVisibilityPolicy.None: case UserTopicVisibilityPolicy.Muted: case UserTopicVisibilityPolicy.Unmuted: return false; case UserTopicVisibilityPolicy.Followed: return true; } } // // // Reducer. // const initialState: MuteState = Immutable.Map(); /** * Warn and return true on an unexpected value; else return false. * * This lets us keep out of our data structures any values we * don't expect in our types. */ function warnInvalidVisibilityPolicy(visibility_policy: UserTopicVisibilityPolicy): boolean { if (!UserTopicVisibilityPolicy.isValid((visibility_policy: number))) { // Not a value we expect. Keep it out of our data structures. logging.warn(`unexpected UserTopicVisibilityPolicy: ${(visibility_policy: number)}`); return true; } return false; } /** Consume the old `muted_topics` format. */ function convertLegacy(data, streams): MuteState { // Same strategy as in convertInitial, below. const byStream = new DefaultMap(() => []); for (const [streamName, topic] of data) { const stream = streams.get(streamName); if (!stream) { logging.warn('mute: unknown stream'); continue; } byStream.getOrCreate(stream.stream_id).push([topic, UserTopicVisibilityPolicy.Muted]); } return Immutable.Map(Immutable.Seq.Keyed(byStream.map.entries()).map(Immutable.Map)); } function convertInitial(data): MuteState { // Turn the incoming array into a nice, indexed, Immutable data structure // in the same two-phase pattern we use for the unread data, as an // optimization. Here it's probably much less often enough data for the // optimization to matter; but a longtime user who regularly uses this // feature will accumulate many records over time, and then it could. // First, collect together all the data for a given stream, just in a // plain old Array. const byStream = new DefaultMap(() => []); for (const { stream_id, topic_name, visibility_policy } of data) { if (warnInvalidVisibilityPolicy(visibility_policy)) { continue; } byStream.getOrCreate(stream_id).push([topic_name, visibility_policy]); } // Then, from each of those build an Immutable.Map all in one shot. return Immutable.Map(Immutable.Seq.Keyed(byStream.map.entries()).map(Immutable.Map)); } export const reducer = ( state: MuteState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, globalState: PerAccountState, ): MuteState => { switch (action.type) { case RESET_ACCOUNT_DATA: return initialState; case REGISTER_COMPLETE: if (action.data.user_topics) { return convertInitial(action.data.user_topics); } // We require this `globalState` to reflect the `streams` sub-reducer // already having run, so that `getStreamsByName` gives the data we // just received. See this sub-reducer's call site in `reducers.js`. // TODO(server-6.0): Stop caring about that, when we cut muted_topics. return convertLegacy( action.data.muted_topics // Unnecessary fallback just to satisfy Flow: the old // `muted_topics` is absent only when the new `user_topics` is // present (ignoring ancient unsupported servers), but Flow // doesn't track that. ?? [], getStreamsByName(globalState), ); case EVENT_MUTED_TOPICS: { if (getZulipFeatureLevel(globalState) >= 134) { // TODO(server-6.0): Drop this muted_topics event type entirely. // This event type is obsoleted by `user_topic`, so we can ignore it. // // The server sends both types of events, because we // don't set event_types in our /register request: // path_to_url#issuecomment-1133466148 // But if we interpreted the muted_topics events as usual, // we'd throw away all policies other than None or Muted. return state; } return convertLegacy(action.muted_topics, getStreamsByName(globalState)); } case EVENT: { const { event } = action; switch (event.type) { case EventTypes.user_topic: { const { stream_id, topic_name } = event; let { visibility_policy } = event; if (warnInvalidVisibilityPolicy(visibility_policy)) { visibility_policy = UserTopicVisibilityPolicy.None; } if (visibility_policy === UserTopicVisibilityPolicy.None) { // This is the "zero value" for this type, which our MuteState // data structure represents by leaving the topic out entirely. return updateAndPrune( state, Immutable.Map(), stream_id, (perStream = Immutable.Map()) => perStream.delete(topic_name), ); } return state.updateIn([stream_id, topic_name], () => visibility_policy); } default: return state; } } default: return state; } }; ```
/content/code_sandbox/src/mute/muteModel.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
1,795
```javascript /* @flow strict-local */ import Immutable from 'immutable'; import deepFreeze from 'deep-freeze'; import mutedUsersReducer from '../mutedUsersReducer'; import { EVENT_MUTED_USERS } from '../../actionConstants'; import * as eg from '../../__tests__/lib/exampleData'; describe('mutedUsersReducer', () => { const baseState = Immutable.Map([[eg.otherUser.user_id, 1618822632]]); describe('REGISTER_COMPLETE', () => { test('when `muted_users` data is provided init state with it', () => { const action = eg.mkActionRegisterComplete({ muted_users: [{ id: eg.otherUser.user_id, timestamp: 1618822632 }], }); expect(mutedUsersReducer(eg.baseReduxState.mutedUsers, action)).toEqual( Immutable.Map([[eg.otherUser.user_id, 1618822632]]), ); }); test('when no `muted_users` data is given reset state', () => { expect(mutedUsersReducer(baseState, eg.action.register_complete)).toEqual(Immutable.Map()); }); }); describe('RESET_ACCOUNT_DATA', () => { test('resets state to initial state', () => { expect(mutedUsersReducer(baseState, eg.action.reset_account_data)).toEqual(Immutable.Map()); }); }); describe('EVENT_MUTED_USERS', () => { test('update `muted_users` when event comes in', () => { const action = deepFreeze({ type: EVENT_MUTED_USERS, id: 1234, muted_users: [ { id: eg.otherUser.user_id, timestamp: 1618822632 }, { id: eg.thirdUser.user_id, timestamp: 1618822635 }, ], }); // prettier-ignore expect(mutedUsersReducer(baseState, action)).toEqual(Immutable.Map([ [eg.otherUser.user_id, 1618822632], [eg.thirdUser.user_id, 1618822635], ])); }); }); }); ```
/content/code_sandbox/src/mute/__tests__/mutedUsersReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
437
```javascript /* @flow strict-local */ import type { AlertWordsState, PerAccountApplicableAction } from '../types'; import { REGISTER_COMPLETE, EVENT_ALERT_WORDS, RESET_ACCOUNT_DATA } from '../actionConstants'; import { NULL_ARRAY } from '../nullObjects'; const initialState = NULL_ARRAY; export default ( state: AlertWordsState = initialState, // eslint-disable-line default-param-last action: PerAccountApplicableAction, ): AlertWordsState => { switch (action.type) { case RESET_ACCOUNT_DATA: return initialState; case REGISTER_COMPLETE: return action.data.alert_words; case EVENT_ALERT_WORDS: return action.alert_words || initialState; default: return state; } }; ```
/content/code_sandbox/src/alertWords/alertWordsReducer.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
146
```javascript /* @flow strict-local */ import deepFreeze from 'deep-freeze'; import alertWordsReducer from '../alertWordsReducer'; import { EVENT_ALERT_WORDS } from '../../actionConstants'; import * as eg from '../../__tests__/lib/exampleData'; describe('alertWordsReducer', () => { describe('RESET_ACCOUNT_DATA', () => { const initialState = eg.baseReduxState.alertWords; const action1 = eg.mkActionRegisterComplete({ alert_words: ['word', '@mobile-core', 'alert'] }); const prevState = alertWordsReducer(initialState, action1); expect(prevState).not.toEqual(initialState); expect(alertWordsReducer(prevState, eg.action.reset_account_data)).toEqual(initialState); }); describe('REGISTER_COMPLETE', () => { test('when `alert_words` data is provided init state with it', () => { const prevState = deepFreeze([]); expect( alertWordsReducer( prevState, eg.mkActionRegisterComplete({ alert_words: ['word', '@mobile-core', 'alert'] }), ), ).toEqual(['word', '@mobile-core', 'alert']); }); }); describe('EVENT_ALERT_WORDS', () => { test('on first call adds new data', () => { const prevState = deepFreeze([]); expect( alertWordsReducer( prevState, deepFreeze({ type: EVENT_ALERT_WORDS, alert_words: ['word', '@mobile-core', 'alert'] }), ), ).toEqual(['word', '@mobile-core', 'alert']); }); test('subsequent calls replace existing data', () => { const prevState = deepFreeze(['word', '@mobile-core', 'alert']); expect( alertWordsReducer( prevState, deepFreeze({ type: EVENT_ALERT_WORDS, alert_words: ['word', '@mobile-core', 'new alert'], }), ), ).toEqual(['word', '@mobile-core', 'new alert']); }); }); }); ```
/content/code_sandbox/src/alertWords/__tests__/alertWordsReducer-test.js
javascript
2016-05-08T05:41:48
2024-08-15T07:25:47
zulip-mobile
zulip/zulip-mobile
1,274
412