You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

248 lines
8.0 KiB

Change IDs to strings rather than numbers in API JSON output (#5019) * Fix JavaScript interface with long IDs Somewhat predictably, the JS interface handled IDs as numbers, which in JS are IEEE double-precision floats. This loses some precision when working with numbers as large as those generated by the new ID scheme, so we instead handle them here as strings. This is relatively simple, and doesn't appear to have caused any problems, but should definitely be tested more thoroughly than the built-in tests. Several days of use appear to support this working properly. BREAKING CHANGE: The major(!) change here is that IDs are now returned as strings by the REST endpoints, rather than as integers. In practice, relatively few changes were required to make the existing JS UI work with this change, but it will likely hit API clients pretty hard: it's an entirely different type to consume. (The one API client I tested, Tusky, handles this with no problems, however.) Twitter ran into this issue when introducing Snowflake IDs, and decided to instead introduce an `id_str` field in JSON responses. I have opted to *not* do that, and instead force all IDs to 64-bit integers represented by strings in one go. (I believe Twitter exacerbated their problem by rolling out the changes three times: once for statuses, once for DMs, and once for user IDs, as well as by leaving an integer ID value in JSON. As they said, "If you’re using the `id` field with JSON in a Javascript-related language, there is a very high likelihood that the integers will be silently munged by Javascript interpreters. In most cases, this will result in behavior such as being unable to load or delete a specific direct message, because the ID you're sending to the API is different than the actual identifier associated with the message." [1]) However, given that this is a significant change for API users, alternatives or a transition time may be appropriate. 1: https://blog.twitter.com/developer/en_us/a/2011/direct-messages-going-snowflake-on-sep-30-2011.html * Additional fixes for stringified IDs in JSON These should be the last two. These were identified using eslint to try to identify any plain casts to JavaScript numbers. (Some such casts are legitimate, but these were not.) Adding the following to .eslintrc.yml will identify casts to numbers: ~~~ no-restricted-syntax: - warn - selector: UnaryExpression[operator='+'] > :not(Literal) message: Avoid the use of unary + - selector: CallExpression[callee.name='Number'] message: Casting with Number() may coerce string IDs to numbers ~~~ The remaining three casts appear legitimate: two casts to array indices, one in a server to turn an environment variable into a number. * Back out RelationshipsController Change This was made to make a test a bit less flakey, but has nothing to do with this branch. * Change internal streaming payloads to stringified IDs as well Per https://github.com/tootsuite/mastodon/pull/5019#issuecomment-330736452 we need these changes to send deleted status IDs as strings, not integers.
6 years ago
7 years ago
7 years ago
  1. import React from 'react';
  2. import ImmutablePropTypes from 'react-immutable-proptypes';
  3. import PropTypes from 'prop-types';
  4. import Avatar from './avatar';
  5. import AvatarOverlay from './avatar_overlay';
  6. import RelativeTimestamp from './relative_timestamp';
  7. import DisplayName from './display_name';
  8. import StatusContent from './status_content';
  9. import StatusActionBar from './status_action_bar';
  10. import { FormattedMessage } from 'react-intl';
  11. import ImmutablePureComponent from 'react-immutable-pure-component';
  12. import { MediaGallery, Video } from '../features/ui/util/async-components';
  13. import { HotKeys } from 'react-hotkeys';
  14. import classNames from 'classnames';
  15. // We use the component (and not the container) since we do not want
  16. // to use the progress bar to show download progress
  17. import Bundle from '../features/ui/components/bundle';
  18. export default class Status extends ImmutablePureComponent {
  19. static contextTypes = {
  20. router: PropTypes.object,
  21. };
  22. static propTypes = {
  23. status: ImmutablePropTypes.map,
  24. account: ImmutablePropTypes.map,
  25. onReply: PropTypes.func,
  26. onFavourite: PropTypes.func,
  27. onReblog: PropTypes.func,
  28. onDelete: PropTypes.func,
  29. onPin: PropTypes.func,
  30. onOpenMedia: PropTypes.func,
  31. onOpenVideo: PropTypes.func,
  32. onBlock: PropTypes.func,
  33. onEmbed: PropTypes.func,
  34. onHeightChange: PropTypes.func,
  35. muted: PropTypes.bool,
  36. hidden: PropTypes.bool,
  37. onMoveUp: PropTypes.func,
  38. onMoveDown: PropTypes.func,
  39. };
  40. state = {
  41. isExpanded: false,
  42. }
  43. // Avoid checking props that are functions (and whose equality will always
  44. // evaluate to false. See react-immutable-pure-component for usage.
  45. updateOnProps = [
  46. 'status',
  47. 'account',
  48. 'muted',
  49. 'hidden',
  50. ]
  51. updateOnStates = ['isExpanded']
  52. handleClick = () => {
  53. if (!this.context.router) {
  54. return;
  55. }
  56. const { status } = this.props;
  57. this.context.router.history.push(`/statuses/${status.getIn(['reblog', 'id'], status.get('id'))}`);
  58. }
  59. handleAccountClick = (e) => {
  60. if (this.context.router && e.button === 0) {
  61. const id = e.currentTarget.getAttribute('data-id');
  62. e.preventDefault();
  63. this.context.router.history.push(`/accounts/${id}`);
  64. }
  65. }
  66. handleExpandedToggle = () => {
  67. this.setState({ isExpanded: !this.state.isExpanded });
  68. };
  69. renderLoadingMediaGallery () {
  70. return <div className='media_gallery' style={{ height: '110px' }} />;
  71. }
  72. renderLoadingVideoPlayer () {
  73. return <div className='media-spoiler-video' style={{ height: '110px' }} />;
  74. }
  75. handleOpenVideo = startTime => {
  76. this.props.onOpenVideo(this._properStatus().getIn(['media_attachments', 0]), startTime);
  77. }
  78. handleHotkeyReply = e => {
  79. e.preventDefault();
  80. this.props.onReply(this._properStatus(), this.context.router.history);
  81. }
  82. handleHotkeyFavourite = () => {
  83. this.props.onFavourite(this._properStatus());
  84. }
  85. handleHotkeyBoost = e => {
  86. this.props.onReblog(this._properStatus(), e);
  87. }
  88. handleHotkeyMention = e => {
  89. e.preventDefault();
  90. this.props.onMention(this._properStatus().get('account'), this.context.router.history);
  91. }
  92. handleHotkeyOpen = () => {
  93. this.context.router.history.push(`/statuses/${this._properStatus().get('id')}`);
  94. }
  95. handleHotkeyOpenProfile = () => {
  96. this.context.router.history.push(`/accounts/${this._properStatus().getIn(['account', 'id'])}`);
  97. }
  98. handleHotkeyMoveUp = () => {
  99. this.props.onMoveUp(this.props.status.get('id'));
  100. }
  101. handleHotkeyMoveDown = () => {
  102. this.props.onMoveDown(this.props.status.get('id'));
  103. }
  104. _properStatus () {
  105. const { status } = this.props;
  106. if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') {
  107. return status.get('reblog');
  108. } else {
  109. return status;
  110. }
  111. }
  112. render () {
  113. let media = null;
  114. let statusAvatar, prepend;
  115. const { hidden } = this.props;
  116. const { isExpanded } = this.state;
  117. let { status, account, ...other } = this.props;
  118. if (status === null) {
  119. return null;
  120. }
  121. if (hidden) {
  122. return (
  123. <div>
  124. {status.getIn(['account', 'display_name']) || status.getIn(['account', 'username'])}
  125. {status.get('content')}
  126. </div>
  127. );
  128. }
  129. if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') {
  130. const display_name_html = { __html: status.getIn(['account', 'display_name_html']) };
  131. prepend = (
  132. <div className='status__prepend'>
  133. <div className='status__prepend-icon-wrapper'><i className='fa fa-fw fa-retweet status__prepend-icon' /></div>
  134. <FormattedMessage id='status.reblogged_by' defaultMessage='{name} boosted' values={{ name: <a onClick={this.handleAccountClick} data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} className='status__display-name muted'><bdi><strong dangerouslySetInnerHTML={display_name_html} /></bdi></a> }} />
  135. </div>
  136. );
  137. account = status.get('account');
  138. status = status.get('reblog');
  139. }
  140. if (status.get('media_attachments').size > 0 && !this.props.muted) {
  141. if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) {
  142. } else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
  143. const video = status.getIn(['media_attachments', 0]);
  144. media = (
  145. <Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} >
  146. {Component => (
  147. <Component
  148. preview={video.get('preview_url')}
  149. src={video.get('url')}
  150. width={239}
  151. height={110}
  152. sensitive={status.get('sensitive')}
  153. onOpenVideo={this.handleOpenVideo}
  154. />
  155. )}
  156. </Bundle>
  157. );
  158. } else {
  159. media = (
  160. <Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery} >
  161. {Component => <Component media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={this.props.onOpenMedia} />}
  162. </Bundle>
  163. );
  164. }
  165. }
  166. if (account === undefined || account === null) {
  167. statusAvatar = <Avatar account={status.get('account')} size={48} />;
  168. }else{
  169. statusAvatar = <AvatarOverlay account={status.get('account')} friend={account} />;
  170. }
  171. const handlers = this.props.muted ? {} : {
  172. reply: this.handleHotkeyReply,
  173. favourite: this.handleHotkeyFavourite,
  174. boost: this.handleHotkeyBoost,
  175. mention: this.handleHotkeyMention,
  176. open: this.handleHotkeyOpen,
  177. openProfile: this.handleHotkeyOpenProfile,
  178. moveUp: this.handleHotkeyMoveUp,
  179. moveDown: this.handleHotkeyMoveDown,
  180. };
  181. return (
  182. <HotKeys handlers={handlers}>
  183. <div className={classNames('status__wrapper', `status__wrapper-${status.get('visibility')}`, { focusable: !this.props.muted })} tabIndex={this.props.muted ? null : 0}>
  184. {prepend}
  185. <div className={classNames('status', `status-${status.get('visibility')}`, { muted: this.props.muted })} data-id={status.get('id')}>
  186. <div className='status__info'>
  187. <a href={status.get('url')} className='status__relative-time' target='_blank' rel='noopener'><RelativeTimestamp timestamp={status.get('created_at')} /></a>
  188. <a onClick={this.handleAccountClick} target='_blank' data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} title={status.getIn(['account', 'acct'])} className='status__display-name'>
  189. <div className='status__avatar'>
  190. {statusAvatar}
  191. </div>
  192. <DisplayName account={status.get('account')} />
  193. </a>
  194. </div>
  195. <StatusContent status={status} onClick={this.handleClick} expanded={isExpanded} onExpandedToggle={this.handleExpandedToggle} />
  196. {media}
  197. <StatusActionBar status={status} account={account} {...other} />
  198. </div>
  199. </div>
  200. </HotKeys>
  201. );
  202. }
  203. }