Split browser-only version into a separate branch & update README

This commit is contained in:
chylex 2022-03-20 15:48:13 +01:00
parent 8f7b566db7
commit f3723ee43b
No known key found for this signature in database
GPG Key ID: 4DE42C8F19A80548
34 changed files with 23 additions and 5251 deletions

52
.vscode/tasks.json vendored
View File

@ -1,52 +0,0 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Build Raw",
"type": "shell",
"command": "python ./build.py --nominify --copytracker",
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"reveal": "always",
"panel": "shared",
"echo": true,
"focus": false,
"showReuseMessage": false
},
"problemMatcher": []
},
{
"label": "Build Minified",
"type": "shell",
"command": "python ./build.py --copytracker",
"group": "build",
"presentation": {
"reveal": "always",
"panel": "shared",
"echo": true,
"focus": false,
"showReuseMessage": false
},
"problemMatcher": []
},
{
"label": "Build Website",
"type": "shell",
"command": "python ./build.py --website",
"group": "build",
"presentation": {
"reveal": "always",
"panel": "shared",
"echo": true,
"focus": false,
"showReuseMessage": false
},
"problemMatcher": []
}
]
}

View File

@ -1,48 +1,32 @@
# Welcome
All you need to **use Discord History Tracker** is either an up-to-date browser, or the [Discord desktop client](https://discord.com/download). Visit the [official website](https://dht.chylex.com) for instructions.
For instructions on how to **use Discord History Tracker**, visit the [official website](https://dht.chylex.com).
To **report an issue or suggestion**, first please see the [issues](https://github.com/chylex/Discord-History-Tracker/issues) page and make sure someone else hasn't already created a similar issue report. If you do find an existing issue, comment on it or add a reaction. Otherwise, either click [New Issue](https://github.com/chylex/Discord-History-Tracker/issues/new), or contact me via email [contact@chylex.com](mailto:contact@chylex.com) or Twitter [@chylexmc](https://twitter.com/chylexmc).
If you are interested in **creating your own version** from the source code, continue reading the [build instructions](#Build-Instructions) below.
If you are interested in **building from source code**, continue reading the [build instructions](#Build-Instructions) below.
This branch is dedicated to the Discord History Tracker desktop app. If you are looking for the older browser-only version, visit the [master-browser-only](https://github.com/chylex/Discord-History-Tracker/tree/master-browser-only) branch.
# Build Instructions
Follow the steps below to create your own version of Discord History Tracker.
### Setup
Fork the repository and clone it to your computer (if you've never used git, you can download the [GitHub Desktop](https://desktop.github.com) client to get started quickly).
Now you can modify the source code:
* `src/tracker/` contains JS files that are automatically combined into the **tracker bookmark/script**
* `src/viewer/` contains HTML, CSS, JS files that are then combined into the **offline viewer page**
Folder organization:
* `app/` contains a Visual Studio solution for the desktop app
* `lib/` contains utilities required to build the project
* `web/` contains source code of the [official website](https://dht.chylex.com), which can be used as a template when making your own website
To start editing source code for the desktop app, open `app/DiscordHistoryTracker.sln` in [Visual Studio](https://visualstudio.microsoft.com/downloads/) or [Rider](https://www.jetbrains.com/rider/).
### Building
After you've done changes to the source code, you will need to build it. Before that, download and install:
* (**required**) [Python 3](https://www.python.org/downloads)
* Use to run the build script
* (optional) [Node + npm](https://nodejs.org/en) & command line [uglify-js](https://www.npmjs.com/package/uglify-js)
* Not required on Windows
* Only required for optional [JS minification](#Minification) on Linux/Mac
To build a `Debug` version of the desktop app, there are no additional requirements.
Now open the folder that contains `build.py` in a command line, and run `python build.py` to create a build with default settings. The following files will be created:
* `bld/track.js` is the raw tracker script that can be pasted into a browser console
* `bld/track.html` is the tracker script but sanitized for inclusion in HTML (see `web/index.php` for examples)
* `bld/viewer.html` is the complete offline viewer
To build a `Release` version of the desktop app, you will need [Python 3](https://www.python.org/downloads), which is used by the build process to launch `app/Resources/minify.py` script.
You can tweak the build process using the following flags:
* `python build.py --nominify` to disable [minification](#Minification)
When creating `Release` builds on systems other than 64-bit Windows, you will also need [Node + npm](https://nodejs.org/en), and [uglify-js](https://www.npmjs.com/package/uglify-js) installed globally (`npm install uglify-js -g`). On 64-bit Windows, both Node and uglify-js are already included in the `lib/` folder for convenience.
### Minification
The build process automatically minifies JS using `UglifyJS@3`, and CSS using a custom minifier.
* If the `--nominify` flag is used, minification will be completely disabled
* If `uglify-js` is not available from the command line, JS minification will be skipped
* When building on Windows 64-bit, the build script will use the included Node runner and packages
* When building on Windows 32-bit, you will need to download [Node 32-bit](https://nodejs.org/en/download) and replace the included one in `lib/`
* When building on Linux/Mac, the build script will attempt to find `uglifyjs` in the command line
To create `Release` builds ready for distribution, run the `app/build.bat` script on Windows, or `app/build.sh` script on other operating systems. This will create self-contained executables for each major operating system, and a portable version that works on all other systems but requires .NET 5 to be installed. All builds are placed in the `app/bin` folder.

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

225
build.py
View File

@ -1,225 +0,0 @@
# Python 3
import fileinput
import glob
import shutil
import sys
import os
import re
import distutils.dir_util
VERSION_SHORT = "v.31a"
VERSION_FULL = VERSION_SHORT + ", released 12 Feb 2022"
EXEC_UGLIFYJS_WIN = "{2}/lib/uglifyjs.cmd --parse bare_returns --compress --mangle toplevel --mangle-props keep_quoted,reserved=[{3}] --output \"{1}\" \"{0}\""
EXEC_UGLIFYJS_AUTO = "uglifyjs --parse bare_returns --compress --mangle toplevel --mangle-props keep_quoted,reserved=[{3}] --output \"{1}\" \"{0}\""
USE_UGLIFYJS = "--nominify" not in sys.argv
USE_MINIFICATION = "--nominify" not in sys.argv
BUILD_WEBSITE = "--website" in sys.argv
CLIPBOARD_TRACKER = "--copytracker" in sys.argv
WORKING_DIR = os.getcwd()
# UglifyJS Setup
if os.name == "nt":
EXEC_UGLIFYJS = EXEC_UGLIFYJS_WIN
else:
EXEC_UGLIFYJS = EXEC_UGLIFYJS_AUTO
if USE_UGLIFYJS and shutil.which("uglifyjs") is None:
USE_UGLIFYJS = False
print("Could not find 'uglifyjs', JS minification will be disabled")
if USE_UGLIFYJS:
with open("reserve.txt", "r") as reserved:
RESERVED_PROPS = ",".join(line.strip() for line in reserved.readlines())
# File Utilities
def combine_files(input_pattern, output_file):
is_first_file = True
with fileinput.input(sorted(glob.glob(input_pattern))) as stream:
for line in stream:
if stream.isfirstline():
if is_first_file:
is_first_file = False
else:
output_file.write("\n")
output_file.write(line.replace("{{{version:full}}}", VERSION_FULL))
def minify_css(input_file, output_file):
if not USE_MINIFICATION:
if input_file != output_file:
shutil.copyfile(input_file, output_file)
return
with open(input_file, "r") as fin:
css = fin.read()
css = re.sub(r"^\s+(.+?):\s*(.+?)(?:\s*(!important))?;\n", r"\1:\2\3;", css, flags = re.M) # remove spaces after colons
css = re.sub(r"\{\n", r"{", css, flags = re.M) # remove new lines after {
css = re.sub(r"\n\}", r"}", css, flags = re.M) # remove new lines before }
css = re.sub(r"\n\n", r"\n", css, flags = re.M) # remove empty lines
css = re.sub(r";\}$", r"}", css, flags = re.M) # remove last semicolons
css = re.sub(r"rgb\((.*?),\s*(.*?),\s*(.*?)\)", r"rgb(\1,\2,\3)", css, flags = re.M) # remove spaces after commas in rgb()
css = re.sub(r"rgba\((.*?),\s*(.*?),\s*(.*?),\s*(.*?)\)", r"rgba(\1,\2,\3,\4)", css, flags = re.M) # remove spaces after commas in rgba()
with open(output_file, "w") as out:
out.write(css)
# Build System
def build_tracker_html():
output_file_raw = "bld/track.js"
output_file_html = "bld/track.html"
output_file_tmp = "bld/track.tmp.js"
input_pattern = "src/tracker/*.js"
with open(output_file_raw, "w") as out:
if not USE_UGLIFYJS:
out.write("(function(){\n")
combine_files(input_pattern, out)
if not USE_UGLIFYJS:
out.write("})()")
if USE_UGLIFYJS:
os.system(EXEC_UGLIFYJS.format(output_file_raw, output_file_tmp, WORKING_DIR, RESERVED_PROPS))
with open(output_file_raw, "w") as out:
out.write("javascript:(function(){")
with open(output_file_tmp, "r") as minified:
out.write(minified.read().replace("\n", " ").replace("\r", ""))
out.write("})()")
os.remove(output_file_tmp)
with open(output_file_raw, "r") as raw:
script_contents = raw.read().replace("&", "&amp;").replace('"', "&quot;").replace("'", "&#x27;").replace("<", "&lt;").replace(">", "&gt;")
with open(output_file_html, "w") as out:
out.write(script_contents)
def build_tracker_userscript():
output_file = "bld/track.user.js"
input_pattern = "src/tracker/*.js"
userscript_base = "src/base/track.user.js"
with open(userscript_base, "r") as base:
userscript_contents = base.read().replace("{{{version}}}", VERSION_SHORT).split("{{{contents}}}")
with open(output_file, "w") as out:
out.write(userscript_contents[0])
combine_files(input_pattern, out)
out.write(userscript_contents[1])
def build_viewer():
output_file = "bld/viewer.html"
input_html = "src/viewer/index.html"
input_css_pattern = "src/viewer/styles/*.css"
tmp_css_file_combined = "bld/viewer.tmp.css"
tmp_css_file_minified = "bld/viewer.min.css"
with open(tmp_css_file_combined, "w") as out:
combine_files(input_css_pattern, out)
minify_css(tmp_css_file_combined, tmp_css_file_minified)
os.remove(tmp_css_file_combined)
input_js_pattern = "src/viewer/scripts/*.js"
tmp_js_file_combined = "bld/viewer.tmp.js"
tmp_js_file_minified = "bld/viewer.min.js"
with open(tmp_js_file_combined, "w") as out:
combine_files(input_js_pattern, out)
if USE_UGLIFYJS:
os.system(EXEC_UGLIFYJS.format(tmp_js_file_combined, tmp_js_file_minified, WORKING_DIR, RESERVED_PROPS))
else:
shutil.copyfile(tmp_js_file_combined, tmp_js_file_minified)
os.remove(tmp_js_file_combined)
tokens = {
"/*{js}*/": tmp_js_file_minified,
"/*{css}*/": tmp_css_file_minified
}
with open(output_file, "w") as out:
with open(input_html, "r") as fin:
for line in fin:
token = None
for token in (token for token in tokens if token in line):
with open(tokens[token], "r") as token_file:
embedded = token_file.read()
out.write(embedded)
os.remove(tokens[token])
if token is None:
out.write(line)
def build_website():
tracker_file_html = "bld/track.html"
tracker_file_userscript = "bld/track.user.js"
viewer_file = "bld/viewer.html"
web_style_file = "bld/web/style.css"
distutils.dir_util.copy_tree("web", "bld/web")
index_file = "bld/web/index.php"
with open(index_file, "r") as index:
index_contents = index.read()
with open(index_file, "w") as index:
index.write(index_contents.replace("{{{version:web}}}", VERSION_SHORT.replace(" ", "&nbsp;")))
shutil.copyfile(tracker_file_html, "bld/web/build/track.html")
shutil.copyfile(tracker_file_userscript, "bld/web/build/track.user.js")
shutil.copyfile(viewer_file, "bld/web/build/viewer.html")
minify_css(web_style_file, web_style_file)
# Build Process
os.makedirs("bld", exist_ok = True)
print("Building tracker html...")
build_tracker_html()
print("Building tracker userscript...")
build_tracker_userscript()
print("Building viewer...")
build_viewer()
if BUILD_WEBSITE:
print("Building website...")
build_website()
if CLIPBOARD_TRACKER:
if os.name == "nt":
print("Copying to clipboard...")
os.system("clip < bld/track.js")
else:
print("Clipboard is only supported on Windows")
print("Done")

View File

@ -1,73 +0,0 @@
autoscroll
_autoscroll
afterFirstMsg
_afterFirstMsg
afterSavedMsg
_afterSavedMsg
enableImagePreviews
_enableImagePreviews
enableFormatting
_enableFormatting
enableAnimatedEmoji
_enableAnimatedEmoji
enableUserAvatars
_enableUserAvatars
DHT_LOADED
DHT_EMBEDDED
meta
data
users
userindex
servers
channels
u
t
m
f
e
a
t
te
d
r
re
c
n
an
tag
avatar
author
type
state
name
position
topic
nsfw
id
username
bot
discriminator
timestamp
content
editedTimestamp
mentions
embeds
attachments
title
description
reply
reactions
emoji
count
animated
ext
toDate
memoizedProps
props
children
channel
messages
msSaveBlob
messageReference
message_id
guild_id

View File

@ -1,50 +0,0 @@
// ==UserScript==
// @name Discord History Tracker
// @version {{{version}}}
// @license MIT
// @namespace https://chylex.com
// @homepageURL https://dht.chylex.com/
// @supportURL https://github.com/chylex/Discord-History-Tracker/issues
// @include https://discord.com/*
// @run-at document-idle
// @grant none
// ==/UserScript==
const start = function(){
{{{contents}}}
};
const css = document.createElement("style");
css.innerText = `
#dht-userscript-trigger { cursor: pointer; margin-top: 5px }
#dht-userscript-trigger svg { opacity: 0.6 }
#dht-userscript-trigger:hover svg { opacity: 1 }
`;
document.head.appendChild(css);
window.setInterval(function(){
if (document.getElementById("dht-userscript-trigger")){
return;
}
const help = document.querySelector("section[class^='title'] a[href*='support.discord.com']");
if (help){
help.insertAdjacentHTML("afterend", `
<span id="dht-userscript-trigger">
<span style="margin: 0 4px" role="button">
<svg width="28" height="16" viewBox="0 0 11 6" fill="#fff">
<path d="M3.133,2.848c0,0.355 -0.044,0.668 -0.132,0.937c-0.088,0.27 -0.208,0.495 -0.36,0.677c-0.153,0.181 -0.333,0.319 -0.541,0.412c-0.207,0.092 -0.431,0.139 -0.672,0.139l-1.413,0l0,-4.266l1.265,0c0.27,0 0.519,0.042 0.746,0.124c0.227,0.083 0.423,0.21 0.586,0.382c0.164,0.171 0.291,0.389 0.383,0.654c0.092,0.264 0.138,0.578 0.138,0.941Zm-0.739,0c0,-0.248 -0.028,-0.461 -0.083,-0.639c-0.056,-0.177 -0.133,-0.323 -0.232,-0.437c-0.099,-0.114 -0.217,-0.198 -0.355,-0.253c-0.139,-0.054 -0.292,-0.082 -0.459,-0.082l-0.518,0l0,2.886l0.621,0c0.147,0 0.283,-0.032 0.409,-0.094c0.125,-0.063 0.233,-0.156 0.325,-0.28c0.092,-0.124 0.163,-0.278 0.215,-0.462c0.051,-0.184 0.077,-0.397 0.077,-0.639Z"></path>
<path d="M5.939,5.013l0,-1.829l-1.523,0l0,1.829l-0.732,0l0,-4.266l0.732,0l0,1.699l1.523,0l0,-1.699l0.733,0l0,4.266l-0.733,0Z"></path>
<path d="M8.933,1.437l0,3.576l-0.732,0l0,-3.576l-1.13,0l0,-0.69l2.994,0l0,0.69l-1.132,0Z"></path>
</svg>
</span>
</span>`);
document.getElementById("dht-userscript-trigger").addEventListener("click", start);
}
}, 200);

View File

@ -1,312 +0,0 @@
var DISCORD = (function(){
var getMessageOuterElement = function(){
return DOM.queryReactClass("messagesWrapper");
};
var getMessageScrollerElement = function(){
return getMessageOuterElement().querySelector("[class*='scroller-']");
};
var getMessageElements = function() {
return getMessageOuterElement().querySelectorAll("[class*='message-']");
};
var getReactProps = function(ele) {
var keys = Object.keys(ele || {});
var key = keys.find(key => key.startsWith("__reactInternalInstance"));
if (key){
return ele[key].memoizedProps;
}
key = keys.find(key => key.startsWith("__reactProps$"));
return key ? ele[key] : null;
};
var getMessageElementProps = function(ele) {
const props = getReactProps(ele);
if (props.children && props.children.length >= 4) {
const childProps = props.children[3].props;
if ("message" in childProps && "channel" in childProps) {
return childProps;
}
}
return null;
};
var hasMoreMessages = function() {
return document.querySelector("#messagesNavigationDescription + [class^=container]") === null;
};
var getMessages = function() {
try {
const messages = [];
for (const ele of getMessageElements()) {
const props = getMessageElementProps(ele);
if (props != null) {
messages.push(props.message);
}
}
return messages;
} catch (e) {
console.error(e);
return [];
}
};
return {
/**
* Calls the provided function with a list of messages whenever the currently loaded messages change,
* or with `false` if there are no more messages.
*/
setupMessageCallback: function(callback) {
let skipsLeft = 0;
let waitForCleanup = false;
let hasReachedStart = false;
const previousMessages = new Set();
const intervalId = window.setInterval(() => {
if (skipsLeft > 0) {
--skipsLeft;
return;
}
const view = getMessageOuterElement();
if (!view) {
skipsLeft = 2;
return;
}
const anyMessage = DOM.queryReactClass("message", getMessageOuterElement());
const messageCount = anyMessage ? anyMessage.parentElement.children.length : 0;
if (messageCount > 300) {
if (waitForCleanup) {
return;
}
skipsLeft = 3;
waitForCleanup = true;
window.setTimeout(() => {
const view = getMessageScrollerElement();
view.scrollTop = view.scrollHeight / 2;
}, 1);
}
else {
waitForCleanup = false;
}
const messages = getMessages();
let hasChanged = false;
for (const message of messages) {
if (!previousMessages.has(message.id)) {
hasChanged = true;
break;
}
}
if (!hasChanged) {
if (!hasReachedStart && !hasMoreMessages()) {
hasReachedStart = true;
callback(false);
}
return;
}
previousMessages.clear();
for (const message of messages) {
previousMessages.add(message.id);
}
hasReachedStart = false;
callback(messages);
}, 200);
window.DHT_ON_UNLOAD.push(() => window.clearInterval(intervalId));
},
/*
* Returns internal React state object of an element.
*/
getReactProps: function(ele){
return getReactProps(ele);
},
/*
* Returns an object containing the selected server name, selected channel name and ID, and the object type.
* For types DM and GROUP, the server and channel names are identical.
* For SERVER type, the channel has to be in view, otherwise Discord unloads it.
*/
getSelectedChannel: function() {
try {
let obj;
for (const ele of getMessageElements()) {
const props = getMessageElementProps(ele);
if (props != null) {
obj = props.channel;
break;
}
}
if (!obj) {
return null;
}
var dms = DOM.queryReactClass("privateChannels");
if (dms){
let name;
for (const ele of dms.querySelectorAll("[class*='channel-'] [class*='selected-'] [class^='name-'] *, [class*='channel-'][class*='selected-'] [class^='name-'] *")) {
const node = Array.prototype.find.call(ele.childNodes, node => node.nodeType === Node.TEXT_NODE);
if (node) {
name = node.nodeValue;
break;
}
}
if (!name) {
return null;
}
let type;
// https://discord.com/developers/docs/resources/channel#channel-object-channel-types
switch (obj.type) {
case 1: type = "DM"; break;
case 3: type = "GROUP"; break;
default: return null;
}
return {
"server": name,
"channel": name,
"id": obj.id,
"type": type,
"extra": {}
};
}
else if (obj.guild_id) {
return {
"server": document.querySelector("nav header > h1").innerText,
"channel": obj.name,
"id": obj.id,
"type": "SERVER",
"extra": {
"position": obj.position,
"topic": obj.topic,
"nsfw": obj.nsfw
}
};
}
else {
return null;
}
} catch(e) {
console.error(e);
return null;
}
},
/*
* Returns an array containing currently loaded messages.
*/
getMessages: function(){
return getMessages();
},
/*
* Returns true if the message view is visible.
*/
isInMessageView: () => !!getMessageOuterElement(),
/*
* Returns true if there are more messages available or if they're still loading.
*/
hasMoreMessages: function(){
return hasMoreMessages();
},
/*
* Forces the message view to load older messages by scrolling all the way up.
*/
loadOlderMessages: function(){
let view = getMessageScrollerElement();
if (view.scrollTop > 0){
view.scrollTop = 0;
}
},
/*
* Selects the next text channel and returns true, otherwise returns false if there are no more channels.
*/
selectNextTextChannel: function(){
var dms = DOM.queryReactClass("privateChannels");
if (dms){
var currentChannel = DOM.queryReactClass("selected", dms);
var nextChannel = currentChannel && currentChannel.nextElementSibling;
if (!nextChannel || !nextChannel.getAttribute("class").includes("channel-") || !("href" in nextChannel) || !nextChannel.href.includes("/@me/")){
return false;
}
else{
nextChannel.click();
nextChannel.scrollIntoView(true);
return true;
}
}
else{
var channelIconNormal = "M5.88657 21C5.57547 21 5.3399 20.7189 5.39427 20.4126L6.00001 17H2.59511C2.28449 17 2.04905 16.7198 2.10259 16.4138L2.27759 15.4138C2.31946 15.1746 2.52722 15 2.77011 15H6.35001L7.41001 9H4.00511C3.69449 9 3.45905 8.71977 3.51259 8.41381L3.68759 7.41381C3.72946 7.17456 3.93722 7 4.18011 7H7.76001L8.39677 3.41262C8.43914 3.17391 8.64664 3 8.88907 3H9.87344C10.1845 3 10.4201 3.28107 10.3657 3.58738L9.76001 7H15.76L16.3968 3.41262C16.4391 3.17391 16.6466 3 16.8891 3H17.8734C18.1845 3 18.4201 3.28107 18.3657 3.58738L17.76 7H21.1649C21.4755 7 21.711 7.28023 21.6574 7.58619L21.4824 8.58619C21.4406 8.82544 21.2328 9 20.9899 9H17.41L16.35 15H19.7549C20.0655 15 20.301 15.2802 20.2474 15.5862L20.0724 16.5862C20.0306 16.8254 19.8228 17 19.5799 17H16L15.3632 20.5874C15.3209 20.8261 15.1134 21 14.8709 21H13.8866C13.5755 21 13.3399 20.7189 13.3943 20.4126L14 17H8.00001L7.36325 20.5874C7.32088 20.8261 7.11337 21 6.87094 21H5.88657ZM9.41045 9L8.35045 15H14.3504L15.4104 9H9.41045Z";
var channelIconSpecial = "M14 8C14 7.44772 13.5523 7 13 7H9.76001L10.3657 3.58738C10.4201 3.28107 10.1845 3 9.87344 3H8.88907C8.64664 3 8.43914 3.17391 8.39677 3.41262L7.76001 7H4.18011C3.93722 7 3.72946 7.17456 3.68759 7.41381L3.51259 8.41381C3.45905 8.71977 3.69449 9 4.00511 9H7.41001L6.35001 15H2.77011C2.52722 15 2.31946 15.1746 2.27759 15.4138L2.10259 16.4138C2.04905 16.7198 2.28449 17 2.59511 17H6.00001L5.39427 20.4126C5.3399 20.7189 5.57547 21 5.88657 21H6.87094C7.11337 21 7.32088 20.8261 7.36325 20.5874L8.00001 17H14L13.3943 20.4126C13.3399 20.7189 13.5755 21 13.8866 21H14.8709C15.1134 21 15.3209 20.8261 15.3632 20.5874L16 17H19.5799C19.8228 17 20.0306 16.8254 20.0724 16.5862L20.2474 15.5862C20.301 15.2802 20.0655 15 19.7549 15H16.35L16.6758 13.1558C16.7823 12.5529 16.3186 12 15.7063 12C15.2286 12 14.8199 12.3429 14.7368 12.8133L14.3504 15H8.35045L9.41045 9H13C13.5523 9 14 8.55228 14 8Z";
var isValidChannelClass = cls => cls.includes("wrapper-") && !cls.includes("clickable-");
var isValidChannelType = ele => !!ele.querySelector('path[d="' + channelIconNormal + '"]') || !!ele.querySelector('path[d="' + channelIconSpecial + '"]');
var isValidChannel = ele => ele.childElementCount > 0 && isValidChannelClass(ele.children[0].className) && isValidChannelType(ele);
var channelListEle = document.querySelector("div[class*='sidebar'] > nav[class*='container'] > div[class*='scroller']");
if (!channelListEle){
return false;
}
var allChannels = Array.prototype.filter.call(channelListEle.querySelectorAll("[class*='containerDefault']"), isValidChannel);
var nextChannel = null;
for(var index = 0; index < allChannels.length-1; index++){
if (allChannels[index].children[0].className.includes("modeSelected")){
nextChannel = allChannels[index+1];
break;
}
}
if (nextChannel === null){
return false;
}
const nextChannelLink = nextChannel.querySelector("a[href^='/channels/']");
if (!nextChannelLink) {
return false;
}
nextChannelLink.click();
nextChannel.scrollIntoView(true);
return true;
}
}
};
})();

View File

@ -1,85 +0,0 @@
var DOM = (function(){
var createElement = (tag, parent, id, html) => {
var ele = document.createElement(tag);
ele.id = id || "";
ele.innerHTML = html || "";
parent.appendChild(ele);
return ele;
};
return {
/*
* Returns a child element by its ID. Parent defaults to the entire document.
*/
id: (id, parent) => (parent || document).getElementById(id),
/*
* Returns the first child element containing the specified obfuscated class. Parent defaults to the entire document.
*/
queryReactClass: (cls, parent) => (parent || document).querySelector(`[class*="${cls}-"]`),
/*
* Creates an element, adds it to the DOM, and returns it.
*/
createElement: (tag, parent, id, html) => createElement(tag, parent, id, html),
/*
* Removes an element from the DOM.
*/
removeElement: (ele) => ele.parentNode.removeChild(ele),
/*
* Creates a new style element with the specified CSS and returns it.
*/
createStyle: (styles) => createElement("style", document.head, "", styles),
/*
* Convenience setTimeout function to save space after minification.
*/
setTimer: (callback, timeout) => window.setTimeout(callback, timeout),
/*
* Convenience addEventListener function to save space after minification.
*/
listen: (ele, event, callback) => ele.addEventListener(event, callback),
/*
* Utility function to save an object into a cookie.
*/
saveToCookie: (name, obj, expiresInSeconds) => {
var expires = new Date(Date.now()+1000*expiresInSeconds).toUTCString();
document.cookie = name+"="+encodeURIComponent(JSON.stringify(obj))+";path=/;expires="+expires;
},
/*
* Utility function to load an object from a cookie.
*/
loadFromCookie: (name) => {
var value = document.cookie.replace(new RegExp("(?:(?:^|.*;\\s*)"+name+"\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1");
return value.length ? JSON.parse(decodeURIComponent(value)) : null;
},
/*
* Triggers a UTF-8 text file download.
*/
downloadTextFile: (fileName, fileContents) => {
var blob = new Blob([fileContents], { "type": "octet/stream" });
if ("msSaveBlob" in window.navigator){
return window.navigator.msSaveBlob(blob, fileName);
}
var url = window.URL.createObjectURL(blob);
var ele = createElement("a", document.body);
ele.href = url;
ele.download = fileName;
ele.style.display = "none";
ele.click();
document.body.removeChild(ele);
window.URL.revokeObjectURL(url);
}
};
})();

View File

@ -1,277 +0,0 @@
var GUI = (function(){
var controller;
var settings;
var updateButtonState = () => {
if (STATE.isTracking()){
controller.ui.btnUpload.disabled = true;
controller.ui.btnSettings.disabled = true;
controller.ui.btnReset.disabled = true;
}
else{
controller.ui.btnUpload.disabled = false;
controller.ui.btnSettings.disabled = false;
controller.ui.btnDownload.disabled = controller.ui.btnReset.disabled = !STATE.hasSavedData();
}
};
var stateChangedEvent = (type, detail) => {
if (controller){
var force = type === "gui" && detail === "controller";
if (type === "data" || force){
updateButtonState();
}
if (type === "tracking" || force){
updateButtonState();
controller.ui.btnToggleTracking.innerHTML = STATE.isTracking() ? "Pause Tracking" : "Start Tracking";
}
if (type === "data" || force){
var messageCount = 0;
var channelCount = 0;
if (STATE.hasSavedData()){
messageCount = STATE.getSavefile().countMessages();
channelCount = STATE.getSavefile().countChannels();
}
controller.ui.textStatus.innerHTML = [
messageCount, " message", (messageCount === 1 ? "" : "s"),
" from ",
channelCount, " channel", (channelCount === 1 ? "" : "s")
].join("");
}
}
if (settings){
var force = type === "gui" && detail === "settings";
if (force){
settings.ui.cbAutoscroll.checked = SETTINGS.autoscroll;
settings.ui.optsAfterFirstMsg[SETTINGS.afterFirstMsg].checked = true;
settings.ui.optsAfterSavedMsg[SETTINGS.afterSavedMsg].checked = true;
}
if (type === "setting" || force){
var autoscrollRev = !SETTINGS.autoscroll;
// discord polyfills Object.values
Object.values(settings.ui.optsAfterFirstMsg).forEach(ele => ele.disabled = autoscrollRev);
Object.values(settings.ui.optsAfterSavedMsg).forEach(ele => ele.disabled = autoscrollRev);
}
}
};
var registeredEvent = false;
var setupStateChanged = function(detail){
if (!registeredEvent){
STATE.onStateChanged(stateChangedEvent);
SETTINGS.onSettingsChanged(stateChangedEvent);
registeredEvent = true;
}
stateChangedEvent("gui", detail);
};
var root = {
showController: function(){
controller = {};
// styles
controller.styles = DOM.createStyle(`
#app-mount > div[class*="app-"] { margin-bottom: 48px !important; }
#dht-ctrl { position: absolute; bottom: 0; width: 100%; height: 48px; background-color: #FFF; }
#dht-ctrl button { height: 32px; margin: 8px 0 8px 8px; font-size: 16px; padding: 0 12px; background-color: #7289DA; color: #FFF; text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.75); }
#dht-ctrl button:disabled { background-color: #7A7A7A; cursor: default; }
#dht-ctrl-close { margin: 8px 8px 8px 0 !important; float: right; }
#dht-ctrl p { display: inline-block; margin: 14px 12px; }
#dht-ctrl input { display: none; }`);
// main
var btn = (id, title) => "<button id='dht-ctrl-"+id+"'>"+title+"</button>";
controller.ele = DOM.createElement("div", document.body, "dht-ctrl", `
${btn("upload", "Upload &amp; Combine")}
${btn("settings", "Settings")}
${btn("track", "")}
${btn("download", "Download")}
${btn("reset", "Reset")}
<p id='dht-ctrl-status'></p>
<input id='dht-ctrl-upload-input' type='file' multiple>
${btn("close", "X")}`);
// elements
controller.ui = {
btnUpload: DOM.id("dht-ctrl-upload"),
btnSettings: DOM.id("dht-ctrl-settings"),
btnToggleTracking: DOM.id("dht-ctrl-track"),
btnDownload: DOM.id("dht-ctrl-download"),
btnReset: DOM.id("dht-ctrl-reset"),
btnClose: DOM.id("dht-ctrl-close"),
textStatus: DOM.id("dht-ctrl-status"),
inputUpload: DOM.id("dht-ctrl-upload-input")
};
// events
DOM.listen(controller.ui.btnUpload, "click", () => {
controller.ui.inputUpload.click();
});
DOM.listen(controller.ui.btnSettings, "click", () => {
root.showSettings();
});
DOM.listen(controller.ui.btnToggleTracking, "click", () => {
STATE.setIsTracking(!STATE.isTracking());
});
DOM.listen(controller.ui.btnDownload, "click", () => {
STATE.downloadSavefile();
});
DOM.listen(controller.ui.btnReset, "click", () => {
STATE.resetState();
});
DOM.listen(controller.ui.btnClose, "click", () => {
root.hideController();
window.DHT_ON_UNLOAD.forEach(f => f());
window.DHT_LOADED = false;
});
DOM.listen(controller.ui.inputUpload, "change", () => {
Array.prototype.forEach.call(controller.ui.inputUpload.files, file => {
var reader = new FileReader();
reader.onload = function(){
var obj = {};
try{
obj = JSON.parse(reader.result);
}catch(e){
alert("Could not parse '"+file.name+"', see console for details.");
console.error(e);
return;
}
if (SAVEFILE.isValid(obj)){
STATE.uploadSavefile(file.name, new SAVEFILE(obj));
}
else{
alert("File '"+file.name+"' has an invalid format.");
}
};
reader.readAsText(file, "UTF-8");
});
controller.ui.inputUpload.value = null;
});
setupStateChanged("controller");
},
hideController: function(){
if (controller){
DOM.removeElement(controller.ele);
DOM.removeElement(controller.styles);
controller = null;
}
},
showSettings: function(){
settings = {};
// styles
settings.styles = DOM.createStyle(`
#dht-cfg-overlay { position: absolute; left: 0; top: 0; width: 100%; height: 100%; background-color: #000; opacity: 0.5; display: block; z-index: 1000; }
#dht-cfg { position: absolute; left: 50%; top: 50%; width: 800px; height: 262px; margin-left: -400px; margin-top: -131px; padding: 8px; background-color: #fff; z-index: 1001; }
#dht-cfg-note { margin-top: 22px; }
#dht-cfg sub { color: #666; font-size: 13px; }`);
// overlay
settings.overlay = DOM.createElement("div", document.body, "dht-cfg-overlay");
DOM.listen(settings.overlay, "click", () => {
root.hideSettings();
});
// main
var radio = (type, id, label) => "<label><input id='dht-cfg-"+type+"-"+id+"' name='dht-"+type+"' type='radio'> "+label+"</label><br>";
settings.ele = DOM.createElement("div", document.body, "dht-cfg", `
<label><input id='dht-cfg-autoscroll' type='checkbox'> Autoscroll</label><br>
<br>
<label>After reaching the first message in channel...</label><br>
${radio("afm", "nothing", "Do Nothing")}
${radio("afm", "pause", "Pause Tracking")}
${radio("afm", "switch", "Switch to Next Channel")}
<br>
<label>After reaching a previously saved message...</label><br>
${radio("asm", "nothing", "Do Nothing")}
${radio("asm", "pause", "Pause Tracking")}
${radio("asm", "switch", "Switch to Next Channel")}
<p id='dht-cfg-note'>
It is recommended to disable link and image previews to avoid putting unnecessary strain on your browser.<br><br>
<sub>{{{version:full}}}</sub>
</p>`);
// elements
settings.ui = {
cbAutoscroll: DOM.id("dht-cfg-autoscroll"),
optsAfterFirstMsg: {},
optsAfterSavedMsg: {}
};
settings.ui.optsAfterFirstMsg[CONSTANTS.AUTOSCROLL_ACTION_NOTHING] = DOM.id("dht-cfg-afm-nothing");
settings.ui.optsAfterFirstMsg[CONSTANTS.AUTOSCROLL_ACTION_PAUSE] = DOM.id("dht-cfg-afm-pause");
settings.ui.optsAfterFirstMsg[CONSTANTS.AUTOSCROLL_ACTION_SWITCH] = DOM.id("dht-cfg-afm-switch");
settings.ui.optsAfterSavedMsg[CONSTANTS.AUTOSCROLL_ACTION_NOTHING] = DOM.id("dht-cfg-asm-nothing");
settings.ui.optsAfterSavedMsg[CONSTANTS.AUTOSCROLL_ACTION_PAUSE] = DOM.id("dht-cfg-asm-pause");
settings.ui.optsAfterSavedMsg[CONSTANTS.AUTOSCROLL_ACTION_SWITCH] = DOM.id("dht-cfg-asm-switch");
// events
settings.ui.cbAutoscroll.addEventListener("change", () => {
SETTINGS.autoscroll = settings.ui.cbAutoscroll.checked;
});
Object.keys(settings.ui.optsAfterFirstMsg).forEach(key => {
DOM.listen(settings.ui.optsAfterFirstMsg[key], "click", () => {
SETTINGS.afterFirstMsg = key;
});
});
Object.keys(settings.ui.optsAfterSavedMsg).forEach(key => {
DOM.listen(settings.ui.optsAfterSavedMsg[key], "click", () => {
SETTINGS.afterSavedMsg = key;
});
});
setupStateChanged("settings");
},
hideSettings: function(){
if (settings){
DOM.removeElement(settings.overlay);
DOM.removeElement(settings.ele);
DOM.removeElement(settings.styles);
settings = null;
}
}
};
return root;
})();

View File

@ -1,349 +0,0 @@
/*
* SAVEFILE STRUCTURE
* ==================
*
* {
* meta: {
* users: {
* <discord user id>: {
* name: <user name>,
* avatar: <user icon>,
* tag: <user discriminator> // only present if not a bot
* }, ...
* },
*
* // the user index is an array of discord user ids,
* // these indexes are used in the message objects to save space
* userindex: [
* <discord user id>, ...
* ],
*
* servers: [
* {
* name: <server name>,
* type: <"SERVER"|"GROUP"|DM">
* }, ...
* ],
*
* channels: {
* <discord channel id>: {
* server: <server index in the meta.servers array>,
* name: <channel name>,
* position: <order in channel list>, // only present if server type == SERVER
* topic: <channel topic>, // only present if server type == SERVER
* nsfw: <channel NSFW status> // only present if server type == SERVER
* }, ...
* }
* },
*
* data: {
* <discord channel id>: {
* <discord message id>: {
* u: <user index of the sender>,
* t: <message timestamp>,
* m: <message content>, // only present if not empty
* f: <message flags>, // only present if edited in which case it equals 1, deprecated (use 'te' instead)
* te: <edit timestamp>, // only present if edited
* e: [ // omit for no embeds
* {
* url: <embed url>,
* type: <embed type>,
* t: <rich embed title>, // only present if type == rich, and if not empty
* d: <rich embed description> // only present if type == rich, and if the embed has a simple description text
* }, ...
* ],
* a: [ // omit for no attachments
* {
* url: <attachment url>
* }, ...
* ],
* r: <reply message id>, // only present if referencing another message (reply)
* re: [ // omit for no reactions
* {
* c: <react count>
* n: <emoji name>,
* id: <emoji id>, // only present for custom emoji
* an: <emoji is animated>, // only present for custom animated emoji
* }, ...
* ]
* }, ...
* }, ...
* }
* }
*
*
* TEMPORARY OBJECT STRUCTURE
* ==========================
*
* {
* userlookup: {
* <discord user id>: <user index in the meta.userindex array>
* },
* channelkeys: Set<channel id>,
* messagekeys: Set<message id>,
* freshmsgs: Set<message id> // only messages which were newly added to the savefile in the current session
* }
*/
class SAVEFILE{
constructor(parsedObj){
var me = this;
if (!SAVEFILE.isValid(parsedObj)){
parsedObj = {
meta: {},
data: {}
};
}
me.meta = parsedObj.meta;
me.data = parsedObj.data;
me.meta.users = me.meta.users || {};
me.meta.userindex = me.meta.userindex || [];
me.meta.servers = me.meta.servers || [];
me.meta.channels = me.meta.channels || {};
me.tmp = {
userlookup: {},
channelkeys: new Set(),
messagekeys: new Set(),
freshmsgs: new Set()
};
}
static isValid(parsedObj){
return parsedObj && typeof parsedObj.meta === "object" && typeof parsedObj.data === "object";
}
findOrRegisterUser(userId, userName, userDiscriminator, userAvatar){
var wasPresent = userId in this.meta.users;
var userObj = wasPresent ? this.meta.users[userId] : {};
userObj.name = userName;
if (userDiscriminator){
userObj.tag = userDiscriminator;
}
if (userAvatar){
userObj.avatar = userAvatar;
}
if (!wasPresent){
this.meta.users[userId] = userObj;
this.meta.userindex.push(userId);
return this.tmp.userlookup[userId] = this.meta.userindex.length-1;
}
else if (!(userId in this.tmp.userlookup)){
return this.tmp.userlookup[userId] = this.meta.userindex.findIndex(id => id == userId);
}
else{
return this.tmp.userlookup[userId];
}
}
findOrRegisterServer(serverName, serverType){
var index = this.meta.servers.findIndex(server => server.name === serverName && server.type === serverType);
if (index === -1){
this.meta.servers.push({
"name": serverName,
"type": serverType
});
return this.meta.servers.length-1;
}
else{
return index;
}
}
tryRegisterChannel(serverIndex, channelId, channelName, extraInfo){
if (!this.meta.servers[serverIndex]){
return undefined;
}
var wasPresent = channelId in this.meta.channels;
var channelObj = wasPresent ? this.meta.channels[channelId] : { "server": serverIndex };
channelObj.name = channelName;
if (extraInfo.position){
channelObj.position = extraInfo.position;
}
if (extraInfo.topic){
channelObj.topic = extraInfo.topic;
}
if (extraInfo.nsfw){
channelObj.nsfw = extraInfo.nsfw;
}
if (wasPresent){
return false;
}
else{
this.meta.channels[channelId] = channelObj;
this.tmp.channelkeys.add(channelId);
return true;
}
}
addMessage(channelId, messageId, messageObject){
var container = this.data[channelId] || (this.data[channelId] = {});
var wasPresent = messageId in container;
container[messageId] = messageObject;
this.tmp.messagekeys.add(messageId);
return !wasPresent;
}
convertToMessageObject(discordMessage){
var author = discordMessage.author;
var obj = {
u: this.findOrRegisterUser(author.id, author.username, author.bot ? null : author.discriminator, author.avatar),
t: discordMessage.timestamp.toDate().getTime()
};
if (discordMessage.content.length > 0){
obj.m = discordMessage.content;
}
if (discordMessage.editedTimestamp !== null){
obj.te = discordMessage.editedTimestamp.toDate().getTime();
}
if (discordMessage.embeds.length > 0){
obj.e = discordMessage.embeds.map(embed => {
let conv = {
url: embed.url,
type: embed.type
};
if (embed.type === "rich"){
if (Array.isArray(embed.title) && embed.title.length === 1 && typeof embed.title[0] === "string"){
conv.t = embed.title[0];
if (Array.isArray(embed.description) && embed.description.length === 1 && typeof embed.description[0] === "string"){
conv.d = embed.description[0];
}
}
}
return conv;
});
}
if (discordMessage.attachments.length > 0){
obj.a = discordMessage.attachments.map(attachment => ({
url: attachment.url
}));
}
if (discordMessage.messageReference !== null){
obj.r = discordMessage.messageReference.message_id;
}
if (discordMessage.reactions.length > 0) {
obj.re = discordMessage.reactions.map(reaction => {
let conv = {
c: reaction.count,
n: reaction.emoji.name
};
if (reaction.emoji.id !== null) {
conv.id = reaction.emoji.id;
}
if (reaction.emoji.animated) {
conv.an = true;
}
return conv;
});
}
return obj;
}
isMessageFresh(id){
return this.tmp.freshmsgs.has(id);
}
addMessagesFromDiscord(channelId, discordMessageArray){
var hasNewMessages = false;
for(var discordMessage of discordMessageArray){
var type = discordMessage.type;
// https://discord.com/developers/docs/resources/channel#message-object-message-reference-structure
if ((type === 0 || type === 19) && discordMessage.state === "SENT" && this.addMessage(channelId, discordMessage.id, this.convertToMessageObject(discordMessage))){
this.tmp.freshmsgs.add(discordMessage.id);
hasNewMessages = true;
}
}
return hasNewMessages;
}
countChannels(){
return this.tmp.channelkeys.size;
}
countMessages(){
return this.tmp.messagekeys.size;
}
combineWith(obj){
var userMap = {};
var shownError = false;
for(var userId in obj.meta.users){
var oldUser = obj.meta.users[userId];
userMap[obj.meta.userindex.findIndex(id => id == userId)] = this.findOrRegisterUser(userId, oldUser.name, oldUser.tag, oldUser.avatar);
}
for(var channelId in obj.meta.channels){
var oldServer = obj.meta.servers[obj.meta.channels[channelId].server];
var oldChannel = obj.meta.channels[channelId];
this.tryRegisterChannel(this.findOrRegisterServer(oldServer.name, oldServer.type), channelId, oldChannel.name, oldChannel /* filtered later */);
}
for(var channelId in obj.data){
var oldChannel = obj.data[channelId];
for(var messageId in oldChannel){
var oldMessage = oldChannel[messageId];
var oldUser = oldMessage.u;
if (oldUser in userMap){
oldMessage.u = userMap[oldUser];
this.addMessage(channelId, messageId, oldMessage);
}
else{
if (!shownError){
shownError = true;
alert("The uploaded archive appears to be corrupted, some messages will be skipped. See console for details.");
console.error("User list:", obj.meta.users);
console.error("User index:", obj.meta.userindex);
console.error("Generated mapping:", userMap);
console.error("Missing user for the following messages:");
}
console.error(oldMessage);
}
}
}
}
toJson(){
return JSON.stringify({
"meta": this.meta,
"data": this.data
});
}
}

View File

@ -1,64 +0,0 @@
var CONSTANTS = {
AUTOSCROLL_ACTION_NOTHING: "optNothing",
AUTOSCROLL_ACTION_PAUSE: "optPause",
AUTOSCROLL_ACTION_SWITCH: "optSwitch"
};
var IS_FIRST_RUN = false;
var SETTINGS = (function(){
var root = {};
var settingsChangedEvents = [];
var saveSettings = function(){
DOM.saveToCookie("DHT_SETTINGS", root, 60*60*24*365*5);
};
var triggerSettingsChanged = function(changeType, changeDetail){
for(var callback of settingsChangedEvents){
callback(changeType, changeDetail);
}
saveSettings();
};
var defineTriggeringProperty = function(obj, property, value){
var name = "_"+property;
Object.defineProperty(obj, property, {
get: (() => obj[name]),
set: (value => {
obj[name] = value;
triggerSettingsChanged("setting", property);
})
});
obj[name] = value;
};
var loaded = DOM.loadFromCookie("DHT_SETTINGS");
if (!loaded){
loaded = {
"_autoscroll": true,
"_afterFirstMsg": CONSTANTS.AUTOSCROLL_ACTION_PAUSE,
"_afterSavedMsg": CONSTANTS.AUTOSCROLL_ACTION_PAUSE
};
IS_FIRST_RUN = true;
}
defineTriggeringProperty(root, "autoscroll", loaded._autoscroll);
defineTriggeringProperty(root, "afterFirstMsg", loaded._afterFirstMsg);
defineTriggeringProperty(root, "afterSavedMsg", loaded._afterSavedMsg);
root.onSettingsChanged = function(callback){
settingsChangedEvents.push(callback);
};
if (IS_FIRST_RUN){
saveSettings();
}
return root;
})();

View File

@ -1,119 +0,0 @@
var STATE = (function(){
var stateChangedEvents = [];
var triggerStateChanged = function(changeType, changeDetail){
for(var callback of stateChangedEvents){
callback(changeType, changeDetail);
}
};
/*
* Internal class constructor.
*/
class CLS{
constructor(){
this.resetState();
};
/*
* Resets the state to default values.
*/
resetState(){
this._savefile = null;
this._isTracking = false;
this._lastFileName = null;
triggerStateChanged("data", "reset");
}
/*
* Returns the savefile object, creates a new one if needed.
*/
getSavefile(){
if (!this._savefile){
this._savefile = new SAVEFILE();
}
return this._savefile;
}
/*
* Returns true if the database file contains any data.
*/
hasSavedData(){
return this._savefile != null;
}
/*
* Returns true if currently tracking message.
*/
isTracking(){
return this._isTracking;
}
/*
* Sets the tracking state.
*/
setIsTracking(state){
this._isTracking = state;
triggerStateChanged("tracking", state);
}
/*
* Combines current savefile with the provided one.
*/
uploadSavefile(fileName, fileObject){
this._lastFileName = fileName;
this.getSavefile().combineWith(fileObject);
triggerStateChanged("data", "upload");
}
/*
* Triggers a savefile download, if available.
*/
downloadSavefile(){
if (this.hasSavedData()){
DOM.downloadTextFile(this._lastFileName || "dht.txt", this._savefile.toJson());
}
}
/*
* Registers a Discord server and channel.
*/
addDiscordChannel(serverName, serverType, channelId, channelName, extraInfo){
var serverIndex = this.getSavefile().findOrRegisterServer(serverName, serverType);
if (this.getSavefile().tryRegisterChannel(serverIndex, channelId, channelName, extraInfo) === true){
triggerStateChanged("data", "channel");
}
}
/*
* Adds all messages from the array to the specified channel. Returns true if the savefile was updated.
*/
addDiscordMessages(channelId, discordMessageArray){
if (this.getSavefile().addMessagesFromDiscord(channelId, discordMessageArray)){
triggerStateChanged("data", "messages");
return true;
}
else{
return false;
}
}
/*
* Returns true if the message was added during this session.
*/
isMessageFresh(id){
return this.getSavefile().isMessageFresh(id);
}
/*
* Adds a listener that is called whenever the state changes. The callback is a function that takes subject (generic type) and detail (specific type or data).
*/
onStateChanged(callback){
stateChangedEvents.push(callback);
}
}
return new CLS();
})();

View File

@ -1,136 +0,0 @@
const url = window.location.href;
if (!url.includes("discord.com/") && !url.includes("discordapp.com/") && !confirm("Could not detect Discord in the URL, do you want to run the script anyway?")){
return;
}
if (window.DHT_LOADED){
alert("Discord History Tracker is already loaded.");
return;
}
window.DHT_LOADED = true;
window.DHT_ON_UNLOAD = [];
// Execution
let ignoreMessageCallback = new Set();
let frozenMessageLoadingTimer = null;
let stopTrackingDelayed = function(callback){
ignoreMessageCallback.add("stopping");
DOM.setTimer(() => {
STATE.setIsTracking(false);
ignoreMessageCallback.delete("stopping");
if (callback){
callback();
}
}, 200); // give the user visual feedback after clicking the button before switching off
};
DISCORD.setupMessageCallback(messages => {
if (STATE.isTracking() && ignoreMessageCallback.size === 0){
let info = DISCORD.getSelectedChannel();
if (!info){
stopTrackingDelayed();
return;
}
STATE.addDiscordChannel(info.server, info.type, info.id, info.channel, info.extra);
if (messages !== false && !messages.length){
DISCORD.loadOlderMessages();
return;
}
let hasUpdatedFile = messages !== false && STATE.addDiscordMessages(info.id, messages);
if (SETTINGS.autoscroll){
let action = null;
if (messages === false) {
action = SETTINGS.afterFirstMsg;
}
else if (!hasUpdatedFile && !STATE.isMessageFresh(messages[0].id)){
action = SETTINGS.afterSavedMsg;
}
if (action === null){
if (hasUpdatedFile){
DISCORD.loadOlderMessages();
window.clearTimeout(frozenMessageLoadingTimer);
frozenMessageLoadingTimer = null;
}
else{
frozenMessageLoadingTimer = window.setTimeout(DISCORD.loadOlderMessages, 2500);
}
}
else{
ignoreMessageCallback.add("stalling");
DOM.setTimer(() => {
ignoreMessageCallback.delete("stalling");
let updatedInfo = DISCORD.getSelectedChannel();
if (updatedInfo && updatedInfo.id === info.id){
let lastMessages = DISCORD.getMessages(); // sometimes needed to catch the last few messages before switching
if (lastMessages != null){
STATE.addDiscordMessages(info.id, lastMessages);
}
}
if ((action === CONSTANTS.AUTOSCROLL_ACTION_SWITCH && !DISCORD.selectNextTextChannel()) || action === CONSTANTS.AUTOSCROLL_ACTION_PAUSE){
STATE.setIsTracking(false);
}
}, 250);
}
}
}
});
STATE.onStateChanged((type, enabled) => {
if (type === "tracking" && enabled){
let info = DISCORD.getSelectedChannel();
if (info){
let messages = DISCORD.getMessages();
if (messages != null){
STATE.addDiscordChannel(info.server, info.type, info.id, info.channel, info.extra);
STATE.addDiscordMessages(info.id, messages);
}
else{
stopTrackingDelayed(() => alert("Cannot see any messages."));
return;
}
}
else{
stopTrackingDelayed(() => alert("The selected channel is not visible in the channel list."));
return;
}
if (SETTINGS.autoscroll && DISCORD.isInMessageView()){
if (DISCORD.hasMoreMessages()){
DISCORD.loadOlderMessages();
}
else{
let action = SETTINGS.afterFirstMsg;
if ((action === CONSTANTS.AUTOSCROLL_ACTION_SWITCH && !DISCORD.selectNextTextChannel()) || action === CONSTANTS.AUTOSCROLL_ACTION_PAUSE){
stopTrackingDelayed();
}
}
}
}
});
GUI.showController();
if (IS_FIRST_RUN){
GUI.showSettings();
}

View File

@ -1,85 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Discord Offline History</title>
<script type="text/javascript">
/*{js}*/
</script>
<style type="text/css">
/*{css}*/
</style>
</head>
<body>
<div id="menu">
<input id="uploaded-file" type="file" style="display:none">
<button id="btn-upload-file" class="hide-embedded">Load File</button>
<div class="splitter hide-embedded"></div>
<button id="btn-settings">Settings</button>
<div> <!-- needed to stop the select from messing up -->
<select id="opt-messages-per-page">
<option value="50">50 messages per page&nbsp;</option>
<option value="100">100 messages per page&nbsp;</option>
<option value="250">250 messages per page&nbsp;</option>
<option value="500">500 messages per page&nbsp;</option>
<option value="1000">1000 messages per page&nbsp;</option>
<option value="0">All messages&nbsp;</option>
</select>
</div>
<div class="nav">
<button id="nav-first" data-nav="first" class="icon">&laquo;</button>
<button id="nav-prev" data-nav="prev" class="icon">&lsaquo;</button>
<button id="nav-pick" data-nav="pick">Page <span id="nav-page-current">1</span>/<span id="nav-page-total">?</span></button>
<button id="nav-next" data-nav="next" class="icon">&rsaquo;</button>
<button id="nav-last" data-nav="last" class="icon">&raquo;</button>
</div>
<div class="splitter"></div>
<div> <!-- needed to stop the select from messing up -->
<select id="opt-messages-filter">
<option value="">No filter&nbsp;</option>
<option value="user">Filter messages by user&nbsp;</option>
<option value="contents">Filter messages by contents&nbsp;</option>
<option value="withimages">Only messages with images&nbsp;</option>
<option value="withdownloads">Only messages with downloads&nbsp;</option>
<option value="edited">Only edited messages&nbsp;</option>
</select>
</div>
<div id="opt-filter-list">
<select id="opt-filter-user" data-filter-type="user">
<option value="">Select user...</option>
</select>
<input id="opt-filter-contents" type="text" data-filter-type="contents" placeholder="Messages containing...">
<input type="hidden" data-filter-type="withimages" value="1">
<input type="hidden" data-filter-type="withdownloads" value="1">
<input type="hidden" data-filter-type="edited" value="1">
</div>
<div id="opt-save-filtered">
<div class="splitter"></div>
<button id="btn-save-filtered">Save Filtered Messages</button>
</div>
<div class="separator"></div>
<button id="btn-about">About</button>
</div>
<div id="app">
<div id="channels"></div>
<div id="messages"></div>
</div>
<div id="modal">
<div id="overlay"></div>
<div id="dialog"></div>
</div>
</body>
</html>

View File

@ -1,246 +0,0 @@
var DISCORD = (function(){
var REGEX = {
formatBold: /\*\*([\s\S]+?)\*\*(?!\*)/g,
formatItalic: /(.)?\*([\s\S]+?)\*(?!\*)/g,
formatUnderline: /__([\s\S]+?)__(?!_)/g,
formatStrike: /~~([\s\S]+?)~~(?!~)/g,
formatCodeInline: /(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/g,
formatCodeBlock: /```(?:([A-z0-9\-]+?)\n+)?\n*([^]+?)\n*```/g,
formatUrl: /(\b(?:https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
formatUrlNoEmbed: /<(\b(?:https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])>/ig,
specialEscapedBacktick: /\\`/g,
specialEscapedSingle: /\\([*\\])/g,
specialEscapedDouble: /\\__|_\\_|\\_\\_|\\~~|~\\~|\\~\\~/g,
specialUnescaped: /([*_~\\])/g,
mentionRole: /&lt;@&(\d+?)&gt;/g,
mentionUser: /&lt;@!?(\d+?)&gt;/g,
mentionChannel: /&lt;#(\d+?)&gt;/g,
customEmojiStatic: /&lt;:([^:]+):(\d+?)&gt;/g,
customEmojiAnimated: /&lt;a:([^:]+):(\d+?)&gt;/g
};
var isImageAttachment = function(attachment){
var dot = attachment.url.lastIndexOf(".");
var ext = dot === -1 ? "" : attachment.url.substring(dot).toLowerCase();
return ext === ".png" || ext === ".gif" || ext === ".jpg" || ext === ".jpeg";
};
var getHumanReadableTime = function(timestamp){
var date = new Date(timestamp);
return date.toLocaleDateString() + ", " + date.toLocaleTimeString();
};
var templateChannelServer;
var templateChannelPrivate;
var templateMessageNoAvatar;
var templateMessageWithAvatar;
var templateUserAvatar;
var templateEmbedImage;
var templateEmbedRich;
var templateEmbedRichNoDescription;
var templateEmbedRichUnsupported;
var templateEmbedDownload;
var processMessageContents = function(contents){
var processed = DOM.escapeHTML(contents.replace(REGEX.formatUrlNoEmbed, "$1"));
if (STATE.settings.enableFormatting){
var escapeHtmlMatch = (full, match) => "&#"+match.charCodeAt(0)+";";
processed = processed
.replace(REGEX.specialEscapedBacktick, "&#96;")
.replace(REGEX.formatCodeBlock, (full, ignore, match) => "<code class='block'>"+match.replace(REGEX.specialUnescaped, escapeHtmlMatch)+"</code>")
.replace(REGEX.formatCodeInline, (full, ignore, match) => "<code class='inline'>"+match.replace(REGEX.specialUnescaped, escapeHtmlMatch)+"</code>")
.replace(REGEX.specialEscapedSingle, escapeHtmlMatch)
.replace(REGEX.specialEscapedDouble, full => full.replace(/\\/g, "").replace(/(.)/g, escapeHtmlMatch))
.replace(REGEX.formatBold, "<b>$1</b>")
.replace(REGEX.formatItalic, (full, pre, match) => pre === '\\' ? full : (pre || "")+"<i>"+match+"</i>")
.replace(REGEX.formatUnderline, "<u>$1</u>")
.replace(REGEX.formatStrike, "<s>$1</s>");
}
var animatedEmojiExtension = STATE.settings.enableAnimatedEmoji ? "gif" : "png";
processed = processed
.replace(REGEX.formatUrl, "<a href='$1' target='_blank' rel='noreferrer'>$1</a>")
.replace(REGEX.mentionChannel, (full, match) => "<span class='link mention-chat'>#"+STATE.getChannelName(match)+"</span>")
.replace(REGEX.mentionUser, (full, match) => "<span class='link mention-user' title='#"+(STATE.getUserTag(match) || "????")+"'>@"+STATE.getUserName(match)+"</span>")
.replace(REGEX.customEmojiStatic, "<img src='https://cdn.discordapp.com/emojis/$2.png' alt=':$1:' title=':$1:' class='emoji'>")
.replace(REGEX.customEmojiAnimated, "<img src='https://cdn.discordapp.com/emojis/$2."+animatedEmojiExtension+"' alt=':$1:' title=':$1:' class='emoji'>");
return "<p>"+processed+"</p>";
};
return {
setup: function(){
templateChannelServer = new TEMPLATE([
"<div data-channel='{id}'>",
"<div class='info' title='{topic}'><strong class='name'>#{name}</strong>{nsfw}<span class='tag'>{msgcount}</span></div>",
"<span class='server'>{server.name} ({server.type})</span>",
"</div>"
].join(""));
templateChannelPrivate = new TEMPLATE([
"<div data-channel='{id}'>",
"<div class='info'><strong class='name'>{name}</strong><span class='tag'>{msgcount}</span></div>",
"<span class='server'>({server.type})</span>",
"</div>"
].join(""));
templateMessageNoAvatar = new TEMPLATE([
"<div>",
"<div class='reply-message'>{reply}</div>",
"<h2><strong class='username' title='#{user.tag}'>{user.name}</strong><span class='info time'>{timestamp}</span>{edit}{jump}</h2>",
"<div class='message'>{contents}{embeds}{attachments}</div>",
"<div class='reactions'>{reactions}</div>",
"</div>"
].join(""));
templateMessageWithAvatar = new TEMPLATE([
"<div>",
"<div class='reply-message reply-message-with-avatar'>{reply}</div>",
"<div class='avatar-wrapper'>",
"<div class='avatar'>{avatar}</div>",
"<div>",
"<h2><strong class='username' title='#{user.tag}'>{user.name}</strong><span class='info time'>{timestamp}</span>{edit}{jump}</h2>",
"<div class='message'>{contents}{embeds}{attachments}</div>",
"<div class='reactions'>{reactions}</div>",
"</div>",
"</div>",
"</div>"
].join(""));
templateUserAvatar = new TEMPLATE([
"<img src='https://cdn.discordapp.com/avatars/{id}/{path}.webp?size=128'>"
].join(""));
templateEmbedImage = new TEMPLATE([
"<a href='{url}' class='embed thumbnail'><img src='{url}' alt='(image attachment not found)'></a><br>"
].join(""));
templateEmbedRich = new TEMPLATE([
"<div class='embed download'><a href='{url}' class='title'>{t}</a><p class='desc'>{d}</p></div>"
].join(""));
templateEmbedRichNoDescription = new TEMPLATE([
"<div class='embed download'><a href='{url}' class='title'>{t}</a></div>"
].join(""));
templateEmbedRichUnsupported = new TEMPLATE([
"<div class='embed download'><p>(Formatted embeds are currently not supported)</p></div>"
].join(""));
templateEmbedDownload = new TEMPLATE([
"<a href='{url}' class='embed download'>Download {filename}</a>"
].join(""));
templateReaction = new TEMPLATE([
"<span class='reaction-wrapper'><span class='reaction-emoji'>{n}</span><span class='count'>{c}</span></span>"
].join(""));
templateReactionCustom = new TEMPLATE([
"<span class='reaction-wrapper'><img src='https://cdn.discordapp.com/emojis/{id}.{ext}' alt=':{n}:' title=':{n}:' class='reaction-emoji-custom'><span class='count'>{c}</span></span>"
].join(""));
},
isImageAttachment: isImageAttachment,
getChannelHTML: function(channel){
return (channel.server.type === "SERVER" ? templateChannelServer : templateChannelPrivate).apply(channel, (property, value) => {
if (property === "server.type"){
switch(value){
case "SERVER": return "server";
case "GROUP": return "group";
case "DM": return "user";
}
}
else if (property === "nsfw"){
return value ? "<span class='tag'>NSFW</span>" : "";
}
});
},
getMessageHTML: function(message){
return (STATE.settings.enableUserAvatars ? templateMessageWithAvatar : templateMessageNoAvatar).apply(message, (property, value) => {
if (property === "avatar"){
return value ? templateUserAvatar.apply(value) : "";
}
else if (property === "user.tag"){
return value ? value : "????";
}
else if (property === "timestamp"){
return getHumanReadableTime(value);
}
else if (property === "contents"){
return value == null || value.length === 0 ? "" : processMessageContents(value);
}
else if (property === "embeds"){
if (!value){
return "";
}
return value.map(embed => {
switch(embed.type){
case "image":
return STATE.settings.enableImagePreviews ? templateEmbedImage.apply(embed) : "";
case "rich":
return (embed.t ? (embed.d ? templateEmbedRich : templateEmbedRichNoDescription) : templateEmbedRichUnsupported).apply(embed);
}
}).join("");
}
else if (property === "attachments"){
if (!value){
return "";
}
return value.map(attachment => {
if (isImageAttachment(attachment) && STATE.settings.enableImagePreviews){
return templateEmbedImage.apply(attachment);
}
else{
var sliced = attachment.url.split("/");
return templateEmbedDownload.apply({
"url": attachment.url,
"filename": sliced[sliced.length-1]
});
}
}).join("");
}
else if (property === "edit"){
return value ? "<span class='info edited'>Edited" + (value > 1 ? " " + getHumanReadableTime(value) : "") + "</span>" : "";
}
else if (property === "jump"){
return STATE.hasActiveFilter ? "<span class='info jump' data-jump='" + value + "'>Jump to message</span>" : "";
}
else if (property === "reply"){
if (value === null) {
return "";
}
var user = "<span class='reply-username' title='#" + (value.user.tag ? value.user.tag : "????") + "'>" + value.user.name + "</span>";
var avatar = STATE.settings.enableUserAvatars && value.avatar ? "<span class='reply-avatar'>" + templateUserAvatar.apply(value.avatar) + "</span>" : "";
var contents = value.contents ? "<span class='reply-contents'>" + processMessageContents(value.contents) + "</span>" : "";
return "<span class='jump' data-jump='" + value.id + "'>Jump to reply</span><span class='user'>" + avatar + user + "</span>" + contents;
}
else if (property === "reactions"){
if (value === null){
return "";
}
return value.map(reaction => {
if ("id" in reaction){
reaction.ext = reaction.an && STATE.settings.enableAnimatedEmoji ? "gif" : "png";
return templateReactionCustom.apply(reaction);
}
else {
return templateReaction.apply(reaction);
}
}).join("");
}
});
}
};
})();

View File

@ -1,77 +0,0 @@
var DOM = (function(){
var createElement = (tag, parent) => {
var ele = document.createElement(tag);
parent.appendChild(ele);
return ele;
};
var entityMap = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': '&quot;',
"'": '&#39;'
};
var entityRegex = /[&<>"']/g;
return {
/*
* Returns a child element by its ID. Parent defaults to the entire document.
*/
id: (id, parent) => (parent || document).getElementById(id),
/*
* Returns an array of all child elements containing the specified class. Parent defaults to the entire document.
*/
cls: (cls, parent) => Array.prototype.slice.call((parent || document).getElementsByClassName(cls)),
/*
* Returns an array of all child elements that have the specified tag. Parent defaults to the entire document.
*/
tag: (tag, parent) => Array.prototype.slice.call((parent || document).getElementsByTagName(tag)),
/*
* Returns the first child element containing the specified class. Parent defaults to the entire document.
*/
fcls: (cls, parent) => (parent || document).getElementsByClassName(cls)[0],
/*
* Creates an element, adds it to the DOM, and returns it.
*/
createElement: (tag, parent) => createElement(tag, parent),
/*
* Removes an element from the DOM.
*/
removeElement: (ele) => ele.parentNode.removeChild(ele),
/*
* Converts characters to their HTML entity form.
*/
escapeHTML: (html) => String(html).replace(entityRegex, s => entityMap[s]),
/*
* Triggers a UTF-8 text file download.
*/
downloadTextFile: (fileName, fileContents) => {
var blob = new Blob([fileContents], { "type": "octet/stream" });
if ("msSaveBlob" in window.navigator){
return window.navigator.msSaveBlob(blob, fileName);
}
var url = window.URL.createObjectURL(blob);
var ele = createElement("a", document.body);
ele.href = url;
ele.download = fileName;
ele.style.display = "none";
ele.click();
document.body.removeChild(ele);
window.URL.revokeObjectURL(url);
}
};
})();

View File

@ -1,58 +0,0 @@
var EMBED = (function(){
var enabled = false;
var html;
var generated;
var downloadTextFile = function(fileName, fileContents){
var blob = new Blob([fileContents], { "type": "octet/stream" });
if ("msSaveBlob" in window.navigator){
return window.navigator.msSaveBlob(blob, fileName);
}
var url = window.URL.createObjectURL(blob);
var ele = DOM.createElement("a", document.body);
ele.href = url;
ele.download = fileName;
ele.style.display = "none";
ele.click();
document.body.removeChild(ele);
window.URL.revokeObjectURL(url);
};
var utoa = function(str){
return window.btoa(unescape(encodeURIComponent(str)));
};
var atou = function(str){
return decodeURIComponent(escape(window.atob(str)));
};
return {
setup: function(){
enabled = true;
html = "<!DOCTYPE html>\n" + document.documentElement.outerHTML;
DOM.id("btn-upload-file").insertAdjacentHTML("afterend", `<button id="btn-embed-file" disabled>Embed File</button>`);
DOM.id("btn-embed-file").addEventListener("click", () => downloadTextFile("embed.html", generated));
},
onFileRead: function(json){
if (!enabled){
return;
}
DOM.id("btn-embed-file").disabled = false;
generated = html.replace("</title>", `</title>\n<script type="text/javascript">window.DHT_EMBEDDED = "${utoa(json)}";<\/script>`).replace(`<${document.body.tagName.toLowerCase()}>`, `<body class="embedded">`);
},
getEmbeddedJSON: function(){
var embed = window.DHT_EMBEDDED;
return embed ? atou(embed) : null;
}
};
})();

View File

@ -1,80 +0,0 @@
document.addEventListener("DOMContentLoaded", () => {
var embedded = EMBED.getEmbeddedJSON();
if (location.search === "?embed" && !embedded){
EMBED.setup();
}
DISCORD.setup();
GUI.setup();
GUI.onOptionMessagesPerPageChanged(() => {
STATE.setMessagesPerPage(GUI.getOptionMessagesPerPage());
});
STATE.setMessagesPerPage(GUI.getOptionMessagesPerPage());
GUI.onOptMessageFilterChanged(filter => {
STATE.setActiveFilter(filter);
});
GUI.onNavigationButtonClicked(action => {
STATE.updateCurrentPage(action);
});
STATE.onUsersRefreshed(users => {
GUI.updateUserList(users);
});
STATE.onChannelsRefreshed((channels, selected) => {
GUI.updateChannelList(channels, selected, STATE.selectChannel);
});
STATE.onMessagesRefreshed(messages => {
GUI.updateNavigation(STATE.getCurrentPage(), STATE.getPageCount());
GUI.updateMessageList(messages);
GUI.scrollMessagesToTop();
});
var loadJSON = function(json, errParse, errInvalid){
var obj;
try{
obj = JSON.parse(json);
EMBED.onFileRead(json);
}catch(e){
console.error(e);
alert(errParse);
return;
}
if (SAVEFILE.isValid(obj)){
STATE.uploadFile(new SAVEFILE(obj));
}
else{
alert(errInvalid);
}
};
if (embedded){
loadJSON(embedded, "Could not parse embedded file, see console for details.", "Embedded file has an invalid format.");
}
else{
GUI.onFileUploaded(files => {
if (files.length === 1){
var file = files[0];
var reader = new FileReader();
STATE.setUploadedFileName(file.name);
reader.onload = () => loadJSON(reader.result, "Could not parse '"+file.name+"', see console for details.", "File '"+file.name+"' has an invalid format.");
reader.readAsText(file, "UTF-8");
}
else{
alert("Please, select only one file.");
}
return true;
});
}
});

View File

@ -1,295 +0,0 @@
var GUI = (function(){
var eventOnFileUploaded;
var eventOnOptMessagesPerPageChanged;
var eventOnOptMessageFilterChanged;
var eventOnNavButtonClicked;
var getActiveFilter = function(){
var active = DOM.fcls("active", DOM.id("opt-filter-list"));
return active && active.value !== "" ? {
"type": active.getAttribute("data-filter-type"),
"value": active.value
} : null;
};
var triggerFilterChanged = function(){
var activeFilter = getActiveFilter();
DOM.id("opt-save-filtered").classList.toggle("active", activeFilter != null);
eventOnOptMessageFilterChanged && eventOnOptMessageFilterChanged(activeFilter);
};
var showModal = function(width, html){
var dialog = DOM.id("dialog");
dialog.innerHTML = html;
dialog.style.width = width+"px";
dialog.style.marginLeft = (-width/2)+"px";
DOM.id("modal").classList.add("visible");
return dialog;
};
// -------------
// Modal dialogs
// -------------
var showSettingsModal = function(){
showModal(560, `
<label><input id='dht-cfg-imgpreviews' type='checkbox'> Image Previews</label><br>
<label><input id='dht-cfg-formatting' type='checkbox'> Message Formatting</label><br>
<label><input id='dht-cfg-useravatars' type='checkbox'> User Avatars</label><br>
<label><input id='dht-cfg-animemoji' type='checkbox'> Animated Emoji</label><br>`);
var setupCheckBox = function(id, settingName){
var ele = DOM.id(id);
ele.checked = STATE.settings[settingName];
ele.addEventListener("change", () => STATE.settings[settingName] = ele.checked);
};
setupCheckBox("dht-cfg-imgpreviews", "enableImagePreviews");
setupCheckBox("dht-cfg-formatting", "enableFormatting");
setupCheckBox("dht-cfg-useravatars", "enableUserAvatars");
setupCheckBox("dht-cfg-animemoji", "enableAnimatedEmoji");
};
var showInfoModal = function(){
var linkGH = "https://github.com/chylex/Discord-History-Tracker";
showModal(560, `
<p>Discord History Tracker is developed by <a href='https://chylex.com'>chylex</a> as an <a href='${linkGH}/blob/master/LICENSE.md'>open source</a> project.</p>
<sub>{{{version:full}}}</sub>
<p>Please, report any issues and suggestions to the <a href='${linkGH}/issues'>tracker</a>. If you want to support the development, please spread the word and consider <a href='https://www.patreon.com/chylex'>becoming a patron</a> or <a href='https://ko-fi.com/chylex'>buying me a coffee</a>. Any support is appreciated!</p>
<p><a href='${linkGH}/issues'>Issue Tracker</a> &nbsp;&mdash;&nbsp; <a href='${linkGH}'>GitHub Repository</a> &nbsp;&mdash;&nbsp; <a href='https://twitter.com/chylexmc'>Developer's Twitter</a></p>`);
};
return {
// ---------
// GUI setup
// ---------
/*
* Hooks all event listeners into the DOM.
*/
setup: function(){
var inputUploadedFile = DOM.id("uploaded-file");
var inputMessageFilter = DOM.id("opt-messages-filter");
var containerFilterList = DOM.id("opt-filter-list");
var resetActiveFilter = function(){
inputMessageFilter.value = "";
inputMessageFilter.dispatchEvent(new Event("change"));
DOM.id("opt-filter-contents").value = "";
DOM.id("opt-save-filtered").classList.remove("active");
};
DOM.id("btn-upload-file").addEventListener("click", () => {
inputUploadedFile.click();
});
inputUploadedFile.addEventListener("change", () => {
if (eventOnFileUploaded && eventOnFileUploaded(inputUploadedFile.files)){
inputUploadedFile.value = null;
resetActiveFilter();
}
});
inputMessageFilter.value = ""; // required to prevent browsers from remembering old value
inputMessageFilter.addEventListener("change", () => {
DOM.cls("active", containerFilterList).forEach(ele => ele.classList.remove("active"));
if (inputMessageFilter.value){
containerFilterList.querySelector("[data-filter-type='"+inputMessageFilter.value+"']").classList.add("active");
}
triggerFilterChanged();
});
Array.prototype.forEach.call(containerFilterList.children, ele => {
ele.addEventListener(ele.tagName === "SELECT" ? "change" : "input", e => triggerFilterChanged());
});
DOM.id("opt-messages-per-page").addEventListener("change", () => {
eventOnOptMessagesPerPageChanged && eventOnOptMessagesPerPageChanged();
});
DOM.id("btn-save-filtered").addEventListener("click", () => {
if (confirm("Filtering only removes messages, all users and servers will remain in the new archive. Continue?")){
STATE.saveFilteredMessages();
}
});
DOM.tag("button", DOM.fcls("nav")).forEach(button => {
button.disabled = true;
button.addEventListener("click", () => {
eventOnNavButtonClicked && eventOnNavButtonClicked(button.getAttribute("data-nav"));
});
});
DOM.id("btn-settings").addEventListener("click", () => {
showSettingsModal();
});
DOM.id("btn-about").addEventListener("click", () => {
showInfoModal();
});
DOM.id("messages").addEventListener("click", e => {
var jump = e.target.getAttribute("data-jump");
if (jump){
resetActiveFilter();
var index = STATE.navigateToMessage(jump);
DOM.id("messages").children[index].scrollIntoView();
}
});
DOM.id("overlay").addEventListener("click", () => {
DOM.id("modal").classList.remove("visible");
DOM.id("dialog").innerHTML = "";
});
},
// -----------------
// Event registering
// -----------------
/*
* Sets a callback for when a file is uploaded. The callback takes a single argument, which is the file object array, and should return true to reset the input.
*/
onFileUploaded: function(callback){
eventOnFileUploaded = callback;
},
/*
* Sets a callback for when the user changes the messages per page option. The callback is not passed any arguments.
*/
onOptionMessagesPerPageChanged: function(callback){
eventOnOptMessagesPerPageChanged = callback;
},
/*
* Sets a callback for when the user changes the active filter. The callback is passed either null or an object such as { type: <filter type>, value: <filter value> }.
*/
onOptMessageFilterChanged: function(callback){
eventOnOptMessageFilterChanged = callback;
},
/*
* Sets a callback for when the user clicks a navigation button. The callback is passed one of the following strings: first, prev, next, last.
*/
onNavigationButtonClicked: function(callback){
eventOnNavButtonClicked = callback;
},
// ----------------------
// Options and navigation
// ----------------------
/*
* Returns the selected amount of messages per page.
*/
getOptionMessagesPerPage: function(){
return parseInt(DOM.id("opt-messages-per-page").value, 10);
},
/*
* Updates the navigation text and buttons.
*/
updateNavigation: function(currentPage, totalPages){
DOM.id("nav-page-current").innerHTML = currentPage;
DOM.id("nav-page-total").innerHTML = totalPages || "?";
DOM.id("nav-first").disabled = currentPage === 1;
DOM.id("nav-prev").disabled = currentPage === 1;
DOM.id("nav-pick").disabled = (totalPages || 0) <= 1;
DOM.id("nav-next").disabled = currentPage === (totalPages || 1);
DOM.id("nav-last").disabled = currentPage === (totalPages || 1);
},
// --------------
// Updating lists
// --------------
/*
* Updates the channel list and sets up their click events. The callback is triggered whenever a channel is selected, and takes the channel ID as its argument.
*/
updateChannelList: function(channels, selected, callback){
var eleChannels = DOM.id("channels");
if (!channels){
eleChannels.innerHTML = "";
}
else{
if (getActiveFilter() != null){
channels = channels.filter(channel => channel.msgcount > 0);
}
eleChannels.innerHTML = channels.map(channel => DISCORD.getChannelHTML(channel)).join("");
Array.prototype.forEach.call(eleChannels.children, ele => {
ele.addEventListener("click", e => {
var currentChannel = DOM.fcls("active", eleChannels);
if (currentChannel){
currentChannel.classList.remove("active");
}
ele.classList.add("active");
callback(ele.getAttribute("data-channel"));
});
});
if (selected){
var activeChannel = eleChannels.querySelector("[data-channel='"+selected+"']");
activeChannel && activeChannel.classList.add("active");
}
}
},
// ------------
// Message list
// ------------
/*
* Updates the message list.
*/
updateMessageList: function(messages){
DOM.id("messages").innerHTML = messages ? messages.map(message => DISCORD.getMessageHTML(message)).join("") : "";
},
/*
* Updates the user filter list.
*/
updateUserList: function(users){
var eleSelect = DOM.id("opt-filter-user");
while(eleSelect.length > 1){
eleSelect.remove(1);
}
var options = [];
for(var key of Object.keys(users)){
var option = document.createElement("option");
option.value = key;
option.text = users[key].name;
options.push(option);
}
options.sort((a, b) => a.text.toLocaleLowerCase().localeCompare(b.text.toLocaleLowerCase()));
options.forEach(option => eleSelect.add(option));
},
/*
* Scrolls the message div to the top.
*/
scrollMessagesToTop: function(){
DOM.id("messages").scrollTop = 0;
}
};
})();

View File

@ -1,41 +0,0 @@
var PROCESSOR = {};
// ------------------------
// Global filter generators
// ------------------------
PROCESSOR.FILTER = {
byUser: ((userindex) => message => message.u === userindex),
byTime: ((timeStart, timeEnd) => message => message.t >= timeStart && message.t <= timeEnd),
byContents: ((substr) => message => ("m" in message ? message.m : "").indexOf(substr) !== -1),
byRegex: ((regex) => message => regex.test("m" in message ? message.m : "")),
withImages: (() => message => (message.e && message.e.some(embed => embed.type === "image")) || (message.a && message.a.some(DISCORD.isImageAttachment))),
withDownloads: (() => message => message.a && message.a.some(attachment => !DISCORD.isImageAttachment(attachment))),
withEmbeds: (() => message => message.e && message.e.length > 0),
withAttachments: (() => message => message.a && message.a.length > 0),
isEdited: (() => message => ("te" in message) ? message.te : (message.f & 1) === 1)
};
// --------------
// Global sorters
// --------------
PROCESSOR.SORTER = {
oldestToNewest: (key1, key2) => {
if (key1.length === key2.length){
return key1 > key2 ? 1 : key1 < key2 ? -1 : 0;
}
else{
return key1.length > key2.length ? 1 : -1;
}
},
newestToOldest: (key1, key2) => {
if (key1.length === key2.length){
return key1 > key2 ? -1 : key1 < key2 ? 1 : 0;
}
else{
return key1.length > key2.length ? -1 : 1;
}
}
};

View File

@ -1,83 +0,0 @@
class SAVEFILE{
constructor(parsedObj){
var me = this;
me.meta = parsedObj.meta;
me.data = parsedObj.data;
me.meta.users = me.meta.users || {};
me.meta.userindex = me.meta.userindex || [];
me.meta.servers = me.meta.servers || [];
me.meta.channels = me.meta.channels || {};
};
static isValid(parsedObj){
return parsedObj && typeof parsedObj.meta === "object" && typeof parsedObj.data === "object";
};
getServer(index){
return this.meta.servers[index] || { "name": "&lt;unknown&gt;", "type": "ERROR" };
}
getChannels(){
return this.meta.channels;
}
getChannelById(channel){
return this.meta.channels[channel] || { "id": channel, "name": channel };
}
getUsers(){
return this.meta.users;
}
getUser(index){
return this.meta.users[this.meta.userindex[index]] || { "name": "&lt;unknown&gt;" };
}
getUserId(index){
return this.meta.userindex[index];
}
getUserById(user){
return this.meta.users[user] || { "name": user };
}
getUserIndex(user){
return this.meta.userindex.indexOf(user);
}
getMessages(channel){
return this.data[channel] || {};
}
filterToJson(filterFunction){
var newMeta = JSON.parse(JSON.stringify(this.meta));
var newData = {};
for(let channel of Object.keys(this.getChannels())){
var messages = this.getMessages(channel);
var retained = {};
for(let key of Object.keys(messages)){
var message = messages[key];
if (filterFunction(message)){
retained[key] = message;
}
}
if (Object.keys(retained).length > 0){
newData[channel] = retained;
}
else{
delete newMeta.channels[channel];
}
}
return JSON.stringify({
"meta": newMeta,
"data": newData
});
}
}

View File

@ -1,358 +0,0 @@
var STATE = (function(){
var ROOT = {};
// ---------------
// State variables
// ---------------
var FILE;
var MSGS;
var uploadedFileName;
var filterFunction;
var selectedChannel;
var currentPage;
var messagesPerPage;
// ----------------------------------
// Channel and message refresh events
// ----------------------------------
var eventOnChannelsRefreshed;
var eventOnMessagesRefreshed;
var eventOnUsersRefreshed;
var triggerChannelsRefreshed = function(selectedChannel){
eventOnChannelsRefreshed && eventOnChannelsRefreshed(ROOT.getChannelList(), selectedChannel);
};
var triggerMessagesRefreshed = function(){
eventOnMessagesRefreshed && eventOnMessagesRefreshed(ROOT.getMessageList());
};
var triggerUsersRefreshed = function(){
eventOnUsersRefreshed && eventOnUsersRefreshed(ROOT.getUserList());
};
ROOT.onChannelsRefreshed = function(callback){
eventOnChannelsRefreshed = callback;
};
ROOT.onMessagesRefreshed = function(callback){
eventOnMessagesRefreshed = callback;
};
ROOT.onUsersRefreshed = function(callback){
eventOnUsersRefreshed = callback;
};
// ------------------------------------
// File upload and basic data retrieval
// ------------------------------------
ROOT.uploadFile = function(file){
FILE = file;
MSGS = null;
selectedChannel = null;
currentPage = 1;
triggerUsersRefreshed();
triggerChannelsRefreshed();
triggerMessagesRefreshed();
};
ROOT.setUploadedFileName = function(name){
uploadedFileName = name;
};
ROOT.getChannelName = function(channel){
return FILE.getChannelById(channel).name;
};
ROOT.getUserName = function(user){
return FILE.getUserById(user).name;
};
ROOT.getUserTag = function(user){
return FILE.getUserById(user).tag;
};
// --------------------------
// Channel list and selection
// --------------------------
var getFilteredMessageKeys = function(channel){
var messages = FILE.getMessages(channel);
var keys = Object.keys(messages);
if (filterFunction){
keys = keys.filter(key => filterFunction(messages[key]));
}
return keys;
};
ROOT.getChannelList = function(){
if (!FILE){
return [];
}
var channels = FILE.getChannels();
return Object.keys(channels).map(key => ({
"id": key,
"name": channels[key].name,
"server": FILE.getServer(channels[key].server),
"msgcount": getFilteredMessageKeys(key).length,
"topic": channels[key].topic || "",
"nsfw": channels[key].nsfw || false,
"position": channels[key].position || -1
})).sort((ac, bc) => {
var as = ac.server;
var bs = bc.server;
return as.type.localeCompare(bs.type, "en") ||
as.name.toLocaleLowerCase().localeCompare(bs.name.toLocaleLowerCase(), undefined, { numeric: true }) ||
ac.position - bc.position ||
ac.name.toLocaleLowerCase().localeCompare(bc.name.toLocaleLowerCase(), undefined, { numeric: true });
});
};
ROOT.selectChannel = function(channel){
currentPage = 1;
selectedChannel = channel;
MSGS = getFilteredMessageKeys(channel).sort(PROCESSOR.SORTER.oldestToNewest);
triggerMessagesRefreshed();
};
ROOT.getSelectedChannel = function(){
return selectedChannel;
};
// ------------
// Message list
// ------------
ROOT.getMessageList = function(){
if (!MSGS){
return [];
}
var messages = FILE.getMessages(selectedChannel);
var startIndex = messagesPerPage*(ROOT.getCurrentPage()-1);
return MSGS.slice(startIndex, !messagesPerPage ? undefined : startIndex+messagesPerPage).map(key => {
var message = messages[key];
var user = FILE.getUser(message.u);
var avatar = user.avatar ? { id: FILE.getUserId(message.u), path: user.avatar } : null;
var reply = ("r" in message && message.r in messages) ? messages[message.r] : null;
var replyUser = reply ? FILE.getUser(reply.u) : null;
var replyAvatar = replyUser && replyUser.avatar ? { id: FILE.getUserId(reply.u), path: replyUser.avatar } : null;
var replyObj = reply ? {
"id": message.r,
"user": replyUser,
"avatar": replyAvatar,
"contents": reply.m
} : null;
return {
"user": user,
"avatar": avatar,
"timestamp": message.t,
"contents": ("m" in message) ? message.m : null,
"embeds": message.e,
"attachments": message.a,
"edit": ("te" in message) ? message.te : (message.f & 1) === 1,
"jump": key,
"reply": replyObj,
"reactions": ("re" in message) ? message.re : null
};
});
};
ROOT.navigateToMessage = function(id){
if (!MSGS){
return 0;
}
var index = MSGS.indexOf(id);
if (index == -1){
return 0;
}
currentPage = Math.max(1, Math.min(ROOT.getPageCount(), 1 + Math.floor(index / messagesPerPage)));
triggerMessagesRefreshed();
return index % messagesPerPage;
};
// ----------
// Filtering
// ----------
ROOT.hasActiveFilter = false;
ROOT.setActiveFilter = function(filter){
switch(filter ? filter.type : ""){
case "user":
filterFunction = PROCESSOR.FILTER.byUser(FILE.getUserIndex(filter.value));
break;
case "contents":
filterFunction = PROCESSOR.FILTER.byContents(filter.value);
break;
case "withimages":
filterFunction = PROCESSOR.FILTER.withImages();
break;
case "withdownloads":
filterFunction = PROCESSOR.FILTER.withDownloads();
break;
case "edited":
filterFunction = PROCESSOR.FILTER.isEdited();
break;
default:
filterFunction = null;
break;
}
ROOT.hasActiveFilter = filterFunction != null;
triggerChannelsRefreshed(selectedChannel);
if (selectedChannel){
ROOT.selectChannel(selectedChannel); // resets current page and updates messages
}
};
ROOT.saveFilteredMessages = function(){
var saveFileName = "dht-filtered.txt";
if (uploadedFileName){
if (uploadedFileName.includes("filtered")){
saveFileName = uploadedFileName;
}
else{
saveFileName = uploadedFileName.replace(".", "-filtered.");
}
}
DOM.downloadTextFile(saveFileName, FILE.filterToJson(filterFunction));
};
// -----
// Users
// -----
ROOT.getUserList = function(){
return FILE ? FILE.getUsers() : [];
};
// ----------
// Pagination
// ----------
ROOT.setMessagesPerPage = function(amount){
messagesPerPage = amount;
triggerMessagesRefreshed();
};
ROOT.updateCurrentPage = function(action){
switch(action){
case "first": currentPage = 1; break;
case "prev": currentPage = Math.max(1, currentPage-1); break;
case "next": currentPage = Math.min(ROOT.getPageCount(), currentPage+1); break;
case "last": currentPage = ROOT.getPageCount(); break;
case "pick":
var page = parseInt(prompt("Select page:", currentPage), 10);
if (!page && page !== 0){
return;
}
currentPage = Math.max(1, Math.min(ROOT.getPageCount(), page));
break;
}
triggerMessagesRefreshed();
};
ROOT.getCurrentPage = function(){
var total = ROOT.getPageCount();
if (currentPage > total && total > 0){
currentPage = total;
}
return currentPage || 1;
};
ROOT.getPageCount = function(){
return !MSGS ? 0 : (!messagesPerPage ? 1 : Math.ceil(MSGS.length/messagesPerPage));
};
// --------
// Settings
// --------
ROOT.settings = {};
var getStorageItem = (property) => {
try{
return localStorage.getItem(property);
}catch(e){
console.error(e);
return null;
}
};
var setStorageItem = (property, value) => {
try{
localStorage.setItem(property, value);
}catch(e){
console.error(e);
}
};
var defineSettingProperty = (property, defaultValue, storageToValue) => {
var name = "_"+property;
Object.defineProperty(ROOT.settings, property, {
get: (() => ROOT.settings[name]),
set: (value => {
ROOT.settings[name] = value;
triggerMessagesRefreshed();
setStorageItem(property, value);
})
});
var stored = getStorageItem(property);
if (stored !== null){
stored = storageToValue(stored);
}
ROOT.settings[name] = stored === null ? defaultValue : stored;
};
var fromBooleanString = (value) => {
if (value === "true") return true;
if (value === "false") return false;
return null;
};
defineSettingProperty("enableImagePreviews", true, fromBooleanString);
defineSettingProperty("enableFormatting", true, fromBooleanString);
defineSettingProperty("enableUserAvatars", true, fromBooleanString);
defineSettingProperty("enableAnimatedEmoji", true, fromBooleanString);
// End
return ROOT;
})();

View File

@ -1,20 +0,0 @@
var TEMPLATE_REGEX = /{([^{}]+?)}/g;
class TEMPLATE{
constructor(contents){
this.contents = contents;
};
apply(obj, processor){
return this.contents.replace(TEMPLATE_REGEX, (full, match) => {
var value = match.split(".").reduce((o, property) => o[property], obj);
if (processor){
var updated = processor(match, value);
return typeof updated === "undefined" ? DOM.escapeHTML(value) : updated;
}
return DOM.escapeHTML(value);
});
}
}

View File

@ -1,42 +0,0 @@
#channels {
width: 15vw;
min-width: 215px;
max-width: 300px;
overflow-y: auto;
background-color: #1C1E22;
}
#channels > div {
cursor: pointer;
padding: 10px 12px;
color: #eee;
font-size: 15px;
border-bottom: 1px solid #333333;
}
#channels > div:hover, #channels > div.active {
background-color: #282B30;
}
#channels .info {
display: flex;
height: 16px;
margin-bottom: 4px;
}
#channels .name {
flex-grow: 1;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
#channels .tag {
flex-shrink: 1;
background-color: rgba(255, 255, 255, 0.08);
border-radius: 4px;
margin-left: 4px;
margin-top: 1px;
padding: 2px 5px;
font-size: 11px;
}

View File

@ -1,24 +0,0 @@
body {
font-family: Whitney, "Helvetica Neue", Helvetica, Verdana, "Lucida Grande", sans-serif;
line-height: 1;
margin: 0;
padding: 0;
overflow: hidden;
}
body.embedded .hide-embedded {
display: none;
}
#menu {
width: 100%;
height: 48px;
display: flex;
flex-direction: row;
}
#app {
height: calc(100vh - 48px);
display: flex;
flex-direction: row;
}

View File

@ -1,82 +0,0 @@
#menu {
background-color: #17181C;
border-bottom: 1px dotted #5D626B;
}
#menu .splitter {
width: 1px;
margin: 9px 4px;
background-color: #5D626B;
}
#menu .separator {
flex: 1 1 0;
}
#menu :disabled {
background-color: #555;
cursor: default;
}
#menu button, #menu select, #menu input[type="text"] {
margin: 8px;
background-color: #7289DA;
color: #FFF;
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.75);
}
#menu button {
font-size: 17px;
padding: 0 12px;
border: 0;
cursor: pointer;
}
#menu select {
font-size: 14px;
padding: 6px;
border: 0;
cursor: pointer;
}
#menu input[type="text"] {
font-size: 14px;
padding: 7px 12px;
border: 0;
}
#menu .nav {
display: flex;
flex-direction: row;
margin: 0 8px;
}
#menu .nav > button {
font-size: 14px;
}
#menu .nav > button.icon {
font-family: Lucida Console, monospace;
font-size: 17px;
padding: 0 8px;
}
#menu .nav > button, #menu .nav > p {
margin: 8px 1px;
}
#opt-filter-list > select, #opt-filter-list > input {
display: none;
}
#opt-filter-list > .active {
display: block;
}
#opt-save-filtered {
display: flex;
}
#opt-save-filtered:not(.active) {
display: none;
}

