Adrià Vilanova MartÃnez | 4677317 | 2024-01-10 21:44:22 +0100 | [diff] [blame] | 1 | import {parseView} from '../common/TWBasicUtils.js'; |
| 2 | import ThreadModel from '../models/Thread.js'; |
| 3 | |
| 4 | var CCThreadWithoutMessage = /forum\/[0-9]*\/thread\/[0-9]*$/; |
| 5 | |
| 6 | /** |
| 7 | * @returns {boolean} Whether the redirection was successful. |
| 8 | */ |
| 9 | export function redirectIfApplicable() { |
| 10 | if (window.TWPTShouldRedirect) { |
| 11 | let ok = redirectToCommunityConsoleV2(); |
| 12 | if (ok) return true; |
| 13 | |
| 14 | return redirectToCommunityConsoleV1(); |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | function redirectToCommunityConsoleV2() { |
| 19 | try { |
| 20 | const threadView = parseView('thread_view'); |
| 21 | if (!threadView) throw new Error('Could not find thread data.'); |
| 22 | |
| 23 | const thread = new ThreadModel(threadView); |
| 24 | const forumId = thread.getForumId(); |
| 25 | const threadId = thread.getId(); |
| 26 | |
| 27 | if (!forumId || !threadId) |
| 28 | throw new Error('Forum id and thread id not present in thread data.'); |
| 29 | |
| 30 | const searchParams = new URLSearchParams(location.search); |
| 31 | const msgId = searchParams.get('msgid'); |
| 32 | |
| 33 | const msgSuffix = msgId ? `/message/${msgId}` : ''; |
| 34 | const hash = window.TWPTRedirectHash ?? ''; |
| 35 | const url = |
| 36 | `/s/community/forum/${forumId}/thread/${threadId}${msgSuffix}${hash}`; |
| 37 | window.location = url; |
| 38 | return true; |
| 39 | } catch (err) { |
| 40 | console.error('Error redirecting to the Community Console (v2): ', err); |
| 41 | return false; |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | function redirectToCommunityConsoleV1() { |
| 46 | try { |
| 47 | const redirectLink = document.querySelector('.community-console'); |
| 48 | if (redirectLink === null) throw new Error('Could not find redirect link.'); |
| 49 | |
| 50 | let redirectUrl = redirectLink.href; |
| 51 | |
| 52 | const searchParams = new URLSearchParams(location.search); |
| 53 | if (searchParams.has('msgid') && searchParams.get('msgid') !== '' && |
| 54 | CCThreadWithoutMessage.test(redirectUrl)) { |
| 55 | redirectUrl += |
| 56 | '/message/' + encodeURIComponent(searchParams.get('msgid')); |
| 57 | } |
| 58 | redirectUrl += window.TWPTRedirectHash ?? ''; |
| 59 | |
| 60 | window.location = redirectUrl; |
| 61 | return true; |
| 62 | } catch (err) { |
| 63 | console.error('Error redirecting to the Community Console (v1): ', err); |
| 64 | return false; |
| 65 | } |
| 66 | } |