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.

531 lines
18 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
4 years ago
  1. import React from 'react';
  2. import Immutable from 'immutable';
  3. import ImmutablePropTypes from 'react-immutable-proptypes';
  4. import PropTypes from 'prop-types';
  5. import Avatar from './avatar';
  6. import AvatarOverlay from './avatar_overlay';
  7. import AvatarComposite from './avatar_composite';
  8. import RelativeTimestamp from './relative_timestamp';
  9. import DisplayName from './display_name';
  10. import StatusContent from './status_content';
  11. import StatusActionBar from './status_action_bar';
  12. import AttachmentList from './attachment_list';
  13. import Card from '../features/status/components/card';
  14. import { injectIntl, FormattedMessage, FormattedNumber } from 'react-intl';
  15. import ImmutablePureComponent from 'react-immutable-pure-component';
  16. import { MediaGallery, Video, Audio } from '../features/ui/util/async-components';
  17. import { HotKeys } from 'react-hotkeys';
  18. import classNames from 'classnames';
  19. import Icon from 'mastodon/components/icon';
  20. import { displayMedia } from '../initial_state';
  21. import StatusContainer from '../containers/status_container2';
  22. // We use the component (and not the container) since we do not want
  23. // to use the progress bar to show download progress
  24. import Bundle from '../features/ui/components/bundle';
  25. export const textForScreenReader = (intl, status, rebloggedByText = false) => {
  26. const displayName = status.getIn(['account', 'display_name']);
  27. const values = [
  28. displayName.length === 0 ? status.getIn(['account', 'acct']).split('@')[0] : displayName,
  29. status.get('spoiler_text') && status.get('hidden') ? status.get('spoiler_text') : status.get('search_index').slice(status.get('spoiler_text').length),
  30. intl.formatDate(status.get('created_at'), { hour: '2-digit', minute: '2-digit', month: 'short', day: 'numeric' }),
  31. status.getIn(['account', 'acct']),
  32. ];
  33. if (rebloggedByText) {
  34. values.push(rebloggedByText);
  35. }
  36. return values.join(', ');
  37. };
  38. export const defaultMediaVisibility = (status) => {
  39. if (!status) {
  40. return undefined;
  41. }
  42. if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') {
  43. status = status.get('reblog');
  44. }
  45. return (displayMedia !== 'hide_all' && !status.get('sensitive') || displayMedia === 'show_all');
  46. };
  47. export default @injectIntl
  48. class Status extends ImmutablePureComponent {
  49. static contextTypes = {
  50. router: PropTypes.object,
  51. };
  52. static propTypes = {
  53. status: ImmutablePropTypes.map,
  54. account: ImmutablePropTypes.map,
  55. otherAccounts: ImmutablePropTypes.list,
  56. onClick: PropTypes.func,
  57. onReply: PropTypes.func,
  58. onFavourite: PropTypes.func,
  59. onReblog: PropTypes.func,
  60. onDelete: PropTypes.func,
  61. onDirect: PropTypes.func,
  62. onMention: PropTypes.func,
  63. onPin: PropTypes.func,
  64. onOpenMedia: PropTypes.func,
  65. onOpenVideo: PropTypes.func,
  66. onBlock: PropTypes.func,
  67. onEmbed: PropTypes.func,
  68. onHeightChange: PropTypes.func,
  69. onToggleHidden: PropTypes.func,
  70. muted: PropTypes.bool,
  71. hidden: PropTypes.bool,
  72. unread: PropTypes.bool,
  73. onMoveUp: PropTypes.func,
  74. onMoveDown: PropTypes.func,
  75. showThread: PropTypes.bool,
  76. getScrollPosition: PropTypes.func,
  77. updateScrollBottom: PropTypes.func,
  78. cacheMediaWidth: PropTypes.func,
  79. cachedMediaWidth: PropTypes.number,
  80. sonsIds: ImmutablePropTypes.list,
  81. onPreview: PropTypes.func
  82. };
  83. // Avoid checking props that are functions (and whose equality will always
  84. // evaluate to false. See react-immutable-pure-component for usage.
  85. updateOnProps = [
  86. 'status',
  87. 'account',
  88. 'muted',
  89. 'hidden',
  90. 'sonsIds'
  91. ];
  92. state = {
  93. showMedia: defaultMediaVisibility(this.props.status),
  94. statusId: undefined,
  95. noPreviewData: true,
  96. noStartPD: true
  97. };
  98. // Track height changes we know about to compensate scrolling
  99. componentDidMount () {
  100. this.didShowCard = !this.props.muted && !this.props.hidden && this.props.status && this.props.status.get('card');
  101. }
  102. getSnapshotBeforeUpdate () {
  103. if (this.props.getScrollPosition) {
  104. return this.props.getScrollPosition();
  105. } else {
  106. return null;
  107. }
  108. }
  109. static getDerivedStateFromProps(nextProps, prevState) {
  110. if (nextProps.status && nextProps.status.get('id') !== prevState.statusId) {
  111. return {
  112. showMedia: defaultMediaVisibility(nextProps.status),
  113. statusId: nextProps.status.get('id'),
  114. };
  115. } else {
  116. return null;
  117. }
  118. }
  119. // Compensate height changes
  120. componentDidUpdate (prevProps, prevState, snapshot) {
  121. const doShowCard = !this.props.muted && !this.props.hidden && this.props.status && this.props.status.get('card');
  122. if (doShowCard && !this.didShowCard) {
  123. this.didShowCard = true;
  124. if (snapshot !== null && this.props.updateScrollBottom) {
  125. if (this.node && this.node.offsetTop < snapshot.top) {
  126. this.props.updateScrollBottom(snapshot.height - snapshot.top);
  127. }
  128. }
  129. }
  130. }
  131. componentWillUnmount() {
  132. if (this.node && this.props.getScrollPosition) {
  133. const position = this.props.getScrollPosition();
  134. if (position !== null && this.node.offsetTop < position.top) {
  135. requestAnimationFrame(() => {
  136. this.props.updateScrollBottom(position.height - position.top);
  137. });
  138. }
  139. }
  140. }
  141. handleToggleMediaVisibility = () => {
  142. this.setState({ showMedia: !this.state.showMedia });
  143. }
  144. handleClick = () => {
  145. if (this.props.onClick) {
  146. this.props.onClick();
  147. return;
  148. }
  149. if (!this.context.router) {
  150. return;
  151. }
  152. const { status } = this.props;
  153. const r_status = status.get('reblog') || status;
  154. if(this.props.com_prev && this.state.noPreviewData && r_status.get('replies_count')) {
  155. if(this.state.noStartPD)
  156. this.handleMouseEnter();
  157. return;
  158. }
  159. this.context.router.history.push(`/statuses/${status.getIn(['reblog', 'id'], status.get('id'))}`);
  160. }
  161. handleMouseEnter = () => {
  162. const { status } = this.props;
  163. const r_status = status.get('reblog') || status;
  164. if(this.props.com_prev && this.state.noStartPD && r_status.get('replies_count')) {
  165. this.setState({noStartPD: false});
  166. setTimeout(() => {
  167. this.props.onPreview(r_status.get('id'));
  168. this.setState({noPreviewData: false});
  169. },500);
  170. }
  171. }
  172. handleExpandClick = (e) => {
  173. if (this.props.onClick) {
  174. this.props.onClick();
  175. return;
  176. }
  177. if (e.button === 0) {
  178. if (!this.context.router) {
  179. return;
  180. }
  181. const { status } = this.props;
  182. this.context.router.history.push(`/statuses/${status.getIn(['reblog', 'id'], status.get('id'))}`);
  183. }
  184. }
  185. handleAccountClick = (e) => {
  186. if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
  187. const id = e.currentTarget.getAttribute('data-id');
  188. e.preventDefault();
  189. this.context.router.history.push(`/accounts/${id}`);
  190. }
  191. }
  192. handleExpandedToggle = () => {
  193. this.props.onToggleHidden(this._properStatus());
  194. };
  195. renderLoadingMediaGallery () {
  196. return <div className='media-gallery' style={{ height: '110px' }} />;
  197. }
  198. renderLoadingVideoPlayer () {
  199. return <div className='video-player' style={{ height: '110px' }} />;
  200. }
  201. renderLoadingAudioPlayer () {
  202. return <div className='audio-player' style={{ height: '110px' }} />;
  203. }
  204. handleOpenVideo = (media, startTime) => {
  205. this.props.onOpenVideo(media, startTime);
  206. }
  207. handleHotkeyReply = e => {
  208. e.preventDefault();
  209. this.props.onReply(this._properStatus(), this.context.router.history);
  210. }
  211. handleHotkeyFavourite = () => {
  212. this.props.onFavourite(this._properStatus());
  213. }
  214. handleHotkeyBoost = e => {
  215. this.props.onReblog(this._properStatus(), e);
  216. }
  217. handleHotkeyMention = e => {
  218. e.preventDefault();
  219. this.props.onMention(this._properStatus().get('account'), this.context.router.history);
  220. }
  221. handleHotkeyOpen = () => {
  222. this.context.router.history.push(`/statuses/${this._properStatus().get('id')}`);
  223. }
  224. handleHotkeyOpenProfile = () => {
  225. this.context.router.history.push(`/accounts/${this._properStatus().getIn(['account', 'id'])}`);
  226. }
  227. handleHotkeyMoveUp = e => {
  228. this.props.onMoveUp(this.props.status.get('id'), e.target.getAttribute('data-featured'));
  229. }
  230. handleHotkeyMoveDown = e => {
  231. this.props.onMoveDown(this.props.status.get('id'), e.target.getAttribute('data-featured'));
  232. }
  233. handleHotkeyToggleHidden = () => {
  234. this.props.onToggleHidden(this._properStatus());
  235. }
  236. handleHotkeyToggleSensitive = () => {
  237. this.handleToggleMediaVisibility();
  238. }
  239. _properStatus () {
  240. const { status } = this.props;
  241. if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') {
  242. return status.get('reblog');
  243. } else {
  244. return status;
  245. }
  246. }
  247. handleRef = c => {
  248. this.node = c;
  249. }
  250. renderChildren (list) {
  251. return list.map(id => (
  252. <StatusContainer
  253. key={id}
  254. id={id}
  255. onMoveUp={()=>{}}
  256. onMoveDown={()=>{}}
  257. contextType='thread'
  258. />
  259. ));
  260. }
  261. render () {
  262. let media = null;
  263. let statusAvatar, prepend, rebloggedByText;
  264. let sons;
  265. const { intl, hidden, featured, otherAccounts, unread, showThread, deep, tree_type, sonsIds } = this.props;
  266. let { status, account, ...other } = this.props;
  267. if (status === null) {
  268. return null;
  269. }
  270. const handlers = this.props.muted ? {} : {
  271. reply: this.handleHotkeyReply,
  272. favourite: this.handleHotkeyFavourite,
  273. boost: this.handleHotkeyBoost,
  274. mention: this.handleHotkeyMention,
  275. open: this.handleHotkeyOpen,
  276. openProfile: this.handleHotkeyOpenProfile,
  277. moveUp: this.handleHotkeyMoveUp,
  278. moveDown: this.handleHotkeyMoveDown,
  279. toggleHidden: this.handleHotkeyToggleHidden,
  280. toggleSensitive: this.handleHotkeyToggleSensitive,
  281. };
  282. if (hidden) {
  283. return (
  284. <HotKeys handlers={handlers}>
  285. <div ref={this.handleRef} className={classNames('status__wrapper', { focusable: !this.props.muted })} tabIndex='0'>
  286. {status.getIn(['account', 'display_name']) || status.getIn(['account', 'username'])}
  287. {status.get('content')}
  288. </div>
  289. </HotKeys>
  290. );
  291. }
  292. if (status.get('filtered') || status.getIn(['reblog', 'filtered'])) {
  293. const minHandlers = this.props.muted ? {} : {
  294. moveUp: this.handleHotkeyMoveUp,
  295. moveDown: this.handleHotkeyMoveDown,
  296. };
  297. return (
  298. <HotKeys handlers={minHandlers}>
  299. <div className='status__wrapper status__wrapper--filtered focusable' tabIndex='0' ref={this.handleRef}>
  300. <FormattedMessage id='status.filtered' defaultMessage='Filtered' />
  301. </div>
  302. </HotKeys>
  303. );
  304. }
  305. if (featured) {
  306. prepend = (
  307. <div className='status__prepend'>
  308. <div className='status__prepend-icon-wrapper'><Icon id='thumb-tack' className='status__prepend-icon' fixedWidth /></div>
  309. <FormattedMessage id='status.pinned' defaultMessage='Pinned toot' />
  310. </div>
  311. );
  312. } else if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') {
  313. const display_name_html = { __html: status.getIn(['account', 'display_name_html']) };
  314. prepend = (
  315. <div className='status__prepend'>
  316. <div className='status__prepend-icon-wrapper'><Icon id='retweet' className='status__prepend-icon' fixedWidth /></div>
  317. <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> }} />
  318. </div>
  319. );
  320. rebloggedByText = intl.formatMessage({ id: 'status.reblogged_by', defaultMessage: '{name} boosted' }, { name: status.getIn(['account', 'acct']) });
  321. account = status.get('account');
  322. status = status.get('reblog');
  323. }
  324. if (status.get('media_attachments').size > 0) {
  325. if (this.props.muted) {
  326. media = (
  327. <AttachmentList
  328. compact
  329. media={status.get('media_attachments')}
  330. />
  331. );
  332. } else if (status.getIn(['media_attachments', 0, 'type']) === 'audio') {
  333. const attachment = status.getIn(['media_attachments', 0]);
  334. media = (
  335. <Bundle fetchComponent={Audio} loading={this.renderLoadingAudioPlayer} >
  336. {Component => (
  337. <Component
  338. src={attachment.get('url')}
  339. alt={attachment.get('description')}
  340. duration={attachment.getIn(['meta', 'original', 'duration'], 0)}
  341. peaks={[0]}
  342. height={70}
  343. />
  344. )}
  345. </Bundle>
  346. );
  347. } else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
  348. const attachment = status.getIn(['media_attachments', 0]);
  349. media = (
  350. <Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} >
  351. {Component => (
  352. <Component
  353. preview={attachment.get('preview_url')}
  354. blurhash={attachment.get('blurhash')}
  355. src={attachment.get('url')}
  356. alt={attachment.get('description')}
  357. width={this.props.cachedMediaWidth}
  358. height={110}
  359. inline
  360. sensitive={status.get('sensitive')}
  361. onOpenVideo={this.handleOpenVideo}
  362. cacheWidth={this.props.cacheMediaWidth}
  363. visible={this.state.showMedia}
  364. onToggleVisibility={this.handleToggleMediaVisibility}
  365. />
  366. )}
  367. </Bundle>
  368. );
  369. } else {
  370. media = (
  371. <Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery}>
  372. {Component => (
  373. <Component
  374. media={status.get('media_attachments')}
  375. sensitive={status.get('sensitive')}
  376. height={110}
  377. onOpenMedia={this.props.onOpenMedia}
  378. cacheWidth={this.props.cacheMediaWidth}
  379. defaultWidth={this.props.cachedMediaWidth}
  380. visible={this.state.showMedia}
  381. onToggleVisibility={this.handleToggleMediaVisibility}
  382. />
  383. )}
  384. </Bundle>
  385. );
  386. }
  387. } else if (status.get('spoiler_text').length === 0 && status.get('card')) {
  388. media = (
  389. <Card
  390. onOpenMedia={this.props.onOpenMedia}
  391. card={status.get('card')}
  392. compact
  393. cacheWidth={this.props.cacheMediaWidth}
  394. defaultWidth={this.props.cachedMediaWidth}
  395. />
  396. );
  397. }
  398. if (otherAccounts && otherAccounts.size > 0) {
  399. statusAvatar = <AvatarComposite accounts={otherAccounts} size={48} />;
  400. } else if (account === undefined || account === null) {
  401. statusAvatar = <Avatar account={status.get('account')} size={48} />;
  402. } else {
  403. statusAvatar = <AvatarOverlay account={status.get('account')} friend={account} />;
  404. }
  405. if(sonsIds && sonsIds.size > 0) {
  406. sons = <div className='comments_timeline'>{this.renderChildren(sonsIds)}</div>;
  407. }
  408. let deepRec;
  409. if(deep != null) {
  410. deepRec = (
  411. <div className="detailed-status__button deep__number">
  412. <Icon id="tree" />
  413. <span>
  414. <FormattedNumber value={deep} />
  415. </span>
  416. </div>
  417. );
  418. }
  419. return (
  420. <HotKeys handlers={handlers}>
  421. <div className={classNames('status__wrapper', `status__wrapper-${status.get('visibility')}`, { 'status__wrapper-reply': !!status.get('in_reply_to_id'), read: unread === false, focusable: !this.props.muted }, (deep!=null) && 'tree-'+tree_type)} tabIndex={this.props.muted ? null : 0} data-featured={featured ? 'true' : null} aria-label={textForScreenReader(intl, status, rebloggedByText)} ref={this.handleRef}>
  422. {prepend}
  423. <div className={classNames('status', `status-${status.get('visibility')}`, { 'status-reply': !!status.get('in_reply_to_id'), muted: this.props.muted, read: unread === false })} data-id={status.get('id')} onMouseEnter={this.handleMouseEnter}>
  424. <div className='status__expand' onClick={this.handleExpandClick} role='presentation' />
  425. <div className='status__info'>
  426. <a href={status.get('url')} className='status__relative-time' target='_blank' rel='noopener'><RelativeTimestamp timestamp={status.get('created_at')} /></a>
  427. <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'>
  428. <div className='status__avatar'>
  429. {statusAvatar}
  430. </div>
  431. <DisplayName account={status.get('account')} others={otherAccounts} />
  432. </a>
  433. </div>
  434. {deepRec}
  435. <StatusContent status={status} onClick={this.handleClick} expanded={!status.get('hidden')} onExpandedToggle={this.handleExpandedToggle} collapsable />
  436. {media}
  437. {showThread && status.get('in_reply_to_id') && (
  438. <button className='status__content__read-more-button' onClick={this.handleClick}>
  439. <FormattedMessage id='status.show_thread' defaultMessage='Show thread' />
  440. </button>
  441. )}
  442. {(deep == null || tree_type != 'ance') && (
  443. <StatusActionBar status={status} account={account} {...other} />
  444. )}
  445. </div>
  446. </div>
  447. {sons}
  448. </HotKeys>
  449. );
  450. }
  451. }