View File

@ -1,254 +0,0 @@
#messages {
flex: 1 1 0;
overflow-y: auto;
background-color: #36393E;
}
#messages > div {
margin: 0 24px;
padding: 4px 0 12px;
border-bottom: 1px solid rgba(255, 255, 255, 0.04);
}
#messages h2 {
margin: 0;
padding: 0;
display: block;
}
#messages .avatar-wrapper {
display: flex;
flex-direction: row;
align-items: flex-start;
align-content: flex-start;
}
#messages .avatar-wrapper > div {
flex: 1 1 auto;
}
#messages .avatar {
flex: 0 0 38px !important;
margin: 8px 14px 0 0;
}
#messages .avatar img {
width: 38px;
border-radius: 50%;
}
#messages .username {
color: #FFF;
font-size: 15px;
font-weight: 600;
margin-right: 3px;
letter-spacing: 0;
}
#messages .info {
color: rgba(255, 255, 255, 0.4);
font-size: 12px;
font-weight: 500;
letter-spacing: 0;
}
#messages .info::before {
content: "\2022";
text-align: center;
display: inline-block;
width: 14px;
}
#messages .jump {
cursor: pointer;
text-decoration: underline;
text-underline-offset: 2px;
}
.message {
margin-top: 6px;
color: rgba(255, 255, 255, 0.7);
font-size: 15px;
line-height: 1.1em;
white-space: pre-wrap;
word-wrap: break-word;
}
.message .link, .reply-message .link {
color: #7289DA;
background-color: rgba(115, 139, 215, 0.1);
}
.message a, .reply-message a {
color: #0096CF;
text-decoration: none;
}
.message a:hover {
text-decoration: underline;
}
.message p {
margin: 0;
}
.message .embed {
display: inline-block;
margin-top: 8px;
}
.message .embed .title {
font-weight: bold;
display: inline-block;
}
.message .embed .desc {
margin-top: 4px;
}
.message .thumbnail {
max-width: calc(100% - 20px);
max-height: 320px;
}
.message .thumbnail img {
max-width: 100%;
max-height: 320px;
border-radius: 3px;
}
.message .download {
margin-right: 8px;
padding: 8px 9px;
border: 1px solid rgba(255, 255, 255, 0.5);
border-radius: 3px;
}
.message .embed:first-child, .message .download + .download {
margin-top: 0;
}
.message code {
background-color: #2E3136;
border-radius: 5px;
font-family: Menlo, Consolas, Monaco, monospace;
font-size: 14px;
}
.message code.inline {
display: inline;
padding: 2px;
}
.message code.block {
display: block;
border: 2px solid #282B30;
margin-top: 6px;
padding: 7px;
}
.message .emoji {
width: 22px;
height: 22px;
margin: 0 1px;
vertical-align: -30%;
object-fit: contain;
}
.reply-message {
display: flex;
align-items: baseline;
flex-wrap: wrap;
line-height: 120%;
white-space: nowrap;
}
.reply-message-with-avatar {
margin: 0 0 -2px 52px;
}
.reply-message .jump {
color: rgba(255, 255, 255, 0.4);
font-size: 12px;
text-underline-offset: 1px;
margin-right: 7px;
}
.reply-message .emoji {
width: 16px;
height: 16px;
vertical-align: -20%;
object-fit: contain;
}
.reply-message .user {
margin-right: 5px;
}
.reply-avatar {
margin-right: 4px;
}
.reply-avatar img {
width: 16px;
border-radius: 50%;
vertical-align: middle;
}
.reply-username {
color: #FFF;
font-size: 12px;
font-weight: 600;
letter-spacing: 0;
}
.reply-contents {
display: inline-block;
color: rgba(255, 255, 255, 0.7);
font-size: 12px;
max-width: calc(80%);
}
.reply-contents p {
margin: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.reply-contents code {
background-color: #2E3136;
font-family: Menlo, Consolas, Monaco, monospace;
padding: 1px 2px;
}
.reactions {
margin-top: 4px;
}
.reactions .reaction-wrapper {
display: inline-block;
border-radius: 4px;
margin: 3px 2px 0 0;
padding: 3px 6px;
background: #42454a;
cursor: default;
}
.reactions .reaction-emoji {
margin-right: 5px;
font-size: 16px;
display: inline-block;
text-align: center;
vertical-align: -5%;
}
.reactions .reaction-emoji-custom {
height: 15px;
margin-right: 5px;
vertical-align: -10%;
}
.reactions .count {
color: rgba(255, 255, 255, 0.45);
font-size: 14px;
}

View File

@ -1,51 +0,0 @@
#modal div {
position: absolute;
display: none;
}
#modal.visible div {
display: block;
}
#modal #overlay {
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: #000;
}
#modal.visible #overlay {
opacity: 0.5;
}
#dialog {
left: 50%;
top: 50%;
padding: 16px;
background-color: #fff;
transform: translateY(-50%);
}
#dialog p {
line-height: 1.2;
}
#dialog p:first-child, #dialog p:last-child {
margin-top: 1px;
margin-bottom: 1px;
}
#dialog sub {
color: #999;
font-size: 12px;
}
#dialog a {
color: #0096CF;
text-decoration: none;
}
#dialog a:hover {
text-decoration: underline;
}

