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.

580 lines
16 KiB

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