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.

651 lines
18 KiB

7 years ago
7 years ago
  1. import api from '../api';
  2. import { CancelToken, isCancel } from 'axios';
  3. import { throttle } from 'lodash';
  4. import { search as emojiSearch } from '../features/emoji/emoji_mart_search_light';
  5. import { tagHistory } from '../settings';
  6. import { useEmoji } from './emojis';
  7. import resizeImage from '../utils/resize_image';
  8. import { importFetchedAccounts } from './importer';
  9. import { updateTimeline } from './timelines';
  10. import { showAlertForError } from './alerts';
  11. import { showAlert } from './alerts';
  12. import { defineMessages } from 'react-intl';
  13. let cancelFetchComposeSuggestionsAccounts, cancelFetchComposeSuggestionsTags;
  14. export const COMPOSE_CHANGE = 'COMPOSE_CHANGE';
  15. export const COMPOSE_SUBMIT_REQUEST = 'COMPOSE_SUBMIT_REQUEST';
  16. export const COMPOSE_SUBMIT_SUCCESS = 'COMPOSE_SUBMIT_SUCCESS';
  17. export const COMPOSE_SUBMIT_FAIL = 'COMPOSE_SUBMIT_FAIL';
  18. export const COMPOSE_REPLY = 'COMPOSE_REPLY';
  19. export const COMPOSE_REPLY_CANCEL = 'COMPOSE_REPLY_CANCEL';
  20. export const COMPOSE_DIRECT = 'COMPOSE_DIRECT';
  21. export const COMPOSE_MENTION = 'COMPOSE_MENTION';
  22. export const COMPOSE_RESET = 'COMPOSE_RESET';
  23. export const COMPOSE_UPLOAD_REQUEST = 'COMPOSE_UPLOAD_REQUEST';
  24. export const COMPOSE_UPLOAD_SUCCESS = 'COMPOSE_UPLOAD_SUCCESS';
  25. export const COMPOSE_UPLOAD_FAIL = 'COMPOSE_UPLOAD_FAIL';
  26. export const COMPOSE_UPLOAD_PROGRESS = 'COMPOSE_UPLOAD_PROGRESS';
  27. export const COMPOSE_UPLOAD_UNDO = 'COMPOSE_UPLOAD_UNDO';
  28. export const THUMBNAIL_UPLOAD_REQUEST = 'THUMBNAIL_UPLOAD_REQUEST';
  29. export const THUMBNAIL_UPLOAD_SUCCESS = 'THUMBNAIL_UPLOAD_SUCCESS';
  30. export const THUMBNAIL_UPLOAD_FAIL = 'THUMBNAIL_UPLOAD_FAIL';
  31. export const THUMBNAIL_UPLOAD_PROGRESS = 'THUMBNAIL_UPLOAD_PROGRESS';
  32. export const COMPOSE_SUGGESTIONS_CLEAR = 'COMPOSE_SUGGESTIONS_CLEAR';
  33. export const COMPOSE_SUGGESTIONS_READY = 'COMPOSE_SUGGESTIONS_READY';
  34. export const COMPOSE_SUGGESTION_SELECT = 'COMPOSE_SUGGESTION_SELECT';
  35. export const COMPOSE_SUGGESTION_TAGS_UPDATE = 'COMPOSE_SUGGESTION_TAGS_UPDATE';
  36. export const COMPOSE_TAG_HISTORY_UPDATE = 'COMPOSE_TAG_HISTORY_UPDATE';
  37. export const COMPOSE_MOUNT = 'COMPOSE_MOUNT';
  38. export const COMPOSE_UNMOUNT = 'COMPOSE_UNMOUNT';
  39. export const COMPOSE_SENSITIVITY_CHANGE = 'COMPOSE_SENSITIVITY_CHANGE';
  40. export const COMPOSE_SPOILERNESS_CHANGE = 'COMPOSE_SPOILERNESS_CHANGE';
  41. export const COMPOSE_SPOILER_TEXT_CHANGE = 'COMPOSE_SPOILER_TEXT_CHANGE';
  42. export const COMPOSE_VISIBILITY_CHANGE = 'COMPOSE_VISIBILITY_CHANGE';
  43. export const COMPOSE_LISTABILITY_CHANGE = 'COMPOSE_LISTABILITY_CHANGE';
  44. export const COMPOSE_COMPOSING_CHANGE = 'COMPOSE_COMPOSING_CHANGE';
  45. export const COMPOSE_EMOJI_INSERT = 'COMPOSE_EMOJI_INSERT';
  46. export const COMPOSE_UPLOAD_CHANGE_REQUEST = 'COMPOSE_UPLOAD_UPDATE_REQUEST';
  47. export const COMPOSE_UPLOAD_CHANGE_SUCCESS = 'COMPOSE_UPLOAD_UPDATE_SUCCESS';
  48. export const COMPOSE_UPLOAD_CHANGE_FAIL = 'COMPOSE_UPLOAD_UPDATE_FAIL';
  49. export const COMPOSE_POLL_ADD = 'COMPOSE_POLL_ADD';
  50. export const COMPOSE_POLL_REMOVE = 'COMPOSE_POLL_REMOVE';
  51. export const COMPOSE_POLL_OPTION_ADD = 'COMPOSE_POLL_OPTION_ADD';
  52. export const COMPOSE_POLL_OPTION_CHANGE = 'COMPOSE_POLL_OPTION_CHANGE';
  53. export const COMPOSE_POLL_OPTION_REMOVE = 'COMPOSE_POLL_OPTION_REMOVE';
  54. export const COMPOSE_POLL_SETTINGS_CHANGE = 'COMPOSE_POLL_SETTINGS_CHANGE';
  55. const messages = defineMessages({
  56. uploadErrorLimit: { id: 'upload_error.limit', defaultMessage: 'File upload limit exceeded.' },
  57. uploadErrorPoll: { id: 'upload_error.poll', defaultMessage: 'File upload not allowed with polls.' },
  58. });
  59. const COMPOSE_PANEL_BREAKPOINT = 600 + (285 * 1) + (10 * 1);
  60. export const ensureComposeIsVisible = (getState, routerHistory) => {
  61. if (!getState().getIn(['compose', 'mounted']) && window.innerWidth < COMPOSE_PANEL_BREAKPOINT) {
  62. routerHistory.push('/statuses/new');
  63. }
  64. };
  65. export function changeCompose(text) {
  66. return {
  67. type: COMPOSE_CHANGE,
  68. text: text,
  69. };
  70. };
  71. export function replyCompose(status, routerHistory) {
  72. return (dispatch, getState) => {
  73. dispatch({
  74. type: COMPOSE_REPLY,
  75. status: status,
  76. });
  77. ensureComposeIsVisible(getState, routerHistory);
  78. };
  79. };
  80. export function cancelReplyCompose() {
  81. return {
  82. type: COMPOSE_REPLY_CANCEL,
  83. };
  84. };
  85. export function resetCompose() {
  86. return {
  87. type: COMPOSE_RESET,
  88. };
  89. };
  90. export function mentionCompose(account, routerHistory) {
  91. return (dispatch, getState) => {
  92. dispatch({
  93. type: COMPOSE_MENTION,
  94. account: account,
  95. });
  96. ensureComposeIsVisible(getState, routerHistory);
  97. };
  98. };
  99. export function directCompose(account, routerHistory) {
  100. return (dispatch, getState) => {
  101. dispatch({
  102. type: COMPOSE_DIRECT,
  103. account: account,
  104. });
  105. ensureComposeIsVisible(getState, routerHistory);
  106. };
  107. };
  108. export function submitCompose(routerHistory) {
  109. return function (dispatch, getState) {
  110. const status = getState().getIn(['compose', 'text'], '');
  111. const media = getState().getIn(['compose', 'media_attachments']);
  112. if ((!status || !status.length) && media.size === 0) {
  113. return;
  114. }
  115. dispatch(submitComposeRequest());
  116. api(getState).post('/api/v1/statuses', {
  117. status,
  118. in_reply_to_id: getState().getIn(['compose', 'in_reply_to'], null),
  119. media_ids: media.map(item => item.get('id')),
  120. sensitive: getState().getIn(['compose', 'sensitive']),
  121. spoiler_text: getState().getIn(['compose', 'spoiler']) ? getState().getIn(['compose', 'spoiler_text'], '') : '',
  122. visibility: getState().getIn(['compose', 'privacy']),
  123. poll: getState().getIn(['compose', 'poll'], null),
  124. }, {
  125. headers: {
  126. 'Idempotency-Key': getState().getIn(['compose', 'idempotencyKey']),
  127. },
  128. }).then(function (response) {
  129. if (routerHistory && routerHistory.location.pathname === '/statuses/new' && window.history.state) {
  130. routerHistory.goBack();
  131. }
  132. dispatch(insertIntoTagHistory(response.data.tags, status));
  133. dispatch(submitComposeSuccess({ ...response.data }));
  134. // To make the app more responsive, immediately push the status
  135. // into the columns
  136. const insertIfOnline = timelineId => {
  137. const timeline = getState().getIn(['timelines', timelineId]);
  138. if (timeline && timeline.get('items').size > 0 && timeline.getIn(['items', 0]) !== null && timeline.get('online')) {
  139. dispatch(updateTimeline(timelineId, { ...response.data }));
  140. }
  141. };
  142. if (response.data.visibility !== 'direct') {
  143. insertIfOnline('home');
  144. }
  145. if (response.data.in_reply_to_id === null && response.data.visibility === 'public') {
  146. insertIfOnline('community');
  147. insertIfOnline('public');
  148. insertIfOnline(`account:${response.data.account.id}`);
  149. }
  150. }).catch(function (error) {
  151. dispatch(submitComposeFail(error));
  152. });
  153. };
  154. };
  155. export function submitComposeRequest() {
  156. return {
  157. type: COMPOSE_SUBMIT_REQUEST,
  158. };
  159. };
  160. export function submitComposeSuccess(status) {
  161. return {
  162. type: COMPOSE_SUBMIT_SUCCESS,
  163. status: status,
  164. };
  165. };
  166. export function submitComposeFail(error) {
  167. return {
  168. type: COMPOSE_SUBMIT_FAIL,
  169. error: error,
  170. };
  171. };
  172. export function uploadCompose(files) {
  173. return function (dispatch, getState) {
  174. const uploadLimit = 4;
  175. const media = getState().getIn(['compose', 'media_attachments']);
  176. const pending = getState().getIn(['compose', 'pending_media_attachments']);
  177. const progress = new Array(files.length).fill(0);
  178. let total = Array.from(files).reduce((a, v) => a + v.size, 0);
  179. if (files.length + media.size + pending > uploadLimit) {
  180. dispatch(showAlert(undefined, messages.uploadErrorLimit));
  181. return;
  182. }
  183. if (getState().getIn(['compose', 'poll'])) {
  184. dispatch(showAlert(undefined, messages.uploadErrorPoll));
  185. return;
  186. }
  187. dispatch(uploadComposeRequest());
  188. for (const [i, f] of Array.from(files).entries()) {
  189. if (media.size + i > 3) break;
  190. resizeImage(f).then(file => {
  191. const data = new FormData();
  192. data.append('file', file);
  193. // Account for disparity in size of original image and resized data
  194. total += file.size - f.size;
  195. return api(getState).post('/api/v2/media', data, {
  196. onUploadProgress: function({ loaded }){
  197. progress[i] = loaded;
  198. dispatch(uploadComposeProgress(progress.reduce((a, v) => a + v, 0), total));
  199. },
  200. }).then(({ status, data }) => {
  201. // If server-side processing of the media attachment has not completed yet,
  202. // poll the server until it is, before showing the media attachment as uploaded
  203. if (status === 200) {
  204. dispatch(uploadComposeSuccess(data, f));
  205. } else if (status === 202) {
  206. const poll = () => {
  207. api(getState).get(`/api/v1/media/${data.id}`).then(response => {
  208. if (response.status === 200) {
  209. dispatch(uploadComposeSuccess(response.data, f));
  210. } else if (response.status === 206) {
  211. setTimeout(() => poll(), 1000);
  212. }
  213. }).catch(error => dispatch(uploadComposeFail(error)));
  214. };
  215. poll();
  216. }
  217. });
  218. }).catch(error => dispatch(uploadComposeFail(error)));
  219. };
  220. };
  221. };
  222. export const uploadThumbnail = (id, file) => (dispatch, getState) => {
  223. dispatch(uploadThumbnailRequest());
  224. const total = file.size;
  225. const data = new FormData();
  226. data.append('thumbnail', file);
  227. api(getState).put(`/api/v1/media/${id}`, data, {
  228. onUploadProgress: ({ loaded }) => {
  229. dispatch(uploadThumbnailProgress(loaded, total));
  230. },
  231. }).then(({ data }) => {
  232. dispatch(uploadThumbnailSuccess(data));
  233. }).catch(error => {
  234. dispatch(uploadThumbnailFail(id, error));
  235. });
  236. };
  237. export const uploadThumbnailRequest = () => ({
  238. type: THUMBNAIL_UPLOAD_REQUEST,
  239. skipLoading: true,
  240. });
  241. export const uploadThumbnailProgress = (loaded, total) => ({
  242. type: THUMBNAIL_UPLOAD_PROGRESS,
  243. loaded,
  244. total,
  245. skipLoading: true,
  246. });
  247. export const uploadThumbnailSuccess = media => ({
  248. type: THUMBNAIL_UPLOAD_SUCCESS,
  249. media,
  250. skipLoading: true,
  251. });
  252. export const uploadThumbnailFail = error => ({
  253. type: THUMBNAIL_UPLOAD_FAIL,
  254. error,
  255. skipLoading: true,
  256. });
  257. export function changeUploadCompose(id, params) {
  258. return (dispatch, getState) => {
  259. dispatch(changeUploadComposeRequest());
  260. api(getState).put(`/api/v1/media/${id}`, params).then(response => {
  261. dispatch(changeUploadComposeSuccess(response.data));
  262. }).catch(error => {
  263. dispatch(changeUploadComposeFail(id, error));
  264. });
  265. };
  266. };
  267. export function changeUploadComposeRequest() {
  268. return {
  269. type: COMPOSE_UPLOAD_CHANGE_REQUEST,
  270. skipLoading: true,
  271. };
  272. };
  273. export function changeUploadComposeSuccess(media) {
  274. return {
  275. type: COMPOSE_UPLOAD_CHANGE_SUCCESS,
  276. media: media,
  277. skipLoading: true,
  278. };
  279. };
  280. export function changeUploadComposeFail(error) {
  281. return {
  282. type: COMPOSE_UPLOAD_CHANGE_FAIL,
  283. error: error,
  284. skipLoading: true,
  285. };
  286. };
  287. export function uploadComposeRequest() {
  288. return {
  289. type: COMPOSE_UPLOAD_REQUEST,
  290. skipLoading: true,
  291. };
  292. };
  293. export function uploadComposeProgress(loaded, total) {
  294. return {
  295. type: COMPOSE_UPLOAD_PROGRESS,
  296. loaded: loaded,
  297. total: total,
  298. };
  299. };
  300. export function uploadComposeSuccess(media, file) {
  301. return {
  302. type: COMPOSE_UPLOAD_SUCCESS,
  303. media: media,
  304. file: file,
  305. skipLoading: true,
  306. };
  307. };
  308. export function uploadComposeFail(error) {
  309. return {
  310. type: COMPOSE_UPLOAD_FAIL,
  311. error: error,
  312. skipLoading: true,
  313. };
  314. };
  315. export function undoUploadCompose(media_id) {
  316. return {
  317. type: COMPOSE_UPLOAD_UNDO,
  318. media_id: media_id,
  319. };
  320. };
  321. export function clearComposeSuggestions() {
  322. if (cancelFetchComposeSuggestionsAccounts) {
  323. cancelFetchComposeSuggestionsAccounts();
  324. }
  325. return {
  326. type: COMPOSE_SUGGESTIONS_CLEAR,
  327. };
  328. };
  329. const fetchComposeSuggestionsAccounts = throttle((dispatch, getState, token) => {
  330. if (cancelFetchComposeSuggestionsAccounts) {
  331. cancelFetchComposeSuggestionsAccounts();
  332. }
  333. api(getState).get('/api/v1/accounts/search', {
  334. cancelToken: new CancelToken(cancel => {
  335. cancelFetchComposeSuggestionsAccounts = cancel;
  336. }),
  337. params: {
  338. q: token.slice(1),
  339. resolve: false,
  340. limit: 4,
  341. },
  342. }).then(response => {
  343. dispatch(importFetchedAccounts(response.data));
  344. dispatch(readyComposeSuggestionsAccounts(token, response.data));
  345. }).catch(error => {
  346. if (!isCancel(error)) {
  347. dispatch(showAlertForError(error));
  348. }
  349. });
  350. }, 200, { leading: true, trailing: true });
  351. const fetchComposeSuggestionsEmojis = (dispatch, getState, token) => {
  352. const results = emojiSearch(token.replace(':', ''), { maxResults: 5 });
  353. dispatch(readyComposeSuggestionsEmojis(token, results));
  354. };
  355. const fetchComposeSuggestionsTags = throttle((dispatch, getState, token) => {
  356. if (cancelFetchComposeSuggestionsTags) {
  357. cancelFetchComposeSuggestionsTags();
  358. }
  359. dispatch(updateSuggestionTags(token));
  360. api(getState).get('/api/v2/search', {
  361. cancelToken: new CancelToken(cancel => {
  362. cancelFetchComposeSuggestionsTags = cancel;
  363. }),
  364. params: {
  365. type: 'hashtags',
  366. q: token.slice(1),
  367. resolve: false,
  368. limit: 4,
  369. exclude_unreviewed: true,
  370. },
  371. }).then(({ data }) => {
  372. dispatch(readyComposeSuggestionsTags(token, data.hashtags));
  373. }).catch(error => {
  374. if (!isCancel(error)) {
  375. dispatch(showAlertForError(error));
  376. }
  377. });
  378. }, 200, { leading: true, trailing: true });
  379. export function fetchComposeSuggestions(token) {
  380. return (dispatch, getState) => {
  381. switch (token[0]) {
  382. case ':':
  383. fetchComposeSuggestionsEmojis(dispatch, getState, token);
  384. break;
  385. case '#':
  386. fetchComposeSuggestionsTags(dispatch, getState, token);
  387. break;
  388. default:
  389. fetchComposeSuggestionsAccounts(dispatch, getState, token);
  390. break;
  391. }
  392. };
  393. };
  394. export function readyComposeSuggestionsEmojis(token, emojis) {
  395. return {
  396. type: COMPOSE_SUGGESTIONS_READY,
  397. token,
  398. emojis,
  399. };
  400. };
  401. export function readyComposeSuggestionsAccounts(token, accounts) {
  402. return {
  403. type: COMPOSE_SUGGESTIONS_READY,
  404. token,
  405. accounts,
  406. };
  407. };
  408. export const readyComposeSuggestionsTags = (token, tags) => ({
  409. type: COMPOSE_SUGGESTIONS_READY,
  410. token,
  411. tags,
  412. });
  413. export function selectComposeSuggestion(position, token, suggestion, path) {
  414. return (dispatch, getState) => {
  415. let completion, startPosition;
  416. if (suggestion.type === 'emoji') {
  417. completion = suggestion.native || suggestion.colons;
  418. startPosition = position - 1;
  419. dispatch(useEmoji(suggestion));
  420. } else if (suggestion.type === 'hashtag') {
  421. completion = `#${suggestion.name}`;
  422. startPosition = position - 1;
  423. } else if (suggestion.type === 'account') {
  424. completion = getState().getIn(['accounts', suggestion.id, 'acct']);
  425. startPosition = position;
  426. }
  427. dispatch({
  428. type: COMPOSE_SUGGESTION_SELECT,
  429. position: startPosition,
  430. token,
  431. completion,
  432. path,
  433. });
  434. };
  435. };
  436. export function updateSuggestionTags(token) {
  437. return {
  438. type: COMPOSE_SUGGESTION_TAGS_UPDATE,
  439. token,
  440. };
  441. }
  442. export function updateTagHistory(tags) {
  443. return {
  444. type: COMPOSE_TAG_HISTORY_UPDATE,
  445. tags,
  446. };
  447. }
  448. export function hydrateCompose() {
  449. return (dispatch, getState) => {
  450. const me = getState().getIn(['meta', 'me']);
  451. const history = tagHistory.get(me);
  452. if (history !== null) {
  453. dispatch(updateTagHistory(history));
  454. }
  455. };
  456. }
  457. function insertIntoTagHistory(recognizedTags, text) {
  458. return (dispatch, getState) => {
  459. const state = getState();
  460. const oldHistory = state.getIn(['compose', 'tagHistory']);
  461. const me = state.getIn(['meta', 'me']);
  462. const names = recognizedTags.map(tag => text.match(new RegExp(`#${tag.name}`, 'i'))[0].slice(1));
  463. const intersectedOldHistory = oldHistory.filter(name => names.findIndex(newName => newName.toLowerCase() === name.toLowerCase()) === -1);
  464. names.push(...intersectedOldHistory.toJS());
  465. const newHistory = names.slice(0, 1000);
  466. tagHistory.set(me, newHistory);
  467. dispatch(updateTagHistory(newHistory));
  468. };
  469. }
  470. export function mountCompose() {
  471. return {
  472. type: COMPOSE_MOUNT,
  473. };
  474. };
  475. export function unmountCompose() {
  476. return {
  477. type: COMPOSE_UNMOUNT,
  478. };
  479. };
  480. export function changeComposeSensitivity() {
  481. return {
  482. type: COMPOSE_SENSITIVITY_CHANGE,
  483. };
  484. };
  485. export function changeComposeSpoilerness() {
  486. return {
  487. type: COMPOSE_SPOILERNESS_CHANGE,
  488. };
  489. };
  490. export function changeComposeSpoilerText(text) {
  491. return {
  492. type: COMPOSE_SPOILER_TEXT_CHANGE,
  493. text,
  494. };
  495. };
  496. export function changeComposeVisibility(value) {
  497. return {
  498. type: COMPOSE_VISIBILITY_CHANGE,
  499. value,
  500. };
  501. };
  502. export function insertEmojiCompose(position, emoji, needsSpace) {
  503. return {
  504. type: COMPOSE_EMOJI_INSERT,
  505. position,
  506. emoji,
  507. needsSpace,
  508. };
  509. };
  510. export function changeComposing(value) {
  511. return {
  512. type: COMPOSE_COMPOSING_CHANGE,
  513. value,
  514. };
  515. };
  516. export function addPoll() {
  517. return {
  518. type: COMPOSE_POLL_ADD,
  519. };
  520. };
  521. export function removePoll() {
  522. return {
  523. type: COMPOSE_POLL_REMOVE,
  524. };
  525. };
  526. export function addPollOption(title) {
  527. return {
  528. type: COMPOSE_POLL_OPTION_ADD,
  529. title,
  530. };
  531. };
  532. export function changePollOption(index, title) {
  533. return {
  534. type: COMPOSE_POLL_OPTION_CHANGE,
  535. index,
  536. title,
  537. };
  538. };
  539. export function removePollOption(index) {
  540. return {
  541. type: COMPOSE_POLL_OPTION_REMOVE,
  542. index,
  543. };
  544. };
  545. export function changePollSettings(expiresIn, isMultiple) {
  546. return {
  547. type: COMPOSE_POLL_SETTINGS_CHANGE,
  548. expiresIn,
  549. isMultiple,
  550. };
  551. };