View File

@ -1,3 +1 @@
<IfModule mod_expires.c>
ExpiresActive Off
</IfModule>
Redirect permanent / https://dht.chylex.com/browser-only/

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

View File

@ -4,7 +4,7 @@
<meta charset="utf-8">
<meta name="robots" content="index,follow">
<meta name="author" content="chylex">
<meta name="description" content="Discord History Tracker - Browser script to save history of Discord servers and private conversations">
<meta name="description" content="Discord History Tracker - Save history of Discord servers and private conversations">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Discord History Tracker</title>
@ -13,14 +13,14 @@
</head>
<body>
<div class="inner">
<h1>Discord History Tracker <span class="version">{{{version:web}}}</span>&nbsp;<span class="bar">|</span>&nbsp;<span class="notes"><a href="https://github.com/chylex/Discord-History-Tracker/wiki/Release-Notes">Release&nbsp;Notes</a></span></h1>
<h1>Discord History Tracker&nbsp;<span class="bar">|</span>&nbsp;<span class="notes"><a href="https://github.com/chylex/Discord-History-Tracker/releases">Release&nbsp;Notes</a></span></h1>
<p>Discord History Tracker lets you save chat history in your servers, groups, and private conversations, and view it offline.</p>
<p>You can use Discord History Tracker either <a href="#browser-only">entirely in your browser</a>, or download a <a href="#desktop-app">desktop app</a> for Windows / Linux / Mac. While the browser-only method is simpler and works on any device that has a modern web browser, it has significant limitations and fewer features than the app. Please read about both methods below.</p>
<img src="img/tracker.png" width="851" class="dht bordered">
<h2 id="desktop-app">Method 1: Desktop App</h2>
<p>The app can be downloaded from <a href="https://github.com/chylex/Discord-History-Tracker/releases">GitHub</a>. Every release includes 4 versions:</p>
<p>This page explains how to use the desktop app, which is available for Windows / Linux / Mac.</p>
<p>If you are looking for the older version of Discord History Tracker which only needs a browser or the Discord app, visit the page for the <a href="https://dht.chylex.com/browser-only">browser-only version</a>, however keep in mind that this version has <strong>significant limitations and fewer features</strong>.</p>
<h2>How to Use</h2>
<p>The desktop app can be downloaded from <a href="https://github.com/chylex/Discord-History-Tracker/releases">GitHub</a>. Every release includes 4 versions:</p>
<ul>
<li><strong>win-x64</strong> is for Windows (64-bit)</li>
<li><strong>linux-x64</strong> is for Linux (64-bit)</li>
@ -28,19 +28,18 @@
<li><strong>portable</strong> requires <a href="https://dotnet.microsoft.com/download/dotnet/5.0/runtime" rel="nofollow noopener">.NET 5</a> to be installed, but should run on any operating system supported by .NET</li>
</ul>
<p>For the non-portable versions: extract the <strong>DiscordHistoryTracker</strong> file into a folder, and double-click it to launch the app.<br>For the portable version: extract it into a folder, open the folder in a terminal and type: <code>dotnet DiscordHistoryTracker.dll</code></p>
<h3>How to Track Messages</h3>
<p>The app saves messages into a database file stored on your computer. When you open the app, you are given the option to create a new database file, or open an existing one.</p>
<p>In the <strong>Tracking</strong> tab, click <strong>Copy Tracking Script</strong> to generate a tracking script that works similarly to the browser-only version of Discord History Tracker, but instead of saving messages in the browser, the tracking script sends them to the app which saves them in the database file.</p>
<img src="img/app-tracker.png" class="dht bordered" alt="Screenshot of the App (Tracker tab)">
<p>See <strong>Option 2: Browser / Discord Console</strong> above for more detailed instructions on how to paste the tracking script into the browser or Discord app console.</p>
<p>When using the script for the first time, you will see a <strong>Settings</strong> dialog where you can configure the script. These settings will be remembered as long as you don't delete cookies in your browser.</p>
<p>By default, Discord History Tracker is set to automatically scroll up to load the channel history, and pause tracking if it reaches a previously saved message to avoid unnecessary history loading.</p>
<h3>How to View History</h3>
<p>In the <strong>Viewer</strong> tab, you can open a viewer in your browser, or save it as a file you can open in your browser later. You also have the option to apply filters to only view a portion of the saved messages.</p>
<img src="img/app-viewer.png" class="dht bordered" alt="Screenshot of the App (Viewer tab)">
<h3>Technical Details</h3>
<ol>
<li>The app uses SQLite, which means that you can use SQL to manually query or manipulate the database file.</li>
@ -48,70 +47,6 @@
<li>You can use the <code>-port &lt;p&gt;</code> and <code>-token &lt;t&gt;</code> command line arguments to configure the server manually &mdash; otherwise, they will be assigned automatically in a way that allows running multiple separate instances of the app.</li>
</ol>
<h2 id="browser-only">Method 2: Browser-Only</h2>
<p>A tracking script will load messages according to your settings, and save them in your browser.</p>
<p>Because everything happens in your browser, if the browser tab is closed, or your browser or computer crashes, you will lose all progress. Your browser may also be unable to process large amounts of messages. If this is a concern, use the app method.</p>
<h3>Setup the Tracking Script</h3>
<h4>Option 1: Userscript</h4>
<div class="quote">
<p><strong>Preferred option.</strong> Requires a browser addon, but DHT will stay up-to-date and be easily accessible on the Discord website.</p>
<ol>
<li>Install a userscript manager addon:
<ul>
<li><a href="https://violentmonkey.github.io/get-it/">Violentmonkey</a> (Chrome)</li>
<li><a href="https://tampermonkey.net/">Tampermonkey</a> (Firefox, Edge, Chrome, Opera)</li>
<li>Due to browser bugs / limitations, DHT will not work in <strong>Firefox</strong> with Greasemonkey / Violentmonkey, and in <strong>Safari</strong> at all</li>
</ul>
</li>
<li>Click <a href="build/track.user.js">Install Userscript</a> to prompt an installation into the userscript manager</li>
<li>Open <a href="https://discord.com/channels/@me" rel="noreferrer">Discord</a>, and view any server, group, or private conversation (it will not appear in Friends list)</li>
<li>Click <strong>DHT</strong> in the top right corner:<br><img src="img/button.png" class="bordered"></li>
</ol>
</div>
<h4>Option 2: Browser / Discord Console</h4>
<div class="quote">
<p>The console is the only way to use DHT directly in the desktop app.</p>
<ol>
<li>Click <a href="javascript:" id="tracker-copy-button" onauxclick="return false;">Copy to Clipboard</a> to copy the tracking script
<noscript> (requires JavaScript)</noscript>
</li>
<li>Press <strong>Ctrl</strong>+<strong>Shift</strong>+<strong>I</strong> in your browser or the Discord app, and select the <strong>Console</strong> tab</li>
<li>Paste the script into the console, and press <strong>Enter</strong> to run it</li>
<li>Press <strong>Ctrl</strong>+<strong>Shift</strong>+<strong>I</strong> again to close the console</li>
</ol>
<p id="tracker-copy-issue">Your browser may not support copying to clipboard, please try copying the script manually:</p>
<textarea id="tracker-copy-contents"><?php include './build/track.html'; ?></textarea>
</div>
<h4>Option 3: Bookmarklet</h4>
<div class="quote">
<p>Requires Firefox 69 or newer.</p>
<ol>
<li>Right-click <a href="<?php include './build/track.html'; ?>" onclick="return false;" onauxclick="return false;">Discord History Tracker</a></li>
<li>Select &laquo;Bookmark This Link&raquo; and save the bookmark</li>
<li>Open <a href="https://discord.com/channels/@me" rel="noreferrer">Discord</a> and click the bookmark to run the script</li>
</ol>
</div>
<h4>Old Versions</h4>
<p>Whenever DHT is updated to work with a new version of Discord, it may no longer work with the previous version of Discord.</p>
<p>If you haven't received that Discord update yet, see <a href="https://github.com/chylex/Discord-History-Tracker/wiki/Release-Notes">Release Notes</a> for information about recent updates, and <a href="https://github.com/chylex/Discord-History-Tracker/wiki/Old-Versions">Old Versions</a> if you need to use an older version of DHT.</p>
<h3>How to Track Messages</h3>
<p>When using the script for the first time, you will see a <strong>Settings</strong> dialog where you can configure the script. These settings will be remembered as long as you don't delete cookies in your browser.</p>
<p>By default, Discord History Tracker is set to automatically scroll up to load the channel history, and pause tracking if it reaches a previously saved message to avoid unnecessary history loading.</p>
<p>Before you <strong>Start Tracking</strong>, you may use <strong>Upload &amp; Combine</strong> to load messages from a previously saved archive file into the browser.</p>
<p>When you click <strong>Download</strong>, the browser will generate an archive file from saved messages, and lets you save it to your computer.</p>
<h3>How to View History</h3>
<p>First, save the <a href="build/viewer.html">Viewer</a> file to your computer. Then you can open the downloaded viewer in your browser, click <strong>Load File</strong>, and select the archive to view.</p>
<h2>External Links</h2>
<p class="links">
<a href="https://github.com/chylex/Discord-History-Tracker/issues">Issues&nbsp;&amp;&nbsp;Suggestions</a>&nbsp;&nbsp;&mdash;&nbsp;
@ -121,32 +56,5 @@
<a href="https://ko-fi.com/chylex">Support&nbsp;via&nbsp;Ko-fi</a>
</p>
</div>
<script type="text/javascript">
var contents = document.getElementById("tracker-copy-contents");
var issue = document.getElementById("tracker-copy-issue");
var button = document.getElementById("tracker-copy-button");
if (document.queryCommandSupported("copy")) {
contents.style.display = "none";
issue.style.display = "none";
}
button.addEventListener("click", function() {
contents.style.display = "block";
issue.style.display = "block";
contents.select();
document.execCommand("copy");
button.innerHTML = "Copied to Clipboard";
contents.style.display = "none";
issue.style.display = "none";
});
contents.addEventListener("click", function() {
contents.select();
});
</script>
</body>
</html>

View File

@ -132,14 +132,3 @@ code {
overflow: hidden;
text-overflow: ellipsis;
}
#tracker-copy-contents {
width: 100%;
height: 82px;
padding: 4px;
color: rgba(255, 255, 255, 0.8);
background: rgba(255, 255, 255, 0.2);
border: none;
resize: none;
box-sizing: border-box;
}