Tip: Use a colour with transparancy set, to respect light and dark themes. Example: rgb(100,0,100,0.4)
Tip2: Do you want a faded image, staying fixed in place, and filling the screen? This is how:
linear-gradient(rgb(var(--color-background),0.8),rgb(var(--color-background),0.8)),url(https://www.example.com/myBackground.jpg) center/100% fixed
`,
backgroundSettings);
let inputField = create("input",false,false,backgroundSettings);
inputField.value = useScripts.profileBackgroundValue;
create("br",false,false,backgroundSettings);
let backgroundChange = create("button",["hohButton","button"],"Submit",backgroundSettings);
backgroundChange.onclick = function(){
useScripts.profileBackgroundValue = inputField.value;
useScripts.save();
let jsonMatch = userObject.about.match(/^/);
let profileJson = {};
if(jsonMatch){
try{
profileJson = JSON.parse(jsonMatch[1]);
}
catch(e){
console.warn("Invalid profile JSON");
};
}
profileJson.background = useScripts.profileBackgroundValue;
let newDescription = "" + (userObject.about.replace(/^/,""));
authAPIcall(
`mutation($about: String){
UpdateUser(about: $about){
about
}
}`,
{about: newDescription},function(data){/*later*/}
);
};
hohSettings.appendChild(create("hr"));
};
if(useScripts.customCSS && useScripts.accessToken){
let backgroundSettings = create("div",false,false,hohSettings);
create("p",false,"Add custom CSS to your profile. This will be visible to others.",backgroundSettings);
let inputField = create("textarea",false,false,backgroundSettings);
inputField.value = useScripts.customCSSValue;
create("br",false,false,backgroundSettings);
let backgroundChange = create("button",["hohButton","button"],"Submit",backgroundSettings);
backgroundChange.onclick = function(){
useScripts.customCSSValue = inputField.value;
useScripts.save();
let jsonMatch = userObject.about.match(/^/);
let profileJson = {};
if(jsonMatch){
try{
profileJson = JSON.parse(jsonMatch[1]);
}
catch(e){
console.warn("Invalid profile JSON");
};
}
profileJson.customCSS = useScripts.customCSSValue;
let newDescription = "" + (userObject.about.replace(/^/,""));
authAPIcall(
`mutation($about: String){
UpdateUser(about: $about){
about
}
}`,
{about: newDescription},function(data){/*later*/}
);
};
hohSettings.appendChild(create("hr"));
};
create("p",false,"Delete all custom settings. Re-installing the script will not do that by itself.",hohSettings);
let cleanEverything= create("button",["hohButton","button","danger"],"Default Settings",hohSettings);
cleanEverything.onclick = function(){
localStorage.removeItem("hohSettings");
window.location.reload(false);
}
create("hr","hohSeparator",false,hohSettings);
let loginURL = create("a",false,"Sign in with the script",hohSettings);
loginURL.href = authUrl;
loginURL.style.color = "rgb(var(--color-blue))";
create("p",false,"Enables or improves every module in the \"Login\" tab, improves those greyed out.",hohSettings);
}
function addMoreStats(){
if(!document.URL.match(/\/stats\/?/)){
return;
};
if(document.querySelector(".hohStatsTrigger")){
return;
};
let filterGroup = document.querySelector(".filter-wrap");
if(!filterGroup){
setTimeout(function(){
addMoreStats();
},200);//takes some time to load
return;
};
let hohStats;
let hohGenres;
let regularGenresTable;
let regularTagsTable;
let regularAnimeTable;
let regularMangaTable;
let animeStaff;
let mangaStaff;
let animeStudios;
let hohStatsTrigger = create("span","hohStatsTrigger","More stats",filterGroup);
let hohGenresTrigger = create("span","hohStatsTrigger","Genres & Tags",filterGroup);
let hohSiteStats = create("a","hohStatsTrigger","Site Stats",filterGroup);
hohSiteStats.href = "/site-stats";
let generateStatPage = function(){
let personalStats = create("div","#personalStats","loading anime list...",hohStats);
let personalStatsManga = create("div","#personalStatsManga","loading manga list...",hohStats);
let miscQueries = create("div","#miscQueries",false,hohStats);
create("hr","hohSeparator",false,miscQueries);
create("h1","hohStatHeading","Various queries",miscQueries);
let miscInput = create("div",false,false,miscQueries,"padding-top:10px;padding-bottom:10px;");
let miscOptions = create("div","#queryOptions",false,miscQueries);
let miscResults = create("div","#queryResults",false,miscQueries);
let user = decodeURIComponent(document.URL.match(/user\/(.+)\/stats\/?/)[1]);
const loginMessage = "Requires being signed in to the script. You can do that at the bottom of the settings page https://anilist.co/settings/apps";
let availableQueries = [
{name: "First Activity",code: function(){
generalAPIcall("query($name:String){User(name:$name){id}}",{name: user},function(data){
let userId = data.data.User.id;
let userFirstQuery =
`query ($userId: Int) {
Activity(sort: ID,userId: $userId){
... on MessageActivity {
id
createdAt
}
... on TextActivity {
id
createdAt
}
... on ListActivity {
id
createdAt
}
}
}`;
generalAPIcall(userFirstQuery,{userId: userId},function(data){
miscResults.innerText = "";
let newPage = create("a",false,"https://anilist.co/activity/" + data.data.Activity.id,miscResults,"color:rgb(var(--color-blue));padding-right:30px;");
newPage.href = "/activity/" + data.data.Activity.id;
let createdAt = data.data.Activity.createdAt;
create("span",false," " + (new Date(createdAt*1000)),miscResults);
let possibleOlder = create("p",false,false,miscResults);
for(var i=1;i<=15;i++){
generalAPIcall(userFirstQuery,{userId: userId + i},function(data){
if(!data){return};
if(data.data.Activity.createdAt < createdAt){
createdAt = data.data.Activity.createdAt;
possibleOlder.innerText = "But the account is known to exist already at " + (new Date(createdAt * 1000));
}
})
}
},"hohFirstActivity" + data.data.User.id,60*1000);
},"hohIDlookup" + user.toLowerCase());
}},
{name: "Rank",code: function(){
generalAPIcall(
"query($name:String){User(name:$name){name stats{watchedTime chaptersRead}}}",
{name: user},
function(data){
miscResults.innerText = "";
create("p",false,"NOTE: Due to an unfixed bug in the Anilist API, these results are increasingly out of date. This query is just kept here in case future changes allows it to work properly again.",miscResults);
create("p",false,"Time watched: " + (data.data.User.stats.watchedTime/(60*24)).roundPlaces(1) + " days",miscResults);
create("p",false,"Chapters read: " + data.data.User.stats.chaptersRead,miscResults);
let ranks = {
"anime": create("p",false,false,miscResults),
"manga": create("p",false,false,miscResults)
};
let recursiveCall = function(userName,amount,currentPage,minPage,maxPage,type){
ranks[type].innerText = capitalize(type) + " rank: [calculating...] range " + ((minPage - 1)*50 + 1) + " - " + (maxPage ? maxPage*50 : "");
generalAPIcall(
`
query($page:Int){
Page(page:$page){
pageInfo{lastPage}
users(sort:${type === "anime" ? "WATCHED_TIME_DESC" : "CHAPTERS_READ_DESC"}){
stats{${type === "anime" ? "watchedTime" : "chaptersRead"}}
}
}
}`,
{page: currentPage},
function(data){
if(!maxPage){
maxPage = data.data.Page.pageInfo.lastPage
}
let block = (
type === "anime"
? Array.from(data.data.Page.users,(a) => a.stats.watchedTime)
: Array.from(data.data.Page.users,(a) => a.stats.chaptersRead)
);
if(block[block.length - 1] > amount){
recursiveCall(userName,amount,Math.floor((currentPage + 1 + maxPage)/2),currentPage + 1,maxPage,type);
return;
}
else if(block[0] > amount){
block.forEach(function(item,index){
if(amount === item){
ranks[type].innerText = capitalize(type) + " rank: " + ((currentPage - 1)*50 + index + 1);
return;
};
});
}
else if(block[0] === amount){
if(minPage === currentPage){
ranks[type].innerText = capitalize(type) + " rank: " + ((currentPage-1)*50 + 1)
}
else{
recursiveCall(userName,amount,Math.floor((minPage + currentPage)/2),minPage,currentPage,type)
};
return;
}
else{
recursiveCall(userName,amount,Math.floor((minPage + currentPage - 1)/2),minPage,currentPage - 1,type);
return;
};
},"hohRank" + type + currentPage,60*60*1000
);
};
recursiveCall(user,data.data.User.stats.watchedTime,1000,1,undefined,"anime");
recursiveCall(user,data.data.User.stats.chaptersRead,500,1,undefined,"manga");
},"hohRankStats" + user,2*60*1000
);
}},
{name: "Hidden media entries",code: function(){
miscResults.innerText = "";
let pageCounter = create("p",false,false,miscResults);
let pager = function(page,user){
generalAPIcall(
`query ($userName: String,$page:Int) {
Page(page:$page){
pageInfo{
currentPage
lastPage
}
mediaList(userName:$userName){
hiddenFromStatusLists
mediaId
media{
type
title{romaji}
}
customLists(asArray:true)
}
}
}`,
{
page: page,
userName: user
},
function(data){
if(data.data.Page.pageInfo.currentPage < data.data.Page.pageInfo.lastPage){
setTimeout(function(){
pager(data.data.Page.pageInfo.currentPage + 1,user)
},800);
}
pageCounter.innerText = "Searching page " + data.data.Page.pageInfo.currentPage + " of " + data.data.Page.pageInfo.lastPage;
data.data.Page.mediaList.forEach(function(media){
if(
media.hiddenFromStatusLists
&& media.customLists.every(cl => cl.enabled === false)
){
create("a","newTab",media.media.title.romaji,miscResults,"display:block;")
.href = "/" + media.media.type.toLowerCase() + "/" + media.mediaId;
}
});
}
);
};pager(1,user);
}},
{name: "Notification count",code: function(){
if(useScripts.accessToken){
authAPIcall("query{Page{pageInfo{total}notifications{...on AiringNotification{id}}}}",{},function(data){
miscResults.innerText =
`${data.data.Page.pageInfo.total} notifications.
This is your notification count. The notifications of other users are private.`
})
}
else{
miscResults.innerText =
`Error: Not signed in with the script. Reading notifications requires AUTH permissions.
You can sign in with the script from the settings page.`
}
}},
{name: "Message Stats",code: function(){
generalAPIcall(
``,
{name: user},
function(data){
}
)
}},
{name: "Related anime not on list",code: function(){
generalAPIcall(
`query($name: String!){
MediaListCollection(userName: $name,type: ANIME){
lists{
entries{
mediaId
score
status
media{
relations{
nodes{
id
title{romaji}
type
}
}
}
}
}
}
}`,
{name: user},function(data){
let list = returnList(data,true);
let listEntries = new Set(list.map(a => a.mediaId));
let found = [];
list.forEach(function(media){
if(media.status !== "PLANNING"){
media.media.relations.nodes.forEach(function(relation){
if(!listEntries.has(relation.id) && relation.type === "ANIME"){
relation.host = media.score;
found.push(relation);
}
})
};
});
found = removeGroupedDuplicates(
found,
e => e.id,
(oldElement,newElement) => {
newElement.host = Math.max(oldElement.host,newElement.host)
}
).sort(
(b,a) => a.host - b.host
);
miscResults.innerText = "Found " + found.length + " shows:";
found.forEach(item => {
create("a",["link","newTab"],item.title.romaji,miscResults,"display:block;padding:5px;")
.href = "/anime/" + item.id
});
});
}},
{name: "Check compatibility with all following (slow)",setup: function(){
create("span",false,"List Type: ",miscOptions);
let select = create("select","#typeSelect",false,miscOptions);
let animeOption = create("option",false,"Anime",select);
let mangaOption = create("option",false,"Manga",select);
animeOption.value = "ANIME";
mangaOption.value = "MANGA";
},code: function(){
miscResults.innerText = "";
let loadingStatus = create("p",false,false,miscResults);
loadingStatus.innerText = "Looking up ID...";
generalAPIcall("query($name:String){User(name:$name){id}}",{name: user},function(data){
let userId = data.data.User.id;
let currentLocation = location.pathname;
loadingStatus.innerText = "Loading media list...";
let typeList = document.getElementById("typeSelect").value;
generalAPIcall(
queryMediaListCompat,
{
name: user,
listType: typeList
},
function(data){
loadingStatus.innerText = "Loading users...";
let comDisplay = create("div",false,false,miscResults);
let list = returnList(data).filter(element => element.scoreRaw);
let comCache = [];
let drawComCache = function(){
while(comDisplay.childElementCount){
comDisplay.lastChild.remove();
};
comCache.forEach(function(friend){
let userRow = create("p",false,false,comDisplay);
let differenceSpan = create("span",false,friend.difference.toPrecision(3),userRow,"min-width:60px;display:inline-block;");
if(friend.difference < 0.9){
differenceSpan.style.color = "green";
}
else if(friend.difference > 1.1){
differenceSpan.style.color = "red";
};
let friendLink = create("a","newTab",friend.user,userRow,"color:rgb(var(--color-blue))");
friendLink.href = "/user/" + friend.user;
create("span",false,", " + friend.shared + " shared.",userRow);
});
};
let friendsCaller = function(page){
generalAPIcall(
`query($id: Int!,$page: Int){
Page(page: $page){
pageInfo{
lastPage
}
following(userId: $id,sort: USERNAME){
name
}
}
}`,
{id: userId,page: page},
function(data){
let index = 0;
let delayer = function(){
if(location.pathname !== currentLocation){
return
}
loadingStatus.innerText = "Comparing with " + data.data.Page.following[index].name + "...";
compatCheck(list,data.data.Page.following[index].name,typeList,function(data){
if(data.difference){
comCache.push(data);
comCache.sort((a,b) => a.difference - b.difference);
drawComCache();
};
});
if(++index < data.data.Page.following.length){
setTimeout(delayer,1000)
}
else{
if(page < data.data.Page.pageInfo.lastPage){
friendsCaller(page + 1)
}
else{
loadingStatus.innerText = ""
}
}
};delayer(index);
}
)
};friendsCaller(1);
},"hohCompatANIME" + user,5*60*1000
);
},"hohIDlookup" + user.toLowerCase());
}},
{name: "Message spy",code: function(){
miscResults.innerText = "";
let page = 1;
let results = create("div",false,false,miscResults);
let moreButton = create("button",["button","hohButton"],"Load more",miscResults);
let getPage = function(page){
generalAPIcall(`
query($page: Int){
Page(page: $page){
activities(type: MESSAGE,sort: ID_DESC){
... on MessageActivity{
id
recipient{name}
message(asHtml: true)
pure:message(asHtml: false)
createdAt
messenger{name}
}
}
}
}`,
{page: page},
function(data){
data.data.Page.activities.forEach(function(message){
if(
message.pure.includes("AWC")
|| message.pure.match(/^.{0,8}(thanks|tha?n?x|thank|ty).*follow.{0,10}(http.*(jpg|png|gif))?.{0,10}$/i)
|| message.pure.match(/for( the)? follow/i)
){
return
};
let time = new Date(message.createdAt*1000);
let newElem = create("div","message",false,results);
create("span","time",time.toISOString().match(/^(.*)\.000Z$/)[1] + " ",newElem);
let user = create("a",["link","newTab"],message.messenger.name,newElem,"color:rgb(var(--color-blue))");
user.href = "/user/" + message.messenger.name;
create("span",false," sent a message to ",newElem);
let user2 = create("a",["link","newTab"],message.recipient.name,newElem,"color:rgb(var(--color-blue))");
user2.href = "/user/" + message.recipient.name;
let link = create("a",["link","newTab"]," Link",newElem);
link.href = "/activity/" + message.id;
newElem.innerHTML += message.message;
create("hr",false,false,results);
});
}
);
};getPage(page);
moreButton.onclick = function(){
page++;
getPage(page);
};
}},
{name: "Media statistics of friends",code: function(){
generalAPIcall("query($name:String){User(name:$name){id}}",{name: user},function(data){
generalAPIcall(
`
query($userId: Int!){
a1:Page(page:1){following(userId: $userId,sort: ID){... stuff}}
a2:Page(page:2){following(userId: $userId,sort: ID){... stuff}}
a3:Page(page:3){following(userId: $userId,sort: ID){... stuff}}
a4:Page(page:4){following(userId: $userId,sort: ID){... stuff}}
a5:Page(page:5){following(userId: $userId,sort: ID){... stuff}}
a6:Page(page:6){following(userId: $userId,sort: ID){... stuff}}
a7:Page(page:7){following(userId: $userId,sort: ID){... stuff}}
a8:Page(page:8){following(userId: $userId,sort: ID){... stuff}}
a9:Page(page:9){following(userId: $userId,sort: ID){... stuff}}
a10:Page(page:10){following(userId: $userId,sort: ID){... stuff}}
User(id: $userId){... stuff}
}
fragment stuff on User{
name
statistics{
anime{
count
minutesWatched
}
manga{
count
chaptersRead
volumesRead
}
}
stats{
watchedTime
chaptersRead
}
}`,
{userId: data.data.User.id},
function(stats){
let userList = [].concat(
...Object.keys(stats.data).map(
a => stats.data[a].following || []
)
);
userList.push(stats.data.User);
//API error polyfill
userList.forEach(function(wrong){
if(!wrong.statistics.anime.minutesWatched){
wrong.statistics.anime.minutesWatched = wrong.stats.watchedTime
}
if(!wrong.statistics.manga.chaptersRead){
wrong.statistics.manga.chaptersRead = wrong.stats.chaptersRead
}
});
userList.sort((b,a) => a.statistics.anime.minutesWatched - b.statistics.anime.minutesWatched);
miscResults.innerText = "";
let drawUserList = function(){
while(miscResults.childElementCount){
miscResults.lastChild.remove()
}
let table = create("div",["table","hohTable","hohNoPointer","good"],false,miscResults);
let headerRow = create("div",["header","row"],false,table);
let nameHeading = create("div",false,"Name",headerRow,"cursor:pointer;");
let animeCountHeading = create("div",false,"Anime Count",headerRow,"cursor:pointer;");
let animeTimeHeading = create("div",false,"Time Watched",headerRow,"cursor:pointer;");
let mangaCountHeading = create("div",false,"Manga Count",headerRow,"cursor:pointer;");
let mangaChapterHeading = create("div",false,"Chapters Read",headerRow,"cursor:pointer;");
let mangaVolumeHeading = create("div",false,"Volumes Read",headerRow,"cursor:pointer;");
userList.forEach(function(user,index){
let row = create("div","row",false,table);
if(user.name === stats.data.User.name || user.name === whoAmI){
row.style.color = "rgb(var(--color-blue))";
row.style.background = "rgb(var(--color-background))";
}
let nameCel = create("div",false,(index + 1) + " ",row);
let userLink = create("a",["link","newTab"],user.name,nameCel);
userLink.href = "/user/" + user.name;
create("div",false,user.statistics.anime.count,row);
let timeString = formatTime(user.statistics.anime.minutesWatched*60);
if(!user.statistics.anime.minutesWatched){
timeString = "-"
}
create("div",false,timeString,row);
create("div",false,user.statistics.manga.count,row);
if(user.statistics.manga.chaptersRead){
create("div",false,user.statistics.manga.chaptersRead,row)
}
else{
create("div",false,"-",row)
}
if(user.statistics.manga.volumesRead){
create("div",false,user.statistics.manga.volumesRead,row)
}
else{
create("div",false,"-",row)
}
});
nameHeading.onclick = function(){
userList.sort(ALPHABETICAL(a => a.name));
drawUserList();
};
animeCountHeading.onclick = function(){
userList.sort((b,a) => a.statistics.anime.count - b.statistics.anime.count);
drawUserList();
};
animeTimeHeading.onclick = function(){
userList.sort((b,a) => a.statistics.anime.minutesWatched - b.statistics.anime.minutesWatched);
drawUserList();
};
mangaCountHeading.onclick = function(){
userList.sort((b,a) => a.statistics.manga.count - b.statistics.manga.count);
drawUserList();
};
mangaChapterHeading.onclick = function(){
userList.sort((b,a) => a.statistics.manga.chaptersRead - b.statistics.manga.chaptersRead);
drawUserList();
};
mangaVolumeHeading.onclick = function(){
userList.sort((b,a) => a.statistics.manga.volumesRead - b.statistics.manga.volumesRead);
drawUserList();
};
};drawUserList();
}
)
},"hohIDlookup" + user.toLowerCase());
}},
{name: "Most popular favourites of friends",code: function(){
generalAPIcall("query($name:String){User(name:$name){id}}",{name: user},function(data){
generalAPIcall(
`
query($userId: Int!){
a1:Page(page:1){following(userId: $userId,sort: ID){... stuff}}
a2:Page(page:2){following(userId: $userId,sort: ID){... stuff}}
a3:Page(page:3){following(userId: $userId,sort: ID){... stuff}}
a4:Page(page:4){following(userId: $userId,sort: ID){... stuff}}
a5:Page(page:5){following(userId: $userId,sort: ID){... stuff}}
a6:Page(page:6){following(userId: $userId,sort: ID){... stuff}}
a7:Page(page:7){following(userId: $userId,sort: ID){... stuff}}
a8:Page(page:8){following(userId: $userId,sort: ID){... stuff}}
a9:Page(page:9){following(userId: $userId,sort: ID){... stuff}}
a10:Page(page:10){following(userId: $userId,sort: ID){... stuff}}
User(id: $userId){... stuff}
}
fragment stuff on User{
name
favourites{
anime1:anime(page:1){
nodes{
id
title{romaji}
}
}
anime2:anime(page:2){
nodes{
id
title{romaji}
}
}
manga1:manga(page:1){
nodes{
id
title{romaji}
}
}
manga2:manga(page:2){
nodes{
id
title{romaji}
}
}
}
}`,
{userId: data.data.User.id},
function(foll){
let userList = [].concat(
...Object.keys(foll.data).map(
a => foll.data[a].following || []
)
);
let me = foll.data.User;
me.favourites.anime = me.favourites.anime1.nodes.concat(me.favourites.anime2.nodes);
delete me.favourites.anime1;
delete me.favourites.anime2;
me.favourites.manga = me.favourites.manga1.nodes.concat(me.favourites.manga2.nodes);
delete me.favourites.manga1;
delete me.favourites.manga2;
let animeFavs = {};
let mangaFavs = {};
userList.forEach(function(user){
user.favourites.anime = user.favourites.anime1.nodes.concat(user.favourites.anime2.nodes);
delete user.favourites.anime1;
delete user.favourites.anime2;
user.favourites.anime.forEach(fav => {
if(animeFavs[fav.id]){
animeFavs[fav.id].count++
}
else{
animeFavs[fav.id] = {
count: 1,
title: fav.title.romaji
}
}
});
user.favourites.manga = user.favourites.manga1.nodes.concat(user.favourites.manga2.nodes);
delete user.favourites.manga1;
delete user.favourites.manga2;
user.favourites.manga.forEach(fav => {
if(mangaFavs[fav.id]){
mangaFavs[fav.id].count++
}
else{
mangaFavs[fav.id] = {
count: 1,
title: fav.title.romaji
}
}
})
});
miscResults.innerText = "";
create("h1",false,"Anime:",miscResults,"color:rgb(var(--color-blue))");
Object.keys(animeFavs).map(key => animeFavs[key]).sort((b,a) => a.count - b.count).slice(0,20).forEach(function(entry){
create("p",false,entry.count + ": " + entry.title,miscResults)
});
create("h1",false,"Manga:",miscResults,"color:rgb(var(--color-blue))");
Object.keys(mangaFavs).map(key => mangaFavs[key]).sort((b,a) => a.count - b.count).slice(0,20).forEach(function(entry){
create("p",false,entry.count + ": " + entry.title,miscResults)
});
create("h1",false,"Similar favs:",miscResults,"color:rgb(var(--color-blue))");
let sharePerc = user => {
let total = user.favourites.anime.length + user.favourites.manga.length + me.favourites.anime.length + me.favourites.manga.length;
let shared = user.favourites.anime.filter(
a => me.favourites.anime.some(
b => a.id === b.id
)
).length + user.favourites.manga.filter(
a => me.favourites.manga.some(
b => a.id === b.id
)
).length;
return shared/total;
};
userList.sort((b,a) => sharePerc(a) - sharePerc(b));
userList.slice(0,10).forEach(entry => {
let row = create("p",false,false,miscResults);
create("a","newTab",entry.name,row)
.href = "/user/" + entry.name
});
}
)
},"hohIDlookup" + user.toLowerCase());
}},
{name: "Fix your dating mess",code: function(){
generalAPIcall("query($name:String){User(name:$name){id}}",{name: user},function(iddata){
let delay = 0;
miscResults.innerText = "";
while(miscResults.childElementCount){
miscResults.lastChild.remove()
};
while(miscOptions.childElementCount){
miscOptions.lastChild.remove()
};
let config = [
{
description: "Completion date before start date",
code: media => fuzzyDateCompare(media.startedAt,media.completedAt) === 0
},{
description: "Completion date before official end date",
code: media => fuzzyDateCompare(media.media.endDate,media.completedAt) === 0
},{
description: "Start date before official release date",
code: media => fuzzyDateCompare(media.media.startDate,media.startedAt) === 0
},{
description: "Status completed but no completion date set",
code: media => media.status === "COMPLETED" && !media.completedAt.year
},{
description: "Status completed but no start date set",
code: media => media.status === "COMPLETED" && !media.startedAt.year
},{
description: "Status dropped but no start date set",
code: media => media.status === "DROPPED" && !media.startedAt.year
},{
description: "Status current but no start date set",
code: media => media.status === "CURRENT" && !media.startedAt.year
},{
description: "Planning entry with start date",
code: media => media.status === "PLANNING" && media.startedAt.year
},{
description: "Dates in the far future or past",
code: media => (
media.startedAt.year && (media.startedAt.year < 1960 || media.startedAt.year > (new Date().getFullYear() + 3))
) || (
media.completedAt.year && (media.completedAt.year < 1960 || media.completedAt.year > (new Date().getFullYear() + 3))
)
}
];
config.forEach(function(setting){
let row = create("p",false,false,miscOptions);
let checkBox = createCheckbox(row);
let label = create("span",false,setting.description,row);
checkBox.checked = true;
checkBox.onchange = function(){
Array.from(miscResults.children).forEach(res => {
if(res.children[1].innerText === setting.description){
if(checkBox.checked){
res.style.display = "block"
}
else{
res.style.display = "none"
}
}
});
};
});
let proc = function(data){
let list = returnList(data,true);
list.forEach(function(item){
let matches = [];
config.forEach(setting => {
if(setting.code(item)){
matches.push(setting.description)
}
});
if(matches.length){
let row = create("p",false,false,miscResults);
let link = create("a",["link","newTab"],item.media.title.romaji,row,"width:440px;display:inline-block;");
link.href = "/" + item.media.type.toLowerCase() + "/" + item.mediaId + "/" + safeURL(item.media.title.romaji);
create("span",false,matches.join(", "),row);
let chance = create("p",false,false,row,"margin-left:20px;margin-top: 2px;");
create("span",false,"Entry created: " + (new Date(item.createdAt*1000)).toISOString().split("T")[0] + " \n",chance);
if(
(new Date(item.createdAt*1000)).toISOString().split("T")[0]
!== (new Date(item.updatedAt*1000)).toISOString().split("T")[0]
){
create("span",false,"Entry updated: " + (new Date(item.updatedAt*1000)).toISOString().split("T")[0] + " \n",chance);
}
if(item.repeat){
create("span",false,"Repeats: " + item.repeat + " \n",chance);
}
setTimeout(function(){
generalAPIcall(
`
query($userId: Int,$mediaId: Int){
first:Activity(userId: $userId,mediaId: $mediaId,sort: ID){... on ListActivity{createdAt siteUrl status progress}}
last:Activity(userId: $userId,mediaId: $mediaId,sort: ID_DESC){... on ListActivity{createdAt siteUrl status progress}}
}
`,
{
userId: iddata.data.User.id,
mediaId: item.mediaId
},
function(act){
if(!act){return};
let progressFirst = [act.data.first.status,act.data.first.progress].filter(TRUTHY).join(" ");
progressFirst = (progressFirst ? " (" + progressFirst + ")" : "");
let progressLast = [act.data.last.status,act.data.last.progress].filter(TRUTHY).join(" ");
progressLast = (progressLast ? " (" + progressLast + ")" : "");
if(act.data.first.siteUrl === act.data.last.siteUrl){
let firstLink = create("a",["link","newTab"],"Only activity" + progressFirst + ": ",chance,"color:rgb(var(--color-blue));");
firstLink.href = act.data.first.siteUrl;
create("span",false,(new Date(act.data.first.createdAt*1000)).toISOString().split("T")[0] + " ",chance);
}
else{
let firstLink = create("a",["link","newTab"],"First activity" + progressFirst + ": ",chance,"color:rgb(var(--color-blue));");
firstLink.href = act.data.first.siteUrl;
create("span",false,(new Date(act.data.first.createdAt*1000)).toISOString().split("T")[0] + " \n",chance);
let lastLink = create("a",["link","newTab"],"Last activity" + progressLast + ": ",chance,"color:rgb(var(--color-blue));");
lastLink.href = act.data.last.siteUrl;
create("span",false,(new Date(act.data.last.createdAt*1000)).toISOString().split("T")[0] + " ",chance);
}
}
);
},delay);
delay += 1000;
}
});
};
const query = `query($name: String!, $listType: MediaType){
MediaListCollection(userName: $name, type: $listType){
lists{
entries{
startedAt{year month day}
completedAt{year month day}
mediaId
status
createdAt
updatedAt
repeat
media{
title{romaji english native}
startDate{year month day}
endDate{year month day}
type
}
}
}
}
}`;
generalAPIcall(
query,
{
name: user,
listType: "MANGA"
},
proc
);
generalAPIcall(
query,
{
name: user,
listType: "ANIME"
},
proc
);
},"hohIDlookup" + user.toLowerCase());
}},
{name: "Fix your dating mess [Dangerous edition]",setup: function(){
if(!useScripts.accessToken){
miscResults.innerText = loginMessage;
return;
};
if(user.toLowerCase() !== whoAmI.toLowerCase()){
miscResults.innerText = "This is the profile of\"" + user + "\", but currently signed in as \"" + whoAmI + "\". Are you sure this is right?";
return;
};
let warning = create("b",false,"Clicking on red buttons means changes to your data!",miscResults);
let description = create("p",false,"When run, this will do the following:",miscResults);
create("p",false,"- Completed entries with 1 episode/chapter, no rewatches, no start date, but a completion date will have the start date set equal to the completion date",miscResults);
create("p",false,"- A list of all the changes will be printed.",miscResults);
create("p",false,"- This will run slowly, and can be stopped at any time.",miscResults);
let dryRun = create("button",["button","hohButton"],"Dry run",miscResults);
let dryRunDesc = create("span",false,"(no changes made)",miscResults);
create("hr",false,false,miscResults);
let fullRun = create("button",["button","hohButton","danger"],"RUN",miscResults);
let stopRun = create("button",["button","hohButton"],"Abort!",miscResults);
create("hr",false,false,miscResults);
let changeLog = create("div",false,false,miscResults);
let allowRunner = true;
let allowRun = true;
let isDryRun = true;
let list = [];
let firstTime = true;
let runner = function(){
if(!allowRunner){
return;
}
allowRunner = false;
fullRun.disabled = true;
dryRun.disabled = true;
generalAPIcall("query($name:String){User(name:$name){id}}",{name: user},function(iddata){
let proc = function(data){
list = list.concat((returnList(data,true) || []).filter(
item => item.status === "COMPLETED" && (item.media.episodes || item.media.chapters) === 1 && (!item.startedAt.year) && item.completedAt.year && !item.repeat
));
if(firstTime){
firstTime = false;
return;
};
if(isDryRun){
create("p",false,"DRY RUN",changeLog);
};
if(!list.length){
changeLog.innerText = "No such entries found";
return;
};
create("p",false,"Found " + list.length + " entries.",changeLog);
let changer = function(index){
if(!allowRun){
return;
};
create("p",false,list[index].media.title.romaji + " start date set to " + list[index].completedAt.year + "-" + list[index].completedAt.month + "-" + list[index].completedAt.day,changeLog);
if(!isDryRun){
authAPIcall(
`mutation($date: FuzzyDateInput,$mediaId: Int){
SaveMediaListEntry(startedAt: $date,mediaId: $mediaId){
id
}
}`,
{mediaId: list[index].mediaId,date: list[index].completedAt},
data => {}
);
};
index++;
if(index < list.length){
setTimeout(function(){changer(index)},1000);
};
};changer(0);
};
const query = `query($name: String!, $listType: MediaType){
MediaListCollection(userName: $name, type: $listType){
lists{
entries{
startedAt{year month day}
completedAt{year month day}
mediaId
status
repeat
media{
title{romaji english native}
chapters
episodes
}
}
}
}
}`;
generalAPIcall(
query,
{
name: user,
listType: "MANGA"
},
proc
);
generalAPIcall(
query,
{
name: user,
listType: "ANIME"
},
proc
);
},"hohIDlookup" + user.toLowerCase());
};
stopRun.onclick = function(){
allowRun = false;
stopRun.disable = true;
alert("Stopped!");
};
fullRun.onclick = function(){
isDryRun = false;
runner();
};
dryRun.onclick = function(){
runner();
};
},code: function(){
miscResults.innerText = "Read the description first!";
}},
{name: "Reviews",code: function(){
miscResults.innerText = "";
let dataHeader = create("div",false,false,miscResults);
create("span",false,"There are ",dataHeader);
let data_amount = create("span",false,"[loading...]",dataHeader);
create("span",false," reviews on Anilist, with ",dataHeader);
let data_ratingAmount = create("span",false,"[loading...]",dataHeader);
create("span",false," ratings (",dataHeader);
let data_ratingPositive = create("span",false,"[loading...]",dataHeader);
create("span",false,"% positive)",dataHeader);
generalAPIcall(
`query ($page: Int) {
Page (page: $page) {
pageInfo {
total
perPage
currentPage
lastPage
hasNextPage
}
reviews {
id
}
}
}`,
{page: 1},
function(data){
data_amount.innerText = data.data.Page.pageInfo.total;
let list = [];
for(var i=1;i<=data.data.Page.pageInfo.lastPage;i++){
generalAPIcall(
`query ($page: Int){
Page (page: $page){
pageInfo{
total
perPage
currentPage
lastPage
hasNextPage
}
reviews{
id
rating
ratingAmount
user{
name
id
}
media{
id
title{romaji}
}
}
}
}`,
{page: i},
function(reviewData){
list = list.concat(reviewData.data.Page.reviews);
if(list.length !== reviewData.data.Page.pageInfo.total){
return;
};
list.sort((b,a) => wilson(a.rating,a.ratingAmount).left - wilson(b.rating,b.ratingAmount).left);
create("h3",false,"100 best reviews on Anilist",miscResults);
let datalist1 = create("div",false,false,miscResults);
list.slice(0,100).forEach((review,index) => {
let dataCel = create("p",false,false,datalist1);
create("span",false,(index + 1) + ". ",dataCel,"width:35px;display:inline-block;");
create("span","hohMonospace",wilson(review.rating,review.ratingAmount).left.toPrecision(3) + " ",dataCel);
let userName = "[error]";
if(review.user){
if(review.user.name){
userName = review.user.name;
};
};
create("a",["link","newTab"],userName + "'s review of " + review.media.title.romaji,dataCel)
.href = "/review/" + review.id;
});
list.sort((a,b)=>wilson(a.rating,a.ratingAmount).right - wilson(b.rating,b.ratingAmount).right);
create("h3",false,"100 worst reviews on Anilist",miscResults);
let datalist2 = create("div",false,false,miscResults);
list.slice(0,100).forEach((review,index) => {
let dataCel = create("p",false,false,datalist2);
create("span",false,(index + 1) + ". ",dataCel,"width:35px;display:inline-block;");
create("span","hohMonospace",wilson(review.rating,review.ratingAmount).right.toPrecision(3) + " ",dataCel);
let userName = "[error]";
if(review.user){
if(review.user.name){
userName = review.user.name;
};
};
create("a",["link","newTab"],userName + "'s review of " + review.media.title.romaji,dataCel)
.href = "/review/" + review.id;
});
let reviewers = new Map();
let ratings = 0;
let positiveRatings = 0;
list.forEach(rev => {
ratings += rev.ratingAmount;
positiveRatings += rev.rating;
if(rev.user){
if(rev.user.id){
if(!reviewers.has(rev.user.id)){
reviewers.set(rev.user.id,{
id: rev.user.id,
name: rev.user.name,
rating: 0,
ratingAmount: 0,
amount: 0
});
}
let person = reviewers.get(rev.user.id);
person.rating += rev.rating;
person.ratingAmount += rev.ratingAmount;
person.amount++;
};
};
});
data_ratingAmount.innerText = ratings;
data_ratingPositive.innerText = Math.round(100 * positiveRatings/ratings);
reviewers = [...reviewers].map(
pair => pair[1]
).sort(
(b,a) => wilson(a.rating,a.ratingAmount).left - wilson(b.rating,b.ratingAmount).left
);
create("h3",false,"10 best reviewers on Anilist",miscResults);
let datalist3 = create("div",false,false,miscResults);
reviewers.slice(0,10).forEach((rev,index) => {
let dataCel = create("p",false,false,datalist3);
create("span",false,(index + 1) + ". ",dataCel,"width:35px;display:inline-block;");
create("span","hohMonospace",wilson(rev.rating,rev.ratingAmount).left.toPrecision(3) + " ",dataCel);
let userName = rev.name || "[private or deleted]";
let link = create("a",["link","newTab"],userName,dataCel,"color:rgb(var(--color-blue));");
link.href = "/user/" + rev.name || "removed";
});
reviewers.sort((a,b) => wilson(a.rating,a.ratingAmount).right - wilson(b.rating,b.ratingAmount).right);
create("h3",false,"10 worst reviewers on Anilist",miscResults);
let datalist4 = create("div",false,false,miscResults);
reviewers.slice(0,10).forEach((rev,index) => {
let dataCel = create("p",false,false,datalist4);
create("span",false,(index + 1) + ". ",dataCel,"width:35px;display:inline-block;");
create("span","hohMonospace",wilson(rev.rating,rev.ratingAmount).right.toPrecision(3) + " ",dataCel);
let userName = rev.name || "[private or deleted]";
let link = create("a",["link","newTab"],userName,dataCel,"color:rgb(var(--color-blue));");
link.href = "/user/" + rev.name || "removed";
});
reviewers.sort(function(b,a){
if(a.amount === b.amount){//rating as tie-breaker
return a.rating/a.ratingAmount - b.rating/b.ratingAmount;
}
else{
return a.amount - b.amount
}
});
create("h3",false,"25 most prolific reviewers on Anilist",miscResults);
let datalist5 = create("div",false,false,miscResults);
let profilicSum = 0;
reviewers.slice(0,25).forEach((rev,index) => {
profilicSum += rev.amount;
let dataCel = create("p",false,false,datalist5);
create("span",false,(index + 1) + ". ",dataCel,"width:35px;display:inline-block;");
create("span","hohMonospace",rev.amount + " ",dataCel);
let userName = rev.name || "[private or deleted]";
let link = create("a",["link","newTab"],userName,dataCel,"color:rgb(var(--color-blue));");
link.href = "/user/" + rev.name || "removed";
create("span",false," average rating: " + (100*rev.rating/rev.ratingAmount).toPrecision(2) + "%",dataCel);
});
create("p",false,"That's " + Math.round(100*profilicSum/list.length) + "% of all reviews on Anilist",miscResults);
let average = (data.data.Page.pageInfo.total/reviewers.length).toPrecision(2);
let median = Stats.median(reviewers,e => e.amount);
let mode = Stats.mode(reviewers,e => e.amount);
create("p",false,`${reviewers.length} users have contributed reviews (${average} reviews each on average, median ${median}, mode ${mode})`,miscResults);
}
)
};
}
);
}},
{name: "How many people have blocked you",code: function(){
if(!useScripts.accessToken){
miscResults.innerText = loginMessage;
return;
}
authAPIcall("query{Page{pageInfo{total}users{id}}}",{},function(data){
generalAPIcall("query{Page{pageInfo{total}users{id}}}",{},function(data2){
miscResults.innerText = "This only applies to you, regardless of what stats page you ran this query from.";
if(data.data.Page.pageInfo.total === data2.data.Page.pageInfo.total){
create("p",false,"No users have blocked you",miscResults)
}
else if((data2.data.Page.pageInfo.total - data.data.Page.pageInfo.total) < 0){
create("p",false,"Error: The elevated privileges of moderators makes this query fail",miscResults)
}
else{
create("p",false,(data2.data.Page.pageInfo.total - data.data.Page.pageInfo.total) + " users have blocked you",miscResults)
}
});
})
}},
{name: "Find people you have blocked/are blocked by",code: function(){
if(!useScripts.accessToken){
miscResults.innerText = loginMessage;
return;
}
miscResults.innerText = `This only applies to you, regardless of what stats page you ran this query from. Furthermore, it probably won't find everyone.
Use the other query if you just want the number.`;
let flag = true;
let stopButton = create("button",["button","hohButton"],"Stop",miscResults,"display:block");
let progress = create("p",false,false,miscResults);
stopButton.onclick = function(){
flag = false;
};
let blocks = new Set();
progress.innerText = "1 try..."
let caller = function(page,page2){
generalAPIcall(`
query($page: Int){
Page(page: $page){
activities(sort: ID_DESC,type: TEXT){
... on TextActivity{
id
user{name}
}
}
}
}`,
{page: page},function(data){
progress.innerText = (page + 1) + " tries...";
authAPIcall(`
query($page: Int){
Page(page: $page){
activities(sort: ID_DESC,type: TEXT){
... on TextActivity{
id
}
}
}
}`, {page: page2},function(data2){
let offset = 0;
while(data2.data.Page.activities[offset].id > data.data.Page.activities[0].id){
offset++;
};
while(data2.data.Page.activities[0].id < data.data.Page.activities[-offset].id){
offset--;
};
for(var k=Math.max(-offset,0);k conf(...ig));
},code: function(){
let type = document.getElementById("typeSelect").value;
let restrict = document.getElementById("restrictToList").checked;
let require = new Set();
let config = [
{name: "startEnd",description: "End date before start date",code: function(media){
if(!media.startDate.year || !media.endDate.year){
return false
}
if(media.startDate.year > media.endDate.year){
return true
}
else if(media.startDate.year < media.endDate.year){
return false
}
if(!media.startDate.month || !media.endDate.month){
return false
}
if(media.startDate.month > media.endDate.month){
return true
}
else if(media.startDate.month < media.endDate.month){
return false
}
if(!media.startDate.day || !media.endDate.day){
return false
}
if(media.startDate.day > media.endDate.day){
return true
}
return false;
},require: ["startDate{year month day}","endDate{year month day}"]},
{name: "earlyDates",description: "Dates before 1900",code: function(media){
return (media.startDate.year && media.startDate.year < 1900) || (media.endDate.year && media.endDate.year < 1900)
},require: ["startDate{year month day}","endDate{year month day}"]},
{name: "missingDates",description: "Missing dates",code: function(media){
if(media.status === "FINISHED"){
return (!media.startDate.year) || (!media.endDate.year);
}
else if(media.status === "RELEASING"){
return !media.startDate.year;
}
return false;
},require: ["startDate{year month day}","endDate{year month day}","status"]}
,
{name: "incompleteDates",description: "Incomplete dates",code: function(media){
if(media.status === "FINISHED"){
return (!media.startDate.year) || (!media.startDate.month) || (!media.startDate.day) || (!media.endDate.year) || (!media.endDate.month) || (!media.endDate.day);
}
else if(media.status === "RELEASING"){
return (!media.startDate.year) || (!media.startDate.month) || (!media.startDate.day);
}
return false;
},require: ["startDate{year month day}","endDate{year month day}","status"]},
{name: "noTags",description: "No tags",code: function(media){
return media.tags.length === 0;
},require: ["tags{rank name}"]},
{name: "noGenres",description: "No genres",code: function(media){
return media.genres.length === 0;
},require: ["genres"]},
{name: "lowTag",description: "Has tag below 20%",code: function(media){
return media.tags.some(tag => tag.rank < 20);
},require: ["tags{rank name}"]},
{name: "demographics",description: "Multiple demographic tags",code: function(media){
return media.tags.filter(tag => ["Shounen","Shoujo","Josei","Seinen","Kids"].includes(tag.name)).length > 1;
},require: ["tags{rank name}"]},
{name: "badGenre",description: "Has invalid genre",code: function(media){
return media.genres.some(genre => !["Action","Adventure","Comedy","Drama","Ecchi","Fantasy","Hentai","Horror","Mahou Shoujo","Mecha","Music","Mystery","Psychological","Romance","Sci-Fi","Slice of Life","Sports","Supernatural","Thriller"].includes(genre));
},require: ["genres"]},
{name: "noBanner",description: "Missing banner",code: function(media){
return !media.bannerImage
},require: ["bannerImage"]},
{name: "oneshot",description: "Oneshot without one chapter",code: function(media){
return media.format === "ONE_SHOT" && media.chapters !== 1;
},require: ["chapters"]},
{name: "idMal",description: "Missing MAL ID",code: function(media){
return !media.idMal
},require: ["idMal"]},
{name: "nativeTitle",description: "Missing native title",code: function(media){
return !media.title.native
}},
{name: "englishTitle",description: "Missing english title",code: function(media){
return !media.title.english
}},
{name: "noDuration",description: "No duration",code: function(media){
return media.type === "ANIME" && media.status !== "NOT_YET_RELEASED" && !media.duration;
},require: ["type","duration","status"]},
{name: "noLength",description: "No chapter or episode count",code: function(media){
if(media.status !== "FINISHED"){
return false;
}
if(media.type === "ANIME"){
return !media.episodes;
}
else{
return !media.chapters;
}
},require: ["type","chapters","episodes","status"]},
{name: "noStudios",description: "No studios",code: function(media){
return media.type === "ANIME" && !media.studios.nodes.length;
},require: ["type","studios{nodes{id}}"]},
{name: "unusualLength",description: "Unusual Length",code: function(media){
if(media.type === "ANIME"){
return (media.episodes && media.episodes > 1000) || (media.duration && media.duration > 180);
}
else{
return (media.cahpters && media.chapters > 2000) || (media.volumes && media.volumes > 150);
}
},require: ["type","chapters","volumes","duration","episodes"]},
{name: "noSource",description: "No source",code: function(media){
return !media.source;
},require: ["source(version: 2)"]},
{name: "otherSource",description: "Source = other",code: function(media){
return (media.source && media.source === "OTHER");
},require: ["source(version: 2)"]},
{name: "redundantSynonym",description: "Synonym equal to title",code: function(media){
return media.synonyms.some(
word => word === media.title.romaji
)
|| (media.title.native && media.synonyms.some(
word => word === media.title.native
))
|| (media.title.english && media.synonyms.some(
word => word === media.title.english
));
},require: ["synonyms"]},
{name: "hashtag",description: "Has Twitter hashtag",code: function(media){
return !!media.hashtag;
},require: ["hashtag"]},
{name: "nonAdultHentai",description: "Hentai with isAdult = false",code: function(media){
return (media.genres.includes("Hentai") && !media.isAdult);
},require: ["genres","isAdult"]},
{name: "extraLarge",description: "No extraLarge cover image",code: function(media){
return media.coverImage.large && media.coverImage.large === media.coverImage.extraLarge;
},require: ["coverImage{large extraLarge}"]},
{name: "tempTitle",description: "Temporary title",code: function(media){
return media.title.romaji === "(Title to be Announced)"
|| (media.title.native && media.title.native === "(Title to be Announced)")
|| media.title.romaji.includes("(Provisional Title)")
|| (media.title.native && media.title.native.includes("(仮)"));
}},
{name: "badRomaji",description: "Romaji inconsistencies",code: function(media){
let illegals = ["~","「","」","ō","ū","。","!","?","Toukyou","Oosaka"];
if(illegals.some(char => media.title.romaji.match(char))){
return true;
}
return media.title.native && (
(media.title.native.includes("っち") && media.title.romaji.includes("tchi"))
|| (media.title.native.includes("っちゃ") && media.title.romaji.includes("tcha"))
|| (media.title.native.includes("っちょ") && media.title.romaji.includes("tcho"))
|| (media.title.native.includes("☆") && !media.title.romaji.includes("☆"))
|| (media.title.native.includes("♪") && !media.title.romaji.includes("♪"))
);
}},
{name: "weirdSpace",description: "Weird spacing in title",code: function(media){
return (
(media.title.native || "").trim().replace(" "," ") !== (media.title.native || "")
|| (media.title.romaji || "").trim().replace(" "," ") !== (media.title.romaji || "")
|| (media.title.english || "").trim().replace(" "," ") !== (media.title.english || "")
)
},require: ["duration"]},
{name: "tvShort",description: "TV/TV Short mixup",code: function(media){
if(media.duration){
return (media.format === "TV" && media.duration < 15) || (media.format === "TV_SHORT" && media.duration >= 15)
}
return false;
},require: ["duration"]},
{name: "newSource",description: "Adaptation older than source",code: function(media){
return media.sourcing.edges.some(function(edge){
if(edge.relationType === "SOURCE"){
return fuzzyDateCompare(edge.node.startDate,media.startDate) === 0;
}
return false;
})
},require: ["startDate{year month day}","sourcing:relations{edges{relationType(version: 2) node{format startDate{year month day}}}}"]},
{name: "moreSource",description: "More than one source",code: function(media){
return media.sourcing.edges.filter(edge => edge.relationType === "SOURCE").length > 1;
},require: ["startDate{year month day}","sourcing:relations{edges{relationType(version: 2) node{format startDate{year month day}}}}"]},
{name: "formatSource",description: "Source field not equal to source media format",code: function(media){
let source = media.sourcing.edges.filter(edge => edge.relationType === "SOURCE");
return source.length && media.source
&& (
(source[0].node.format !== media.source)
&& !(source[0].node.format === "NOVEL" && media.source === "LIGHT_NOVEL")
);
},require: ["source(version: 2)","sourcing:relations{edges{relationType(version: 2) node{format startDate{year month day}}}}"]},
{name: "releasingZero",description: "Releasing manga with non-zero chapter of volume count",code: function(media){
return media.format === "MANGA" && media.status === "RELEASING" && (media.chapters || media.volumes)
},require: ["status","chapters","volumes"]},
{name: "duplicatedStudio",description: "Duplicated studio",code: function(media){
return (new Set(media.studios.nodes)).size !== media.studios.nodes.length;
},require: ["studios{nodes{id}}"]}
];
config.forEach(function(setting){
setting.active = document.getElementById(setting.name).checked;
if(setting.active && setting.require){
setting.require.forEach(field => require.add(field));
};
});
let query = `
query($type: MediaType,$page: Int){
Page(page: $page){
pageInfo{
currentPage
lastPage
}
media(type: $type,sort: POPULARITY_DESC){
id
title{romaji native english}
format
${[...require].join(" ")}
}
}
}`;
if(restrict){
query = `
query($type: MediaType,$page: Int){
Page(page: $page){
pageInfo{
currentPage
lastPage
}
mediaList(type: $type,sort: MEDIA_ID,userName: "${user}"){
media{
id
title{romaji native english}
format
${[...require].join(" ")}
}
}
}
}`;
}
miscResults.innerText = "";
let flag = true;
let stopButton = create("button",["button","hohButton"],"Stop",miscResults);
let progress = create("p",false,false,miscResults);
stopButton.onclick = function(){
flag = false;
};
let caller = function(page){
generalAPIcall(query,{type: type,page: page},function(data){
data = data.data.Page;
if(data.mediaList){
data.media = data.mediaList.map(item => item.media);
};
data.media.forEach(media => {
progress.innerText = "Page " + page + " of " + data.pageInfo.lastPage;
let matches = config.filter(
setting => setting.active && setting.code(media)
).map(setting => setting.description);
if(matches.length){
let row = create("p",false,false,miscResults);
create("a",["link","newTab"],"[" + media.format + "] " + media.title.romaji,row,"width:440px;display:inline-block;")
.href = "/" + type.toLowerCase() + "/" + media.id;
create("span",false,matches.join(", "),row);
};
});
if(flag && data.pageInfo.currentPage < data.pageInfo.lastPage && document.getElementById("queryOptions")){
setTimeout(function(){caller(page + 1)},1000)
}
});
};caller(1);
}},
{name: "YiffDog officer",setup: function(){
create("p",false,"Welcome to YiffDog. He's a relative of BroomCat, focused on the social aspect of the site. This police dog is just out of beta, so he doesn't have many options yet.",miscOptions);
create("p",false,"(If you're reading this, it's probably not even usable yet).",miscOptions);
create("p","danger","Do not needlessly interact with what's flagged here, limit that to honest mistakes. Silently report, or send mod messages when appropriate.",miscOptions);
createCheckbox(miscOptions,"activities",true);
create("span",false,"Activities",miscOptions);
createCheckbox(miscOptions,"messages",true);
create("span",false,"Messages",miscOptions);
createCheckbox(miscOptions,"forum",true);
create("span",false,"Forum",miscOptions);
createCheckbox(miscOptions,"reviews",true);
create("span",false,"Reviews",miscOptions);
create("h3",false,"Config",miscOptions);
let conf = function(description,id,defaultValue,titleText){
let option = create("p",false,false,miscOptions);
let check = createCheckbox(option,id);
let descriptionText = create("span",false,description + " ",option);
if(defaultValue){
check.checked = defaultValue;
}
if(titleText){
descriptionText.title = titleText;
}
};
[
["Link-only","linkOnly",true],
["Bad words","badWords",true,"I'm not claiming all or any of the words in the internal list are inheritely bad, they are just a useful heuristic"],
["Piracy links","piracy",true],
["High activity","highActivity",true]
].forEach(ig => conf(...ig));
},code: function(){
let checkActivities = document.getElementById("activities").checked;
let checkMessages = document.getElementById("messages").checked;
let checkForum = document.getElementById("forum").checked;
let checkReviews = document.getElementById("reviews").checked;
if(checkActivities || checkMessages || checkForum || checkReviews){
let activitiesQuery = `activities1:Page(page:1){
activities(type:TEXT,sort:ID_DESC){
siteUrl
text(asHtml: true)
user{name}
}
}
activities2:Page(page:2){
activities(type:TEXT,sort:ID_DESC){
siteUrl
text(asHtml: true)
user{name}
}
}`;
let messagesQuery = `messages:Page(page:1){
activities(type:MESSAGE,sort:ID_DESC){
siteUrl
message
messenger{name}
}
}`;
generalAPIcall(
`query{
${(checkActivities ? activitiesQuery : "")}
${(checkMessages ? messagesQuery : "")}
}`,
{},
function(data){
if(document.getElementById("linkOnly").checked){
if(checkActivities){
data.data.activities1.activities.concat(data.data.activities2.activities).forEach(activity => {
if(activity.text.match(/^<\/p>$/)){
let row = create("p",false,false,miscResults);
create("a",["link","newTab"],activity.siteUrl,row,"width:440px;display:inline-block;")
.href = activity.siteUrl;
create("span",false,"Link-only post. Spam?",row);
create("p",false,false,row).innerHTML = activity.text;
}
})
}
}
}
)
}
}},
{name: "Find a status",setup: function(){
let input = create("input","#searchInput",false,miscOptions);
input.placeholder = "text or regex to match";
},code: function(){
generalAPIcall("query($name:String){User(name:$name){id}}",{name: user},function(data){
let userId = data.data.User.id;
miscResults.innerText = "";
let posts = 0;
let progress = create("p",false,false,miscResults);
let results = create("p",false,false,miscResults);
let searchQuery = document.getElementById("searchInput").value;
const query = `
query($userId: Int,$page: Int){
Page(page: $page){
pageInfo{
currentPage
total
lastPage
}
activities (userId: $userId, sort: ID_DESC, type: TEXT){
... on TextActivity{
siteUrl
text(asHtml: true)
}
}
}
}`;
let addNewUserData = function(data){
if(data.data.Page.pageInfo.currentPage === 1){
for(var i=2;i<=data.data.Page.pageInfo.lastPage;i++){
generalAPIcall(query,{userId: userId,page: i},addNewUserData);
};
};
posts += data.data.Page.activities.length;
progress.innerText = "Searching status post " + posts + "/" + data.data.Page.pageInfo.total;
data.data.Page.activities.forEach(function(act){
if(act.text.match(new RegExp(searchQuery,"i"))){
let newDate = create("p",false,false,results,"font-family:monospace;margin-right:10px;");
let newPage = create("a","newTab",act.siteUrl,newDate,"color:rgb(var(--color-blue));");
newPage.href = act.siteUrl;
newDate.innerHTML += act.text;
create("hr",false,false,results);
};
});
};
generalAPIcall(query,{userId: userId,page: 1},addNewUserData);
},"hohIDlookup" + user.toLowerCase());
}},
{name: "Most liked status posts",code: function(){
generalAPIcall("query($name:String){User(name:$name){id}}",{name: user},function(data){
let userId = data.data.User.id;
let list = [];
miscResults.innerText = "";
let progress = create("p",false,false,miscResults);
let results = create("p",false,false,miscResults);
const query = `
query($userId: Int,$page: Int){
Page(page: $page){
pageInfo{
currentPage
total
lastPage
}
activities (userId: $userId, sort: ID_DESC, type: TEXT){
... on TextActivity{
siteUrl
likes{id}
}
}
}
}`;
let addNewUserData = function(data){
list = list.concat(data.data.Page.activities);
if(data.data.Page.pageInfo.currentPage === 1){
for(var i=2;i<=data.data.Page.pageInfo.lastPage;i++){
generalAPIcall(query,{userId: userId,page: i},addNewUserData);
};
};
list.sort(function(b,a){return a.likes.length - b.likes.length});
progress.innerText = "Searching status post " + list.length + "/" + data.data.Page.pageInfo.total;
while(results.childElementCount){
results.lastChild.remove();
}
for(var i=0;i<20;i++){
let newDate = create("p",false,list[i].likes.length + " likes ",results,"font-family:monospace;margin-right:10px;");
let newPage = create("a","newTab",list[i].siteUrl,newDate,"color:rgb(var(--color-blue));");
newPage.href = list[i].siteUrl;
};
};
generalAPIcall(query,{userId: userId,page: 1},addNewUserData);
},"hohIDlookup" + user.toLowerCase());
}}
];
let miscInputSelect = create("select",false,false,miscInput);
let miscInputButton = create("button",["button","hohButton"],"Run",miscInput);
availableQueries.forEach(function(que){
let option = create("option",false,que.name,miscInputSelect);
option.value = que.name;
});
miscInputSelect.oninput = function(){
miscOptions.innerText = "";
let relevant = availableQueries.find(que => que.name === miscInputSelect.value);
if(relevant.setup){
miscResults.innerText = "";
relevant.setup();
};
};
miscInputButton.onclick = function(){
miscResults.innerText = "Loading...";
availableQueries.find(que => que.name === miscInputSelect.value).code();
}
//gather some stats
let customTagsCollection = function(list,title,fields){
let customTags = new Map();
let regularTags = new Map();
let customLists = new Map();
(
JSON.parse(localStorage.getItem("regularTags" + title)) || []
).forEach(tag => {
regularTags.set(tag,{
name : tag,
list : []
});
});
customLists.set("Not on custom list",{name: "Not on custom list",list: []});
customLists.set("All media",{name: "All media",list: []});
list.forEach(media => {
let item = {};
fields.forEach(field => {
item[field.key] = field.method(media);
});
let evalBackslash = function(text){
let output = "";
let special = false;
Array.from(text).forEach(char => {
if(char === "\\"){
if(special){
output += "\\"
}
special = !special;
}
else{
output += char;
}
});
return output;
}
if(media.notes){
(
media.notes.match(/(#(\\\s|\S)+)/g) || []
).filter(
tagMatch => !tagMatch.match(/^#039/)
).map(
tagMatch => evalBackslash(tagMatch)
).forEach(tagMatch => {
if(!customTags.has(tagMatch)){
customTags.set(tagMatch,{name: tagMatch,list: []})
}
customTags.get(tagMatch).list.push(item)
});
(//candidates for multi word tags, which we try to detect even if they are not allowed
media.notes.match(/(#\S+\ [^#]\S+)/g) || []
).filter(
tagMatch => !tagMatch.match(/^#039/)
).map(
tagMatch => evalBackslash(tagMatch)
).forEach(tagMatch => {
if(!customTags.has(tagMatch)){
customTags.set(tagMatch,{name: tagMatch,list: []})
}
customTags.get(tagMatch).list.push(item)
})
};
if(customTags.has("##STRICT")){
customTags.delete("##STRICT")
}
else{
for(let [key,value] of customTags){//filter our multi word candidates
if(key.includes(" ")){
if(value.list.length === 1){//if it's just one of them, the prefix tag takes priority
customTags.delete(key)
}
else{
let prefix = key.split(" ")[0];
if(customTags.has(prefix)){
if(customTags.get(prefix).list.length === value.list.length){
customTags.delete(prefix)
}
else{
customTags.delete(key)
}
}
}
}
}
for(let [key,value] of customTags){//fix the basic casing error, like #shoujo vs #Shoujo. Will only merge if one is of length 1
if(key[1] === key[1].toUpperCase()){
let lowerCaseKey = "#" + key[1].toLowerCase() + key.slice(2);
let lowerCaseValue = customTags.get(lowerCaseKey);
if(lowerCaseValue){
if(value.list.length === 1){
lowerCaseValue.list = lowerCaseValue.list.concat(value.list);
customTags.delete(key);
}
else if(lowerCaseValue.list.length === 1){
value.list = value.list.concat(lowerCaseValue.list);
customTags.delete(lowerCaseKey);
};
}
}
}
}
media.media.tags.forEach(mediaTag => {
if(regularTags.has(mediaTag.name)){
regularTags.get(mediaTag.name).list.push(item)
}
});
if(media.isCustomList){
media.listLocations.forEach(location => {
if(!customLists.has(location)){
customLists.set(location,{name: location,list: []});
}
customLists.get(location).list.push(item);
})
}
else if(useScripts.negativeCustomList){
customLists.get("Not on custom list").list.push(item);
};
if(useScripts.globalCustomList){
customLists.get("All media").list.push(item);
}
});
if(!customLists.get("Not on custom list").list.length){
customLists.delete("Not on custom list")
};
if(!customLists.get("All media").list.length){
customLists.delete("All media")
};
return [...customTags, ...regularTags, ...customLists].map(
pair => pair[1]
).map(tag => {
let amountCount = 0;
let average = 0;
tag.list.forEach(item => {
if(item.score !== 0){
amountCount++;
average += item.score;
};
fields.forEach(field => {
if(field.sumable){
tag[field.key] = field.sumable(tag[field.key],item[field.key]);
}
});
});
tag.average = average/amountCount || 0;
tag.list.sort((b,a) => a.score - b.score);
return tag;
}).sort(
(b,a) => a.list.length - b.list.length || b.name.localeCompare(a.name)
);
};
let regularTagsCollection = function(list,fields,extracter){
let tags = new Map();
list.forEach(media => {
let item = {};
fields.forEach(field => {
item[field.key] = field.method(media);
});
extracter(media).forEach(tag => {
if(useScripts.SFWmode && tag.name === "Hentai"){
return;
}
if(!tags.has(tag.name)){
tags.set(tag.name,{name: tag.name,list: []});
}
tags.get(tag.name).list.push(item);
});
});
tags.forEach(tag => {
tag.amountCount = 0;
tag.average = 0;
tag.list.forEach(item => {
if(item.score){
tag.amountCount++;
tag.average += item.score;
};
fields.forEach(field => {
if(field.sumable){
tag[field.key] = field.sumable(tag[field.key],item[field.key]);
}
});
});
tag.average = tag.average/tag.amountCount || 0;
tag.list.sort((b,a) => a.score - b.score);
});
return [...tags].map(
tag => tag[1]
).sort(
(b,a) => (a.average*a.amountCount + ANILIST_WEIGHT)/(a.amountCount + 1) - (b.average*b.amountCount + ANILIST_WEIGHT)/(b.amountCount + 1) || a.list.length - b.list.length
);
};
let drawTable = function(data,formatter,tableLocation,isTag,autoHide){
while(tableLocation.childElementCount){
tableLocation.lastChild.remove();
};
tableLocation.innerText = "";
let hasScores = data.some(elem => elem.average);
let header = create("p",false,formatter.title);
let tableContent = create("div",["table","hohTable"]);
let headerRow = create("div",["header","row"],false,tableContent);
let indexAccumulator = 0;
formatter.headings.forEach(function(heading){
if(!hasScores && heading === "Mean Score"){
return;
};
let columnTitle = create("div",false,heading,headerRow);
if(heading === "Tag" && !isTag && formatter.isMixed){
columnTitle.innerText = "Genre";
}
if(formatter.focus === indexAccumulator){
columnTitle.innerHTML += " " + svgAssets.angleDown;
};
columnTitle.index = +indexAccumulator;
columnTitle.addEventListener("click",function(){
formatter.focus = this.index;
data.sort(formatter.sorting[this.index]);
drawTable(data,formatter,tableLocation,isTag,autoHide);
});
indexAccumulator++;
});
for(var i=0;i a.score - b.score);
}
else if(formatter.focus === -1){//average != score
//nothing, duh
}
else{
data[i].list.sort(formatter.sorting[formatter.focus]);
}
data[i].list.forEach((nil,ind) => {
let secondaryRow = create("div",["row","hohSecondaryRow"]);
formatter.celData.forEach(celData => {
let cel = create("div");
celData(cel,data[i].list,ind,false,isTag);
secondaryRow.appendChild(cel);
});
showList.appendChild(secondaryRow);
});
showList.style.display = "none";
tableContent.insertBefore(showList,row.nextSibling);
};
tableLocation.appendChild(header);
tableLocation.appendChild(tableContent);
if(autoHide){
let tableHider = create("span",["hohMonospace","hohTableHider"],"[-]",header);
let regularTagsSetting = create("p",false,false,tableLocation);
let regularTagsSettingLabel = create("span",false," Regular tags included (applied on reload): ",regularTagsSetting);
let regularTagsSettingContent = create("span",false,false,regularTagsSetting);
let regularTagsSettingNew = create("input",false,false,regularTagsSetting);
let regularTagsSettingAdd = create("button",["hohButton","button"],"+",regularTagsSetting);
let regularTags = JSON.parse(localStorage.getItem("regularTags" + formatter.title)) || [];
for(var i=0;i media.repeat
},{
key : "status",
sumable : function(acc,val){
if(!acc){
acc = {};
Object.keys(distributionColours).forEach(function(key){
acc[key] = 0;
})
}
acc[val]++;
return acc;
},
method : media => media.status
},{
key : "type",
method : function(media){
if(!media.progressVolumes && !(media.progressVolumes === 0)){
return "ANIME";
}
else{
return "MANGA";
}
}
},{
key : "mediaId",
method : media => media.mediaId
},{
key : "score",
method : media => media.scoreRaw
},{
key : "duration",
sumable : ACCUMULATE,
method : media => media.watchedDuration || 0
},{
key : "chaptersRead",
sumable : ACCUMULATE,
method : media => media.chaptersRead || 0
}
];
let mixedFormatter = {
title : "",
display : true,
isMixed : true,
headings : ["Tag","Count","Mean Score","Time Watched","Chapters Read"],
focus : -1,
celData : [
function(cel,data,index,isPrimary,isTag){
if(isPrimary){
let nameCellCount = create("div","count",(index+1),cel);
let nameCellTag = create("a",false,data[index].name,cel,"cursor:pointer;");
if(isTag){
nameCellTag.href = "/search/anime?includedTags=" + data[index].name + "&onList=true";
}
else{
nameCellTag.href = "/search/anime?includedGenres=" + data[index].name + "&onList=true";
}
if(tagDescriptions[data[index].name]){
nameCellTag.title = tagDescriptions[data[index].name];
}
let nameCellStatus = create("span","hohSumableStatusContainer",false,cel);
Object.keys(distributionColours).sort().forEach(function(status){
if(data[index].status[status]){
let statusSumDot = create("div","hohSumableStatus",data[index].status[status],nameCellStatus);
statusSumDot.style.background = distributionColours[status];
statusSumDot.title = data[index].status[status] + " " + capitalize(status.toLowerCase());
if(data[index].status[status] > 99){
statusSumDot.style.fontSize = "8px";
}
if(data[index].status[status] > 999){
statusSumDot.style.fontSize = "6px";
}
statusSumDot.onclick = function(e){
e.stopPropagation();
Array.from(cel.parentNode.nextSibling.children).forEach(function(child){
if(child.children[1].children[0].title === status.toLowerCase()){
child.style.display = "grid";
}
else{
child.style.display = "none";
};
});
}
}
});
}
else{
let nameCellTag = create("a",["title","hohNameCel"],data[index].name,cel);
if(data[index].type === "ANIME"){
nameCellTag.href = "/anime/" + data[index].mediaId + "/";
nameCellTag.style.color = "rgb(var(--color-blue))";
}
else{
nameCellTag.href = "/manga/" + data[index].mediaId + "/";
nameCellTag.style.color = "rgb(var(--color-green))";
};
}
},
function(cel,data,index,isPrimary){
if(isPrimary){
cel.innerText = data[index].list.length;
}
else{
let statusDot = create("div","hohStatusDot",false,cel);
statusDot.style.backgroundColor = distributionColours[data[index].status];
statusDot.title = data[index].status.toLowerCase();
if(data[index].status === "COMPLETED"){
statusDot.style.backgroundColor = "transparent";//default case
}
if(data[index].repeat === 1){
cel.innerHTML = svgAssets.repeat;
}
else if(data[index].repeat > 1){
cel.innerHTML = svgAssets.repeat + data[index].repeat;
}
}
},
function(cel,data,index,isPrimary){
if(isPrimary){
cel.innerText = (data[index].average).roundPlaces(1) || "-"
}
else{
cel.innerText = (data[index].score).roundPlaces(1) || "-"
}
},
function(cel,data,index,isPrimary){
if(!isPrimary && data[index].type === "MANGA"){
cel.innerText = "-";
}
else if(data[index].duration === 0){
cel.innerText = "-";
}
else if(data[index].duration < 60){
cel.innerText = Math.round(data[index].duration) + "min";
}
else{
cel.innerText = Math.round(data[index].duration/60) + "h";
};
},
function(cel,data,index,isPrimary){
if(isPrimary || data[index].type === "MANGA"){
cel.innerText = data[index].chaptersRead;
}
else{
cel.innerText = "-";
}
}
],
sorting : [
(a,b) => ALPHABETICAL(a => a.name),
(b,a) => a.list.length - b.list.length,
(b,a) => a.average - b.average,
(b,a) => a.duration - b.duration,
(b,a) => a.chaptersRead - b.chaptersRead
]
};
let collectedMedia = semaPhoreAnime.concat(semaPhoreManga);
let listOfTags = regularTagsCollection(collectedMedia,mixedFields,media => media.media.tags);
if(listOfTags.length > 50){//restrict to 3 or more only if the user has many tags
listOfTags = listOfTags.filter(a => a.list.length >= 3);
}
if(!document.URL.match(/\/stats/)){
return;
};
let drawer = function(){
drawTable(listOfTags,mixedFormatter,regularTagsTable,true);
//recycle most of the formatter for genres
drawTable(
regularTagsCollection(
collectedMedia,
mixedFields,
media => media.media.genres.map(a => ({name: a}))
),
mixedFormatter,
regularGenresTable
);
hohGenresTrigger.removeEventListener("mouseover",drawer);
}
hohGenresTrigger.addEventListener("mouseover",drawer);
if(hohGenresTrigger.classList.contains("hohActive")){
drawer();
}
};
//get anime list
let personalStatsCallback = function(data){
personalStats.innerText = "";
create("hr","hohSeparator",false,personalStats)
create("h1","hohStatHeading","Anime stats for " + user,personalStats);
let list = returnList(data);
let scoreList = list.filter(element => element.scoreRaw);
if(whoAmI && whoAmI !== user){
let compatabilityButton = create("button",["button","hohButton"],"Compatibility",personalStats);
let compatLocation = create("div","#hohCheckCompat",false,personalStats);
compatabilityButton.onclick = function(){
compatLocation.innerText = "loading...";
compatLocation.style.marginTop = "5px";
compatCheck(
scoreList,
whoAmI,
"ANIME",
function(data){
formatCompat(data,compatLocation)
}
)
};
};
let addStat = function(text,value,comment){//value,value,html
let newStat = create("p","hohStat",false,personalStats);
create("span",false,text,newStat);
create("span","hohStatValue",value,newStat);
if(comment){
let newStatComment = create("span",false,false,newStat);
newStatComment.innerHTML = comment;
};
};
//first activity
let oldest = list.filter(
item => item.startedAt.year
).map(
item => item.startedAt
).sort((b,a) =>
(a.year < b.year)
|| (a.year === b.year && a.month < b.month)
|| (a.year === b.year && a.month === b.month && a.day < b.day)
)[0];
//scoring stats
let previouScore = 0;
let maxRunLength = 0;
let maxRunLengthScore = 0;
let runLength = 0;
let sumEntries = 0;
let amount = scoreList.length;
let sumWeight = 0;
let sumEntriesWeight = 0;
let average = 0;
let median = (scoreList.length ? Stats.median(scoreList,e => e.scoreRaw) : 0);
let sumDuration = 0;
let publicDeviation = 0;
let publicDifference = 0;
let longestDuration = {
time: 0,
name: "",
status: "",
rewatch: 0,
id: 0
};
scoreList.sort((a,b) => a.scoreRaw - b.scoreRaw);
list.forEach(item => {
let entryDuration = (item.media.duration || 1)*(item.progress || 0);//current round
item.episodes = item.progress || 0;
if(useScripts.noRewatches && item.repeat){
entryDuration = Math.max(
item.progress || 0,
item.media.episodes || 1,
) * (item.media.duration || 1);//first round
item.episodes = Math.max(
item.progress || 0,
item.media.episodes || 1
);
}
else{
entryDuration += (item.repeat || 0) * Math.max(
item.progress || 0,
item.media.episodes || 1
) * (item.media.duration || 1);//repeats
item.episodes += (item.repeat || 0) * Math.max(
item.progress || 0,
item.media.episodes || 1
);
}
if(item.listJSON && item.listJSON.adjustValue){
item.episodes = Math.max(0,item.episodes + item.listJSON.adjustValue);
entryDuration = Math.max(0,entryDuration + item.listJSON.adjustValue*(item.media.duration || 1));
};
item.watchedDuration = entryDuration;
sumDuration += entryDuration;
if(entryDuration > longestDuration.time){
longestDuration.time = entryDuration;
longestDuration.name = item.media.title.romaji;
longestDuration.status = item.status;
longestDuration.rewatch = item.repeat;
longestDuration.id = item.mediaId;
};
});
scoreList.forEach(item => {
sumEntries += item.scoreRaw;
if(item.scoreRaw === previouScore){
runLength++;
if(runLength > maxRunLength){
maxRunLength = runLength;
maxRunLengthScore = item.scoreRaw;
};
}
else{
runLength = 1;
previouScore = item.scoreRaw;
};
sumWeight += (item.media.duration || 1) * (item.media.episodes || 0);
sumEntriesWeight += item.scoreRaw*(item.media.duration || 1) * (item.media.episodes || 0);
});
if(amount){
average = sumEntries/amount;
}
if(scoreList.length){
publicDeviation = Math.sqrt(
scoreList.reduce(function(accum,element){
if(!element.media.meanScore){
return accum;
}
return accum + Math.pow(element.media.meanScore - element.scoreRaw,2);
},0)/amount
);
publicDifference = scoreList.reduce(function(accum,element){
if(!element.media.meanScore){
return accum;
}
return accum + (element.scoreRaw - element.media.meanScore);
},0)/amount
}
list.sort((a,b) => a.mediaId - b.mediaId);
//display scoring stats
addStat("Anime on list: ",list.length);
addStat("Anime rated: ",amount);
if(amount !== 0){//no scores
if(amount === 1){
addStat("Only one score given: ",maxRunLengthScore);
}
else{
addStat(
"Average score: ",
average.toPrecision(4)
);
addStat(
"Average score: ",
(sumEntriesWeight/sumWeight).toPrecision(4),
" (weighted by duration)"
);
addStat("Median score: ",median);
addStat(
"Global difference: ",
publicDifference.roundPlaces(2),
" (average difference from global average)"
);
addStat(
"Global deviation: ",
publicDeviation.roundPlaces(2),
" (standard deviation from the global average of each entry)"
);
if(maxRunLength > 1){
addStat("Most common score: ",maxRunLengthScore, " (" + maxRunLength + " instances)");
}
else{
addStat("Most common score: ","","no two scores alike");
};
};
//longest activity
let singleText = (100*longestDuration.time/sumDuration).roundPlaces(2) + "% is ";
singleText += "" + longestDuration.name + "";
if(longestDuration.rewatch === 0){
if(longestDuration.status === "CURRENT"){
singleText += ". Currently watching."
}
else if(longestDuration.status === "PAUSED"){
singleText += ". On hold."
}
else if(longestDuration.status === "DROPPED"){
singleText += ". Dropped."
};
}
else{
if(longestDuration.status === "COMPLETED"){
if(longestDuration.rewatch === 1){
singleText += ". Rewatched once.";
}
else if(longestDuration.rewatch === 2){
singleText += ". Rewatched twice.";
}
else{
singleText += ". Rewatched " + longestDuration.rewatch + " times.";
};
}
else if(longestDuration.status === "CURRENT" || status === "REPEATING"){
if(longestDuration.rewatch === 1){
singleText += ". First rewatch in progress.";
}
else if(longestDuration.rewatch === 2){
singleText += ". Second rewatch in progress.";
}
else{
singleText += ". Rewatch number " + longestDuration.rewatch + " in progress.";
};
}
else if(longestDuration.status === "PAUSED"){
if(longestDuration.rewatch === 1){
singleText += ". First rewatch on hold.";
}
else if(longestDuration.rewatch === 2){
singleText += ". Second rewatch on hold.";
}
else{
singleText += ". Rewatch number " + longestDuration.rewatch + " on hold.";
};
}
else if(longestDuration.status === "DROPPED"){
if(longestDuration.rewatch === 1){
singleText += ". Dropped on first rewatch.";
}
else if(longestDuration.rewatch === 2){
singleText += ". Dropped on second rewatch.";
}
else{
singleText += ". Dropped on rewatch number " + longestDuration.rewatch + ".";
};
};
};
addStat(
"Time watched: ",
(sumDuration/(60*24)).roundPlaces(2),
" days (" + singleText + ")"
);
};
let TVepisodes = 0;
let TVepisodesLeft = 0;
list.filter(show => show.media.format === "TV").forEach(function(show){
TVepisodes += show.progress;
TVepisodes += show.repeat * Math.max(1,(show.media.episodes || 0),show.progress);
if(show.status === "CURRENT"){
TVepisodesLeft += Math.max((show.media.episodes || 0) - show.progress,0);
};
});
addStat("TV episodes watched: ",TVepisodes);
addStat("TV episodes remaining for current shows: ",TVepisodesLeft);
if(oldest){
create("p",false,"First logged anime: " + oldest.year + "-" + oldest.month + "-" + oldest.day + ". (users can change start dates)",personalStats);
};
let animeFormatter = {
title: "Custom Anime Tags",
display: !useScripts.hideCustomTags,
headings: ["Tag","Count","Mean Score","Time Watched","Episodes","Eps remaining"],
focus: -1,
celData: [
function(cel,data,index,isPrimary){
if(isPrimary){
let nameCellCount = create("div","count",(index+1),cel);
let nameCellTag = create("a",false,data[index].name,cel,"cursor:pointer;");
let nameCellStatus = create("span","hohSumableStatusContainer",false,cel);
Object.keys(distributionColours).sort().forEach(function(status){
if(data[index].status && data[index].status[status]){
let statusSumDot = create("div","hohSumableStatus",data[index].status[status],nameCellStatus);
statusSumDot.style.background = distributionColours[status];
statusSumDot.title = data[index].status[status] + " " + capitalize(status.toLowerCase());
if(data[index].status[status] > 99){
statusSumDot.style.fontSize = "8px";
}
if(data[index].status[status] > 999){
statusSumDot.style.fontSize = "6px";
}
statusSumDot.onclick = function(e){
e.stopPropagation();
Array.from(cel.parentNode.nextSibling.children).forEach(function(child){
if(child.children[1].children[0].title === status.toLowerCase()){
child.style.display = "grid";
}
else{
child.style.display = "none";
};
});
}
}
});
}
else{
create("a","hohNameCel",data[index].name,cel)
.href = "/anime/" + data[index].mediaId + "/" + safeURL(data[index].name);
}
},
function(cel,data,index,isPrimary){
if(isPrimary){
cel.innerText = data[index].list.length;
}
else{
let statusDot = create("div","hohStatusDot",false,cel);
statusDot.style.backgroundColor = distributionColours[data[index].status];
statusDot.title = data[index].status.toLowerCase();
if(data[index].status === "COMPLETED"){
statusDot.style.backgroundColor = "transparent";//default case
}
if(data[index].repeat === 1){
cel.innerHTML += svgAssets.repeat;
}
else if(data[index].repeat > 1){
cel.innerHTML += svgAssets.repeat + data[index].repeat;
}
}
},
function(cel,data,index,isPrimary){
if(isPrimary){
if(data[index].average === 0){
cel.innerText = "-";
}
else{
cel.innerText = (data[index].average).roundPlaces(1);
}
}
else{
if(data[index].score === 0){
cel.innerText = "-";
}
else{
cel.innerText = (data[index].score).roundPlaces(1);
}
}
},
function(cel,data,index){
cel.innerText = formatTime(data[index].duration*60,"short");
cel.title = (data[index].duration/60).roundPlaces(1) + " hours";
},
function(cel,data,index,isPrimary){
if(isPrimary){
if(!data[index].list.length){
cel.innerText = "-";
}
else{
cel.innerText = data[index].episodes;
}
}
else{
cel.innerText = data[index].episodes;
}
},
function(cel,data,index,isPrimary){
if(data[index].episodes === 0 && data[index].remaining === 0 || isPrimary && !data[index].list.length){
cel.innerText = "-";
}
else if(data[index].remaining === 0){
cel.innerText = "completed";
}
else{
if(useScripts.timeToCompleteColumn){
cel.innerText = data[index].remaining + " (" + formatTime(data[index].remainingTime*60,"short") + ")";
}
else{
cel.innerText = data[index].remaining;
}
}
}
],
sorting: [
(a,b) => ALPHABETICAL(a => a.name),
(b,a) => a.list.length - b.list.length,
(b,a) => a.average - b.average,
(b,a) => a.duration - b.duration,
(b,a) => a.episodes - b.episodes,
(b,a) => a.remaining - b.remaining
]
};
const animeFields = [
{
key : "name",
method : function(media){
if(aliases.has(media.mediaId)){
return aliases.get(media.mediaId);
}
if(useScripts.titleLanguage === "NATIVE" && media.media.title.native){
return media.media.title.native;
}
else if(useScripts.titleLanguage === "ENGLISH" && media.media.title.english){
return media.media.title.english;
};
return media.media.title.romaji;
}
},{
key : "mediaId",
method : media => media.mediaId
},{
key : "score",
method : media => media.scoreRaw
},{
key : "repeat",
method : media => media.repeat
},{
key : "status",
sumable : function(acc,val){
if(!acc){
acc = {};
Object.keys(distributionColours).forEach(function(key){
acc[key] = 0;
})
}
acc[val]++;
return acc;
},
method : media => media.status
},{
key : "duration",
sumable : ACCUMULATE,
method : media => media.watchedDuration
},{
key : "episodes",
sumable : ACCUMULATE,
method : media => media.episodes
},{
key : "remaining",
sumable : ACCUMULATE,
method : function(media){
return Math.max((media.media.episodes || 0) - media.progress,0);
}
},{
key : "remainingTime",
sumable : ACCUMULATE,
method : function(media){
return Math.max(((media.media.episodes || 0) - media.progress) * (media.media.duration || 1),0);
}
}
];
let customTags = customTagsCollection(list,animeFormatter.title,animeFields);
if(customTags.length){
let customTagsAnimeTable = create("div","#customTagsAnimeTable",false,personalStats);
drawTable(customTags,animeFormatter,customTagsAnimeTable,true,true);
};
let listOfTags = regularTagsCollection(list,animeFields,media => media.media.tags);
if(listOfTags.length > 50){
listOfTags = listOfTags.filter(a => a.list.length >= 3);
}
drawTable(listOfTags,animeFormatter,regularAnimeTable,true,false);
semaPhoreAnime = list;
nativeTagsReplacer();
generalAPIcall(queryMediaListStaff,{name: user,listType: "ANIME"},function(data){
let rawStaff = returnList(data);
rawStaff.forEach(function(raw,index){
raw.status = list[index].status;
raw.watchedDuration = list[index].watchedDuration;
raw.scoreRaw = list[index].scoreRaw;
});
let staffMap = {};
rawStaff.filter(obj => obj.status !== "PLANNING").forEach(function(media){
media.media.staff.forEach(function(staff){
if(!staffMap[staff.id]){
staffMap[staff.id] = {
watchedDuration: 0,
count: 0,
scoreCount: 0,
scoreSum: 0,
id: staff.id,
name: staff.name
};
};
if(media.watchedDuration){
staffMap[staff.id].watchedDuration += media.watchedDuration;
staffMap[staff.id].count++;
};
if(media.scoreRaw){
staffMap[staff.id].scoreSum += media.scoreRaw;
staffMap[staff.id].scoreCount++;
};
});
});
let staffList = [];
Object.keys(staffMap).forEach(function(key){
staffList.push(staffMap[key]);
});
staffList = staffList.filter(
obj => obj.count >= 1
).sort(
(b,a) => a.count - b.count || a.watchedDuration - b.watchedDuration
);
if(staffList.length > 300){
staffList = staffList.filter(obj => obj.count >= 3);
};
if(staffList.length > 300){
staffList = staffList.filter(obj => obj.count >= 5);
};
if(staffList.length > 300){
staffList = staffList.filter(obj => obj.count >= 10);
};
let hasScores = staffList.some(a => a.scoreCount);
let drawStaffList = function(){
while(animeStaff.childElementCount){
animeStaff.lastChild.remove();
}
animeStaff.innerText = "";
let table = create("div",["table","hohTable","hohNoPointer"],false,animeStaff);
let headerRow = create("div",["header","row","good"],false,table);
let nameHeading = create("div",false,"Name",headerRow,"cursor:pointer;");
let countHeading = create("div",false,"Count",headerRow,"cursor:pointer;");
let scoreHeading = create("div",false,"Mean Score",headerRow,"cursor:pointer;");
if(!hasScores){
scoreHeading.style.display = "none";
}
let timeHeading = create("div",false,"Time Watched",headerRow,"cursor:pointer;");
staffList.forEach(function(staff,index){
let row = create("div",["row","good"],false,table);
let nameCel = create("div",false,(index + 1) + " ",row);
let staffLink = create("a",["link","newTab"],(staff.name.first + " " + (staff.name.last || "")).trim(),nameCel);
staffLink.href = "/staff/" + staff.id;
create("div",false,staff.count,row);
if(hasScores){
create("div",false,(staff.scoreSum/staff.scoreCount).roundPlaces(2),row);
}
let timeCel = create("div",false,formatTime(staff.watchedDuration*60),row);
timeCel.title = (staff.watchedDuration/60).roundPlaces(1) + " hours";
});
let csvButton = create("button",["csvExport","button","hohButton"],"CSV data",animeStaff,"margin-top:10px;");
let jsonButton = create("button",["jsonExport","button","hohButton"],"JSON data",animeStaff,"margin-top:10px;");
csvButton.onclick = function(){
let csvContent = 'Staff,Count,"Mean Score","Time Watched"\n';
staffList.forEach(function(staff){
csvContent += "\"" + (staff.name.first + " " + (staff.name.last || "")).trim().replace(/"/g,"\"\"") + "\",";
csvContent += staff.count + ",";
csvContent += (staff.scoreSum/staff.scoreCount).roundPlaces(2) + ",";
csvContent += (staff.watchedDuration/60).roundPlaces(1) + "\n";
});
saveAs(csvContent,"Anime staff stats for " + user + ".csv",true);
};
jsonButton.onclick = function(){
saveAs({
type: "ANIME",
user: user,
timeStamp: NOW(),
version: "1.00",
scriptInfo: scriptInfo,
url: document.URL,
description: "Anilist anime staff stats for " + user,
fields: [
{name: "name",description: "The full name of the staff member, as firstname lastname"},
{name: "staffID",description: "The staff member's database number in the Anilist database"},
{name: "count",description: "The total number of media this staff member has credits for, for the current user"},
{name: "score",description: "The current user's mean score for the staff member out of 100"},
{name: "minutesWatched",description: "How many minutes of this staff member's credited media the current user has watched"}
],
data: staffList.map(staff => {
return {
name: (staff.name.first + " " + (staff.name.last || "")).trim(),
staffID: staff.id,
count: staff.count,
score: (staff.scoreSum/staff.scoreCount).roundPlaces(2),
minutesWatched: staff.watchedDuration
}
})
},"Anime staff stats for " + user + ".json");
}
nameHeading.onclick = function(){
staffList.sort(ALPHABETICAL(a => a.name.first + " " + (a.name.last || "")));
drawStaffList();
};
countHeading.onclick = function(){
staffList.sort((b,a) => a.count - b.count || a.watchedDuration - b.watchedDuration);
drawStaffList();
};
scoreHeading.onclick = function(){
staffList.sort((b,a) => a.scoreSum/a.scoreCount - b.scoreSum/b.scoreCount);
drawStaffList();
};
timeHeading.onclick = function(){
staffList.sort((b,a) => a.watchedDuration - b.watchedDuration);
drawStaffList();
};
};
let clickOnce = function(){
drawStaffList();
let place = document.querySelector(`[href$="/stats/anime/staff"]`);
if(place){
place.removeEventListener("click",clickOnce);
}
}
let waiter = function(){
if(location.pathname.includes("/stats/anime/staff")){
clickOnce();
return;
}
let place = document.querySelector(`[href$="/stats/anime/staff"]`);
if(place){
place.addEventListener("click",clickOnce);
}
else{
setTimeout(waiter,200);
}
};waiter();
},"hohListCacheAnimeStaff" + user,15*60*1000);
let studioMap = {};
list.forEach(function(anime){
anime.media.studios.nodes.forEach(function(studio){
if(!useScripts.allStudios && !studio.isAnimationStudio){
return;
}
if(!studioMap[studio.name]){
studioMap[studio.name] = {
watchedDuration: 0,
count: 0,
scoreCount: 0,
scoreSum: 0,
id: studio.id,
isAnimationStudio: studio.isAnimationStudio,
name: studio.name,
media: []
};
}
if(anime.watchedDuration){
studioMap[studio.name].watchedDuration += anime.watchedDuration;
studioMap[studio.name].count++;
};
if(anime.scoreRaw){
studioMap[studio.name].scoreSum += anime.scoreRaw;
studioMap[studio.name].scoreCount++;
};
let title = anime.media.title.romaji;
if(anime.status !== "PLANNING"){
if(useScripts.titleLanguage === "NATIVE" && anime.media.title.native){
title = anime.media.title.native;
}
else if(useScripts.titleLanguage === "ENGLISH" && anime.media.title.english){
title = anime.media.title.english;
}
studioMap[studio.name].media.push({
watchedDuration: anime.watchedDuration,
score: anime.scoreRaw,
title: title,
id: anime.mediaId,
repeat: anime.repeat,
status: anime.status
});
}
});
});
let studioList = [];
Object.keys(studioMap).forEach(function(key){
studioList.push(studioMap[key]);
});
studioList = studioList.filter(obj => obj.count >= 1).sort((b,a) => a.count - b.count || a.watchedDuration - b.watchedDuration);
studioList.forEach(function(studio){
studio.media.sort((b,a) => a.score - b.score);
});
let hasScores = studioList.some(a => a.scoreCount);
let drawStudioList = function(){
while(animeStudios.childElementCount){
animeStudios.lastChild.remove();
}
animeStudios.innerText = "";
let table = create("div",["table","hohTable"],false,animeStudios);
let headerRow = create("div",["header","row","good"],false,table);
let nameHeading = create("div",false,"Name",headerRow,"cursor:pointer;");
let countHeading = create("div",false,"Count",headerRow,"cursor:pointer;");
let scoreHeading = create("div",false,"Mean Score",headerRow,"cursor:pointer;");
if(!hasScores){
scoreHeading.style.display = "none";
}
let timeHeading = create("div",false,"Time Watched",headerRow,"cursor:pointer;");
studioList.forEach(function(studio,index){
let row = create("div",["row","good"],false,table);
let nameCel = create("div",false,(index + 1) + " ",row);
let studioLink = create("a",["link","newTab"],studio.name,nameCel);
studioLink.href = "/studio/" + studio.id;
if(!studio.isAnimationStudio){
studioLink.style.color = "rgb(var(--color-green))";
};
let nameCellStatus = create("span","hohSumableStatusContainer",false,nameCel);
Object.keys(distributionColours).sort().forEach(status => {
let statCount = studio.media.filter(media => media.status === status).length;
if(statCount){
let statusSumDot = create("div","hohSumableStatus",statCount,nameCellStatus);
statusSumDot.style.background = distributionColours[status];
statusSumDot.title = statCount + " " + capitalize(status.toLowerCase());
if(statCount > 99){
statusSumDot.style.fontSize = "8px";
}
if(statCount > 999){
statusSumDot.style.fontSize = "6px";
}
statusSumDot.onclick = function(e){
e.stopPropagation();
Array.from(nameCel.parentNode.nextSibling.children).forEach(function(child){
if(child.children[1].children[0].title === status.toLowerCase()){
child.style.display = "grid";
}
else{
child.style.display = "none";
};
});
}
}
});
create("div",false,studio.count,row);
if(hasScores){
let scoreCel = create("div",false,(studio.scoreSum/studio.scoreCount).roundPlaces(2),row);
scoreCel.title = studio.scoreCount + " ratings";
}
let timeString = formatTime(studio.watchedDuration*60);
let timeCel = create("div",false,timeString,row);
timeCel.title = (studio.watchedDuration/60).roundPlaces(1) + " hours";
let showRow = create("div",false,false,table,"display:none;");
studio.media.forEach(function(top){
let secondRow = create("div",["row","hohSecondaryRow","good"],false,showRow);
let titleCel = create("div",false,false,secondRow,"margin-left:50px;");
let titleLink = create("a","link",top.title,titleCel);
titleLink.href = "/anime/" + top.id + "/" + safeURL(top.title);
let countCel = create("div",false,false,secondRow);
let statusDot = create("div","hohStatusDot",false,countCel);
statusDot.style.backgroundColor = distributionColours[top.status];
statusDot.title = top.status.toLowerCase();
if(top.status === "COMPLETED"){
statusDot.style.backgroundColor = "transparent";//default case
}
if(top.repeat === 1){
countCel.innerHTML += svgAssets.repeat;
}
else if(top.repeat > 1){
countCel.innerHTML += svgAssets.repeat + top.repeat;
}
create("div",false,(top.score ? top.score : "-"),secondRow);
let timeString = formatTime(top.watchedDuration*60);
let timeCel = create("div",false,timeString,secondRow);
timeCel.title = (top.watchedDuration/60).roundPlaces(1) + " hours";
});
let open = false;
row.onclick = function(){
if(open){
open = false;
showRow.style.display = "none";
}
else{
open = true;
showRow.style.display = "block";
};
};
});
let csvButton = create("button",["csvExport","button","hohButton"],"CSV data",animeStudios,"margin-top:10px;");
let jsonButton = create("button",["jsonExport","button","hohButton"],"JSON data",animeStudios,"margin-top:10px;");
csvButton.onclick = function(){
let csvContent = 'Studio,Count,"Mean Score","Time Watched"\n';
studioList.forEach(function(studio){
csvContent += "\"" + studio.name.replace(/"/g,"\"\"") + "\",";
csvContent += studio.count + ",";
csvContent += (studio.scoreSum/studio.scoreCount).roundPlaces(2) + ",";
csvContent += (studio.watchedDuration/60).roundPlaces(1) + "\n";
});
saveAs(csvContent,"Anime studio stats for " + user + ".csv",true);
};
jsonButton.onclick = function(){
saveAs({
type: "ANIME",
user: user,
timeStamp: NOW(),
version: "1.00",
scriptInfo: scriptInfo,
url: document.URL,
description: "Anilist anime studio stats for " + user,
fields: [
{name: "studio",description: "The name of the studio. (Can also be other companies, depending on the user's settings)"},
{name: "studioID",description: "The studio's database number in the Anilist database"},
{name: "count",description: "The total number of media this studio has credits for, for the current user"},
{name: "score",description: "The current user's mean score for the studio out of 100"},
{name: "minutesWatched",description: "How many minutes of this studio's credited media the current user has watched"},
{
name: "media",
description: "A list of the media associated with this studio",
subSelection: [
{name: "title",description: "The title of the media (language depends on user settings)"},
{name: "ID",description: "The media's database number in the Anilist database"},
{name: "score",description: "The current user's mean score for the media out of 100"},
{name: "minutesWatched",description: "How many minutes of the media the current user has watched"},
{name: "status",description: "The current user's watching status for the media"},
]
}
],
data: studioList.map(studio => {
return {
studio: studio.name,
studioID: studio.id,
count: studio.count,
score: (studio.scoreSum/studio.scoreCount).roundPlaces(2),
minutesWatched: studio.watchedDuration,
media: studio.media.map(media => {
return {
title: media.title,
ID: media.id,
score: media.score,
minutesWatched: media.watchedDuration,
status: media.status
}
})
}
})
},"Anime studio stats for " + user + ".json");
}
nameHeading.onclick = function(){
studioList.sort(ALPHABETICAL(a => a.name));
studioList.forEach(studio => {
studio.media.sort(ALPHABETICAL(a => a.title));
});
drawStudioList();
};
countHeading.onclick = function(){
studioList.sort((b,a) => a.count - b.count || a.watchedDuration - b.watchedDuration);
drawStudioList();
};
scoreHeading.onclick = function(){
studioList.sort((b,a) => a.scoreSum/a.scoreCount - b.scoreSum/b.scoreCount);
studioList.forEach(studio => {
studio.media.sort((b,a) => a.score - b.score);
});
drawStudioList();
};
timeHeading.onclick = function(){
studioList.sort((b,a) => a.watchedDuration - b.watchedDuration);
studioList.forEach(function(studio){
studio.media.sort((b,a) => a.watchedDuration - b.watchedDuration);
});
drawStudioList();
};
};
let clickOnce = function(){
drawStudioList();
let place = document.querySelector(`[href$="/stats/anime/studios"]`);
if(place){
place.removeEventListener("click",clickOnce);
}
}
let waiter = function(){
if(location.pathname.includes("/stats/anime/studios")){
clickOnce();
return;
}
let place = document.querySelector(`[href$="/stats/anime/studios"]`);
if(place){
place.addEventListener("click",clickOnce);
}
else{
setTimeout(waiter,200);
}
};waiter();
};
if(user === whoAmI){
generalAPIcall(
queryMediaListAnime,
{
name: user,
listType: "ANIME"
},
personalStatsCallback,"hohListCacheAnime",10*60*1000
);
}
else{
generalAPIcall(
queryMediaListAnime,
{
name: user,
listType: "ANIME"
},
personalStatsCallback
);
}
//manga stats
let personalStatsMangaCallback = function(data){
personalStatsManga.innerText = "";
create("hr","hohSeparator",false,personalStatsManga);
create("h1","hohStatHeading","Manga stats for " + user,personalStatsManga);
let list = returnList(data);
let scoreList = list.filter(element => element.scoreRaw);
let personalStatsMangaContainer = create("div",false,false,personalStatsManga);
if(whoAmI && whoAmI !== user){
let compatabilityButton = create("button",["button","hohButton"],"Compatibility",personalStatsManga);
let compatLocation = create("div","#hohCheckCompatManga",false,personalStatsManga);
compatabilityButton.onclick = function(){
compatLocation.innerText = "loading...";
compatLocation.style.marginTop = "5px";
compatCheck(
scoreList,
whoAmI,
"MANGA",
function(data){
formatCompat(data,compatLocation)
}
)
};
};
let addStat = function(text,value,comment){//value,value,html
let newStat = create("p","hohStat",false,personalStatsManga);
create("span",false,text,newStat);
create("span","hohStatValue",value,newStat);
if(comment){
let newStatComment = create("span",false,false,newStat);
newStatComment.innerHTML = comment;
};
};
let chapters = 0;
let volumes = 0;
/*
For most airing anime, Anilist provides "media.nextAiringEpisode.episode"
Unfortunately, the same is not the case for releasing manga.
THIS DOESN'T MATTER the first time a user is reading something, as we are then just using the current progress.
But on a re-read, we need the total length to count all the chapters read.
I can (and do) get a lower bound for this by using the current progress (this is what Anilist does),
but this is not quite accurate, especially early in a re-read.
The list below is to catch some of those exceptions
*/
let unfinishedLookup = function(mediaId,mode,mediaStatus,mediaProgress){
if(mediaStatus === "FINISHED"){
return 0;//it may have finished since the list was updated
};
if(commonUnfinishedManga.hasOwnProperty(mediaId)){
if(mode === "chapters"){
return commonUnfinishedManga[mediaId].chapters;
}
else if(mode === "volumes"){
return commonUnfinishedManga[mediaId].volumes;
}
else if(mode === "volumesNow"){
if(commonUnfinishedManga[mediaId].chapters <= mediaProgress){
return commonUnfinishedManga[mediaId].volumes;
}
else{
return 0;//conservative
};
};
return 0;//fallback
}
else{
return 0;//not in our list
};
};
list.forEach(function(item){
let chaptersRead = 0;
let volumesRead = 0;
if(item.status === "COMPLETED"){//if it's completed, we can make some safe assumptions
chaptersRead += Math.max(//chapter progress on the current read
item.media.chapters,//in most cases, it has a chapter count
item.media.volumes,//if not, there's at least 1 chapter per volume
item.progress,//if it doesn't have a volume count either, the current progress is probably not out of date
item.progressVolumes,//if it doesn't have a chapter progress, count at least 1 chapter per volume
1//finally, an entry has at least 1 chapter
);
volumesRead += Math.max(
item.progressVolumes,
item.media.volumes,
unfinishedLookup(item.mediaId+"","volumesNow",item.media.status,item.progress)//if people have forgotten to update their volume count and have caught up.
);
}
else{//we may only assume what's on the user's list.
chaptersRead += Math.max(
item.progress,
item.progressVolumes
);
volumesRead += Math.max(
item.progressVolumes,
unfinishedLookup(item.mediaId+"","volumesNow",item.media.status,item.progress)
);
};
if(useScripts.noRewatches && item.repeat){//if they have a reread, they have at least completed it
chaptersRead = Math.max(//first round
item.media.chapters,
item.media.volumes,
item.progress,
item.progressVolumes,
unfinishedLookup(item.mediaId+"","chapters",item.media.status),//use our lookup table
1
);
volumesRead = Math.max(
item.media.volumes,
item.progressVolumes,
unfinishedLookup(item.mediaId+"","volumes",item.media.status)
);
}
else{
chaptersRead += item.repeat * Math.max(//chapters from rereads
item.media.chapters,
item.media.volumes,
item.progress,
item.progressVolumes,
unfinishedLookup(item.mediaId+"","chapters",item.media.status),//use our lookup table
1
);
volumesRead += item.repeat * Math.max(//many manga have no volumes, so we can't make all of the same assumptions
item.media.volumes,
item.progressVolumes,//better than nothing if a volume count is missing
unfinishedLookup(item.mediaId+"","volumes",item.media.status)
);
};
if(item.listJSON && item.listJSON.adjustValue){
chaptersRead = Math.max(0,chaptersRead + item.listJSON.adjustValue);
};
chapters += chaptersRead;
volumes += volumesRead;
item.volumesRead = volumesRead;
item.chaptersRead = chaptersRead;
});
//
let previouScore = 0;
let maxRunLength = 0;
let maxRunLengthScore = 0;
let runLength = 0;
let sumEntries = 0;
let average = 0;
let publicDeviation = 0;
let publicDifference = 0;
let amount = scoreList.length;
let median = (scoreList.length ? Stats.median(scoreList,e => e.scoreRaw) : 0);
let sumWeight = 0;
let sumEntriesWeight = 0;
scoreList.sort((a,b) => a.scoreRaw - b.scoreRaw);
scoreList.forEach(function(item){
sumEntries += item.scoreRaw;
if(item.scoreRaw === previouScore){
runLength++;
if(runLength > maxRunLength){
maxRunLength = runLength;
maxRunLengthScore = item.scoreRaw;
};
}
else{
runLength = 1;
previouScore = item.scoreRaw;
};
sumWeight += item.chaptersRead;
sumEntriesWeight += item.scoreRaw * item.chaptersRead;
});
addStat("Manga on list: ",list.length);
addStat("Manga rated: ",amount);
addStat("Total chapters: ",chapters);
addStat("Total volumes: ",volumes);
if(amount){
average = sumEntries/amount;
};
if(scoreList.length){
publicDeviation = Math.sqrt(
scoreList.reduce(function(accum,element){
if(!element.media.meanScore){
return accum;
}
return accum + Math.pow(element.media.meanScore - element.scoreRaw,2);
},0)/amount
);
publicDifference = scoreList.reduce(function(accum,element){
if(!element.media.meanScore){
return accum;
}
return accum + (element.scoreRaw - element.media.meanScore);
},0)/amount
}
list.sort((a,b) => a.mediaId - b.mediaId);
if(amount){//no scores
if(amount === 1){
addStat(
"Only one score given: ",
maxRunLengthScore
);
}
else{
addStat(
"Average score: ",
average.toPrecision(4)
);
addStat(
"Average score: ",
(sumEntriesWeight/sumWeight).toPrecision(4),
" (weighted by chapters)"
);
addStat("Median score: ",median);
addStat(
"Global difference: ",
publicDifference.roundPlaces(2),
" (average difference from global average)"
);
addStat(
"Global deviation: ",
publicDeviation.roundPlaces(2),
" (standard deviation from the global average of each entry)"
);
if(maxRunLength > 1){
addStat("Most common score: ",maxRunLengthScore, " (" + maxRunLength + " instances)");
}
else{
addStat("Most common score: ","","no two scores alike");
};
};
};
//
let mangaFormatter = {
title: "Custom Manga Tags",
display: !useScripts.hideCustomTags,
headings: ["Tag","Count","Mean Score","Chapters","Volumes"],
focus: -1,
celData: [
function(cel,data,index,isPrimary){
if(isPrimary){
let nameCellCount = create("div","count",(index+1),cel);
create("a",false,data[index].name,cel,"cursor:pointer;");
let nameCellStatus = create("span","hohSumableStatusContainer",false,cel);
Object.keys(distributionColours).sort().forEach(function(status){
if(data[index].status && data[index].status[status]){
let statusSumDot = create("div","hohSumableStatus",data[index].status[status],nameCellStatus);
statusSumDot.style.background = distributionColours[status];
statusSumDot.title = data[index].status[status] + " " + capitalize(status.toLowerCase());
if(data[index].status[status] > 99){
statusSumDot.style.fontSize = "8px";
}
if(data[index].status[status] > 999){
statusSumDot.style.fontSize = "6px";
}
statusSumDot.onclick = function(e){
e.stopPropagation();
Array.from(cel.parentNode.nextSibling.children).forEach(function(child){
if(child.children[1].children[0].title === status.toLowerCase()){
child.style.display = "grid";
}
else{
child.style.display = "none";
};
});
}
}
});
}
else{
create("a","hohNameCel",data[index].name,cel)
.href = "/manga/" + data[index].mediaId + "/" + safeURL(data[index].name);
}
},
function(cel,data,index,isPrimary){
if(isPrimary){
cel.innerText = data[index].list.length;
}
else{
let statusDot = create("div","hohStatusDot",false,cel);
statusDot.style.backgroundColor = distributionColours[data[index].status];
statusDot.title = data[index].status.toLowerCase();
if(data[index].status === "COMPLETED"){
statusDot.style.backgroundColor = "transparent";//default case
}
if(data[index].repeat === 1){
cel.innerHTML = svgAssets.repeat;
}
else if(data[index].repeat > 1){
cel.innerHTML = svgAssets.repeat + data[index].repeat;
}
}
},
function(cel,data,index,isPrimary){
if(isPrimary){
if(data[index].average === 0){
cel.innerText = "-";
}
else{
cel.innerText = (data[index].average).roundPlaces(1);
}
}
else{
if(data[index].score === 0){
cel.innerText = "-";
}
else{
cel.innerText = (data[index].score).roundPlaces(1);
}
}
},
function(cel,data,index,isPrimary){
if(isPrimary && !data[index].list.length){
cel.innerText = "-";
}
else{
cel.innerText = data[index].chaptersRead;
}
},
function(cel,data,index,isPrimary){
if(isPrimary && !data[index].list.length){
cel.innerText = "-";
}
else{
cel.innerText = data[index].volumesRead;
}
}
],
sorting: [
(a,b) => ALPHABETICAL(a => a.name),
(b,a) => a.list.length - b.list.length,
(b,a) => a.average - b.average,
(b,a) => a.chaptersRead - b.chaptersRead,
(b,a) => a.volumesRead - b.volumesRead
]
};
const mangaFields = [
{
key : "name",
method : function(media){
if(aliases.has(media.mediaId)){
return aliases.get(media.mediaId);
}
if(useScripts.titleLanguage === "NATIVE" && media.media.title.native){
return media.media.title.native;
}
else if(useScripts.titleLanguage === "ENGLISH" && media.media.title.english){
return media.media.title.english;
}
return media.media.title.romaji;
}
},{
key : "repeat",
method : media => media.repeat
},{
key : "status",
sumable : function(acc,val){
if(!acc){
acc = {};
Object.keys(distributionColours).forEach(function(key){
acc[key] = 0;
})
}
acc[val]++;
return acc;
},
method : media => media.status
},{
key : "mediaId",
method : media => media.mediaId
},{
key : "score",
method : media => media.scoreRaw
},{
key : "chaptersRead",
sumable : ACCUMULATE,
method : media => media.chaptersRead
},{
key : "volumesRead",
sumable : ACCUMULATE,
method : media => media.volumesRead
}
];
let customTags = customTagsCollection(list,mangaFormatter.title,mangaFields);
if(customTags.length){
let customTagsMangaTable = create("div","#customTagsMangaTable",false,personalStatsManga);
drawTable(customTags,mangaFormatter,customTagsMangaTable,true,true);
};
let listOfTags = regularTagsCollection(list,mangaFields,media => media.media.tags);
if(listOfTags.length > 50){
listOfTags = listOfTags.filter(a => a.list.length >= 3);
}
drawTable(listOfTags,mangaFormatter,regularMangaTable,true,false);
semaPhoreManga = list;
nativeTagsReplacer();
generalAPIcall(queryMediaListStaff,{name: user,listType: "MANGA"},function(data){
let rawStaff = returnList(data);
rawStaff.forEach(function(raw,index){
raw.status = list[index].status;
raw.chaptersRead = list[index].chaptersRead;
raw.volumesRead = list[index].volumesRead;
raw.scoreRaw = list[index].scoreRaw;
});
let staffMap = {};
rawStaff.filter(obj => obj.status !== "PLANNING").forEach(function(media){
media.media.staff.forEach(function(staff){
if(!staffMap[staff.id]){
staffMap[staff.id] = {
chaptersRead: 0,
volumesRead: 0,
count: 0,
scoreCount: 0,
scoreSum: 0,
id: staff.id,
name: staff.name
};
}
if(media.chaptersRead || media.volumesRead){
staffMap[staff.id].volumesRead += media.volumesRead;
staffMap[staff.id].chaptersRead += media.chaptersRead;
staffMap[staff.id].count++;
};
if(media.scoreRaw){
staffMap[staff.id].scoreSum += media.scoreRaw;
staffMap[staff.id].scoreCount++;
};
});
});
let staffList = [];
Object.keys(staffMap).forEach(function(key){
staffList.push(staffMap[key]);
});
staffList = staffList.filter(obj => obj.count >= 1).sort(
(b,a) => a.count - b.count || a.chaptersRead - b.chaptersRead || a.volumesRead - b.volumesRead
);
if(staffList.length > 300){
staffList = staffList.filter(obj => obj.count >= 3 || (obj.count >= 2 && obj.chaptersRead > 100) || obj.chaptersRead > 200);
};
if(staffList.length > 300){
staffList = staffList.filter(obj => obj.count >= 5 || (obj.count >= 2 && obj.chaptersRead > 200) || obj.chaptersRead > 300);
};
if(staffList.length > 300){
staffList = staffList.filter(obj => obj.count >= 10 || (obj.count >= 2 && obj.chaptersRead > 300) || obj.chaptersRead > 400);
};
let hasScores = staffList.some(a => a.scoreCount);
let drawStaffList = function(){
while(mangaStaff.childElementCount){
mangaStaff.lastChild.remove();
}
mangaStaff.innerText = "";
let table = create("div",["table","hohTable","hohNoPointer"],false,mangaStaff);
let headerRow = create("div",["header","row","good"],false,table);
let nameHeading = create("div",false,"Name",headerRow,"cursor:pointer;");
let countHeading = create("div",false,"Count",headerRow,"cursor:pointer;");
let scoreHeading = create("div",false,"Mean Score",headerRow,"cursor:pointer;");
if(!hasScores){
scoreHeading.style.display = "none";
}
let timeHeading = create("div",false,"Chapters Read",headerRow,"cursor:pointer;");
let volumeHeading = create("div",false,"Volumes Read",headerRow,"cursor:pointer;");
staffList.forEach(function(staff,index){
let row = create("div",["row","good"],false,table);
let nameCel = create("div",false,(index + 1) + " ",row);
create("a","newTab",staff.name.first + " " + (staff.name.last || ""),nameCel)
.href = "/staff/" + staff.id;
create("div",false,staff.count,row);
if(hasScores){
create("div",false,(staff.scoreSum/staff.scoreCount).roundPlaces(2),row);
}
create("div",false,staff.chaptersRead,row);
create("div",false,staff.volumesRead,row);
});
let csvButton = create("button",["csvExport","button","hohButton"],"CSV data",mangaStaff,"margin-top:10px;");
let jsonButton = create("button",["jsonExport","button","hohButton"],"JSON data",mangaStaff,"margin-top:10px;");
csvButton.onclick = function(){
let csvContent = 'Staff,Count,"Mean Score","Chapters Read","Volumes Read"\n';
staffList.forEach(function(staff){
csvContent += "\"" + (staff.name.first + " " + (staff.name.last || "")).trim().replace(/"/g,"\"\"") + "\",";
csvContent += staff.count + ",";
csvContent += (staff.scoreSum/staff.scoreCount).roundPlaces(2) + ",";
csvContent += staff.chaptersRead + ",";
csvContent += staff.volumesRead + "\n";
});
saveAs(csvContent,"Manga staff stats for " + user + ".csv",true);
};
jsonButton.onclick = function(){
saveAs({
type: "MANGA",
user: user,
timeStamp: NOW(),
version: "1.00",
scriptInfo: scriptInfo,
url: document.URL,
description: "Anilist manga staff stats for " + user,
fields: [
{name: "name",description: "The full name of the staff member, as firstname lastname"},
{name: "staffID",description: "The staff member's database number in the Anilist database"},
{name: "count",description: "The total number of media this staff member has credits for, for the current user"},
{name: "score",description: "The current user's mean score for the staff member out of 100"},
{name: "chaptersRead",description: "How many chapters of this staff member's credited media the current user has read"},
{name: "volumesRead",description: "How many volumes of this staff member's credited media the current user has read"}
],
data: staffList.map(staff => {
return {
name: (staff.name.first + " " + (staff.name.last || "")).trim(),
staffID: staff.id,
count: staff.count,
score: (staff.scoreSum/staff.scoreCount).roundPlaces(2),
chaptersRead: staff.chaptersRead,
volumesRead: staff.volumesRead
}
})
},"Manga staff stats for " + user + ".json");
}
nameHeading.onclick = function(){
staffList.sort(ALPHABETICAL(a => a.name.first + " " + (a.name.last || "")));
drawStaffList();
};
countHeading.onclick = function(){
staffList.sort(
(b,a) => a.count - b.count || a.chaptersRead - b.chaptersRead || a.volumesRead - b.volumesRead || a.scoreSum/a.scoreCount - b.scoreSum/b.scoreCount
);
drawStaffList();
};
scoreHeading.onclick = function(){
staffList.sort(
(b,a) => a.scoreSum/a.scoreCount - b.scoreSum/b.scoreCount || a.count - b.count || a.chaptersRead - b.chaptersRead || a.volumesRead - b.volumesRead
);
drawStaffList();
};
timeHeading.onclick = function(){
staffList.sort(
(b,a) => a.chaptersRead - b.chaptersRead || a.volumesRead - b.volumesRead || a.count - b.count || a.scoreSum/a.scoreCount - b.scoreSum/b.scoreCount
);
drawStaffList();
};
volumeHeading.onclick = function(){
staffList.sort(
(b,a) => a.volumesRead - b.volumesRead || a.chaptersRead - b.chaptersRead || a.count - b.count || a.scoreSum/a.scoreCount - b.scoreSum/b.scoreCount
);
drawStaffList();
};
};
let clickOnce = function(){
drawStaffList();
let place = document.querySelector(`[href$="/stats/manga/staff"]`);
if(place){
place.removeEventListener("click",clickOnce);
}
}
let waiter = function(){
if(location.pathname.includes("/stats/manga/staff")){
clickOnce();
return;
}
let place = document.querySelector(`[href$="/stats/manga/staff"]`);
if(place){
place.addEventListener("click",clickOnce);
}
else{
setTimeout(waiter,200);
}
};waiter();
},"hohListCacheMangaStaff" + user,10*60*1000);
};
if(user === whoAmI){
generalAPIcall(
queryMediaListManga,
{
name: user,
listType: "MANGA"
},
personalStatsMangaCallback,"hohListCacheManga",10*60*1000
);
}
else{
generalAPIcall(
queryMediaListManga,
{
name: user,
listType: "MANGA"
},
personalStatsMangaCallback
);
}
};
let tabWaiter = function(){
let tabMenu = filterGroup.querySelectorAll(".filter-group > a");
tabMenu.forEach(function(tab){
tab.onclick = function(){
Array.from(document.querySelector(".stats-wrap").children).forEach(child => {
child.style.display = "initial";
});
Array.from(document.getElementsByClassName("hohActive")).forEach(child => {
child.classList.remove("hohActive");
});
document.getElementById("hohStats").style.display = "none";
document.getElementById("hohGenres").style.display = "none";
document.querySelector(".page-content .user").classList.remove("hohSpecialPage");
};
});
if(!tabMenu.length){
setTimeout(tabWaiter,200);
}
};tabWaiter();
let statsWrap = document.querySelector(".stats-wrap");
if(statsWrap){
hohStats = create("div","#hohStats",false,statsWrap,"display:none;");
hohGenres = create("div","#hohGenres",false,statsWrap,"display:none;");
regularGenresTable = create("div","#regularGenresTable","loading...",hohGenres);
regularTagsTable = create("div","#regularTagsTable","loading...",hohGenres);
regularAnimeTable = create("div","#regularAnimeTable","loading...",statsWrap);
regularMangaTable = create("div","#regularMangaTable","loading...",statsWrap);
animeStaff = create("div","#animeStaff","loading...",statsWrap);
mangaStaff = create("div","#mangaStaff","loading...",statsWrap);
animeStudios = create("div","#animeStudios","loading...",statsWrap);
hohStats.calculated = false;
generateStatPage();
};
hohStatsTrigger.onclick = function(){
hohStatsTrigger.classList.add("hohActive");
hohGenresTrigger.classList.remove("hohActive");
document.querySelector(".page-content .user").classList.add("hohSpecialPage");
let otherActive = filterGroup.querySelector(".router-link-active");
if(otherActive){
otherActive.classList.remove("router-link-active");
otherActive.classList.remove("router-link-exact-active");
};
document.querySelectorAll(".stats-wrap > div").forEach(module => {
module.style.display = "none";
});
hohStats.style.display = "initial";
hohGenres.style.display = "none";
};
hohGenresTrigger.onclick = function(){
hohStatsTrigger.classList.remove("hohActive");
hohGenresTrigger.classList.add("hohActive");
document.querySelector(".page-content .user").classList.add("hohSpecialPage");
let otherActive = filterGroup.querySelector(".router-link-active");
if(otherActive){
otherActive.classList.remove("router-link-active");
otherActive.classList.remove("router-link-exact-active");
};
document.querySelectorAll(".stats-wrap > div").forEach(module => {
module.style.display = "none";
});
hohStats.style.display = "none";
hohGenres.style.display = "initial";
};
};
function drawListStuff(){
const URLstuff = location.pathname.match(/^\/user\/(.+)\/(animelist|mangalist)/);
if(!URLstuff){
return;
};
if(document.querySelector(".hohExtraFilters")){
return;
};
let filters = document.querySelector(".filters-wrap");
if(!filters){
setTimeout(drawListStuff,200);
return;
};
let extraFilters = create("div","hohExtraFilters");
extraFilters.style.marginTop = "15px";
if(useScripts.draw3x3){
let buttonDraw3x3 = create("span","#hohDraw3x3","3x3",extraFilters);
buttonDraw3x3.title = "Create a 3x3 from 9 selected entries";
buttonDraw3x3.onclick = function(){
this.style.color = "rgb(var(--color-blue))";
let counter = 0;
let linkList = [];
let cardList = document.querySelectorAll(".entry-card.row,.entry.row");
cardList.forEach(function(card){
card.onclick = function(){
if(this.draw3x3selected){
counter--;
linkList[this.draw3x3selected - 1] = "";
this.draw3x3selected = false;
this.style.borderStyle = "none";
}
else{
counter++;
linkList.push(this.querySelector(".cover .image").style.backgroundImage.replace("url(","").replace(")","").replace('"',"").replace('"',""));
this.draw3x3selected = +linkList.length;
this.style.borderStyle = "solid";
if(counter === 9){
linkList = linkList.filter(e => e !== "");
let displayBox = createDisplayBox();
create("p",false,"Save the image below:",displayBox);
displayBox.querySelector(".hohDisplayBoxClose").onclick = function(){
displayBox.remove();
cardList.forEach(function(card){
card.draw3x3selected = false;
card.style.borderStyle = "none";
});
counter = 0;
linkList = [];
};
create("div",false,false,displayBox);
let finalCanvas = create("canvas",false,false,displayBox);
finalCanvas.width = 230*3;
finalCanvas.height = 345*3;
let ctx = finalCanvas.getContext("2d");
let drawStuff = function(image,x,y,width,height){
let img = new Image();
img.onload = function(){
ctx.drawImage(img,x,y,width,height);
}
img.src = image;
};
for(var i=0;i<3;i++){
for(var j=0;j<3;j++){
drawStuff(linkList[i*3+j],j*230,i*345,230,345);
};
};
}
}
};
});
}
}
if(useScripts.newChapters && URLstuff[2] === "mangalist"){
let buttonFindChapters = create("button",["hohButton","button"],"New Chapters",extraFilters,"display:block;");
buttonFindChapters.onclick = function(){
let displayBox = createDisplayBox("min-width:400px;height:500px;");
let loader = create("p",false,"Scanning...",displayBox);
let scrollableContent = create("div",false,false,displayBox);
generalAPIcall(`
query($name: String!){
MediaListCollection(userName: $name, type: MANGA){
lists{
entries{
mediaId
status
media{
status
}
}
}
}
}`,
{name: decodeURIComponent(URLstuff[1])},
function(data){
let list = returnList(data,true).filter(a => a.status === "CURRENT" && a.media.status === "RELEASING");
let returnedItems = 0;
let goodItems = [];
let checkListing = function(data){
returnedItems++;
if(returnedItems === list.length){
loader.innerText = "";
if(!goodItems.length){
loader.innerText = "No new items found :(";
};
};
let guesses = [];
let userIdCache = new Set();
data.data.Page.activities.forEach(function(activity){
if(activity.progress){
let chapterMatch = parseInt(activity.progress.match(/\d+$/)[0]);
if(!userIdCache.has(activity.userId)){
guesses.push(chapterMatch);
userIdCache.add(activity.userId);
};
};
});
guesses.sort(VALUE_DESC);
if(guesses.length){
let bestGuess = guesses[0];
if(guesses.length > 2){
let diff = guesses[0] - guesses[1];
let inverseDiff = 1 + Math.ceil(20/(diff+1));
if(guesses.length >= inverseDiff){
if(guesses[1] === guesses[inverseDiff]){
bestGuess = guesses[1];
}
};
};
if(commonUnfinishedManga.hasOwnProperty(data.data.MediaList.media.id)){
if(bestGuess < commonUnfinishedManga[data.data.MediaList.media.id].chapters){
bestGuess = commonUnfinishedManga[data.data.MediaList.media.id].chapters;
};
};
let bestDiff = bestGuess - data.data.MediaList.progress;
if(bestDiff > 0 && bestDiff < 30){
goodItems.push({data:data,bestGuess:bestGuess});
while(scrollableContent.childElementCount){
scrollableContent.lastChild.remove();
};
goodItems.sort((b,a) => a.data.data.MediaList.score - b.data.data.MediaList.score);
goodItems.forEach(function(item){
let listing = create("p","hohNewChapter",false,scrollableContent);
let title = item.data.data.MediaList.media.title.romaji;
if(useScripts.titleLanguage === "NATIVE" && item.data.data.MediaList.media.title.native){
title = item.data.data.MediaList.media.title.native;
}
else if(useScripts.titleLanguage === "ENGLISH" && item.data.data.MediaList.media.title.english){
title = item.data.data.MediaList.media.title.english;
};
let countPlace = create("span",false,false,listing,"width:110px;display:inline-block;");
let progress = create("span",false,item.data.data.MediaList.progress + " ",countPlace);
let guess = create("span",false,"+" + (item.bestGuess - item.data.data.MediaList.progress),countPlace,"color:rgb(var(--color-green));");
if(useScripts.accessToken){
progress.style.cursor = "pointer";
progress.title = "Increase progress by 1";
progress.onclick = function(){
item.data.data.MediaList.progress++;
authAPIcall(
`mutation($id: Int,$progress: Int){
SaveMediaListEntry(mediaId: $id,progress: $progress){id}
}`,
{
id: item.data.data.MediaList.media.id,
progress: item.data.data.MediaList.progress
},
function(fib){}
);
progress.innerText = item.data.data.MediaList.progress + " ";
if(item.bestGuess - item.data.data.MediaList.progress > 0){
guess.innerText = "+" + (item.bestGuess - item.data.data.MediaList.progress);
}
else{
guess.innerText = "";
}
}
};
create("a",["link","newTab"],title,listing)
.href = "/manga/" + item.data.data.MediaList.media.id + "/" + safeURL(title) + "/";
let chapterClose = create("span","hohDisplayBoxClose",svgAssets.cross,listing);
chapterClose.onclick = function(){
listing.remove();
};
});
}
};
};
let bigQuery = [];
list.forEach(function(entry,index){
bigQuery.push({
query: `
query($id: Int,$userName: String){
Page(page: 1){
activities(
mediaId: $id,
sort: ID_DESC
){
... on ListActivity{
progress
userId
}
}
}
MediaList(
userName: $userName,
mediaId: $id
){
progress
score
media{
id
title{romaji native english}
}
}
}`,
variables: {
id: entry.mediaId,
userName: decodeURIComponent(URLstuff[1])
},
callback: checkListing
});
if((index % 20) === 0){
queryPacker(bigQuery);
bigQuery = [];
};
});
queryPacker(bigQuery);
});
};
};
if(useScripts.tagIndex && (!useScripts.mobileFriendly)){
let tagIndex = create("div",false,false,extraFilters);
let collectNotes = function(data){
let customTags = [];
let listData = returnList(data,true);
listData.forEach(function(entry){
if(entry.notes){
let tagMatches = entry.notes.match(/(#\S+)/g);
if(tagMatches){
for(var j=0;j a.count - b.count);
while(tagIndex.childElementCount){
tagIndex.lastChild.remove();
};
customTags.forEach(function(tag){
let tagElement = create("p",false,tag.name,tagIndex,"cursor:pointer;");
tagElement.onclick = function(){
let filterBox = document.querySelector(".entry-filter input");
filterBox.value = tag.name;
let event = new Event("input");
filterBox.dispatchEvent(event);
};
});
};
let variables = {
name: decodeURIComponent(URLstuff[1]),
listType: "ANIME"
};
if(URLstuff[2] === "mangalist"){
variables.listType = "MANGA";
};
generalAPIcall(queryMediaListNotes,variables,collectNotes,"hohCustomTagIndex" + variables.listType + variables.name,60*1000);
}
filters.appendChild(extraFilters);
let filterBox = document.querySelector(".entry-filter input");
let searchParams = new URLSearchParams(location.search);
let paramSearch = searchParams.get("search");
if(paramSearch){
filterBox.value = decodeURIComponent(paramSearch);
let event = new Event("input");
filterBox.dispatchEvent(event);
}
let filterChange = function(){
let newURL = location.protocol + "//" + location.host + location.pathname
if(filterBox.value === ""){
searchParams.delete("search");
}
else{
searchParams.set("search",encodeURIComponent(filterBox.value));
newURL += "?" + searchParams.toString();
}
current = newURL;
history.replaceState({},"",newURL);
if(document.querySelector(".el-icon-circle-close")){
document.querySelector(".el-icon-circle-close").onclick = filterChange;
}
}
filterBox.oninput = filterChange;
filterChange();
let mutationConfig = {
attributes: false,
childList: true,
subtree: true
};
if(
decodeURIComponent(URLstuff[1]) === whoAmI
&& useScripts.accessToken
&& useScripts.plussMinus
&& (
document.querySelector(".medialist").classList.contains("POINT_100")
|| document.querySelector(".medialist").classList.contains("POINT_10")
|| document.querySelector(".medialist").classList.contains("POINT_10_DECIMAL")
)
){
let minScore = 1;
let maxScore = 100;
let stepSize = 1;
if(document.querySelector(".medialist").classList.contains("POINT_10") || document.querySelector(".medialist").classList.contains("POINT_10_DECIMAL")){
maxScore = 10;
}
if(document.querySelector(".medialist").classList.contains("POINT_10_DECIMAL")){
stepSize = 0.1;
}
let scoreChanger = function(){
observer.disconnect();
lists.querySelectorAll(".list-entries .row .score").forEach(function(entry){
if(!entry.childElementCount){
let updateScore = function(isUp){
let score = parseFloat(entry.attributes.score.value);
if(isUp){
score += stepSize;
}
else{
score -= stepSize;
}
if(score >= minScore && score <= maxScore){
let id = parseInt(entry.previousElementSibling.children[0].href.match(/(anime|manga)\/(\d+)/)[2]);
lists.querySelectorAll("[href=\"" + entry.previousElementSibling.children[0].attributes.href.value + "\"]").forEach(function(rItem){
rItem.parentNode.nextElementSibling.attributes.score.value = score.roundPlaces(1);
rItem.parentNode.nextElementSibling.childNodes[1].textContent = " " + score.roundPlaces(1) + " ";
});
authAPIcall(
`mutation($id:Int,$score:Float){
SaveMediaListEntry(mediaId:$id,score:$score){
score
}
}`,
{id:id,score:score},function(data){/*later*/}
);
};
};
let changeMinus = create("span","hohChangeScore","-");
entry.insertBefore(changeMinus,entry.firstChild);
let changePluss = create("span","hohChangeScore","+",entry);
changeMinus.onclick = function(){updateScore(false)};
changePluss.onclick = function(){updateScore(true)};
}
});
observer.observe(lists,mutationConfig);
}
let lists = document.querySelector(".lists");
let observer = new MutationObserver(scoreChanger);
observer.observe(lists,mutationConfig);
scoreChanger();
}
};
function addDblclickZoom(){
if(!location.pathname.match(/^\/home\/?$/)){
return;
};
let activityFeedWrap = document.querySelector(".activity-feed-wrap");
if(!activityFeedWrap){
setTimeout(addDblclickZoom,200);
return;
};
activityFeedWrap.addEventListener("dblclick",function(e){
e = e || window.event;
let target = e.target || e.srcElement;
while(target.classList){
if(target.classList.contains("activity-entry")){
target.classList.toggle("hohZoom");
break;
};
target = target.parentNode;
}
},false);
}
function addFeedFilters(){
if(!location.pathname.match(/^\/home\/?$/)){
return;
};
let filterBox = document.querySelector(".hohFeedFilter");
if(filterBox){
return;
};
let activityFeedWrap = document.querySelector(".activity-feed-wrap");
if(!activityFeedWrap){
setTimeout(addFeedFilters,100);
return;
};
let activityFeed = activityFeedWrap.querySelector(".activity-feed");
if(!activityFeed){
setTimeout(addFeedFilters,100);
return;
};
let commentFilterBoxInput;
let commentFilterBoxLabel;
let likeFilterBoxInput;
let likeFilterBoxLabel;
let allFilterBox;
let blockList = localStorage.getItem("blockList");
if(blockList){
blockList = JSON.parse(blockList);
}
else{
blockList = [];
};
let postRemover = function(){
if(!location.pathname.match(/^\/home\/?$/)){
return;
};
let duplicates = new Set();
for(var i=0;i a.action").href;
let blockRequire = true;
if(useScripts.blockWord && activityFeed.children[i].classList.contains("activity-text")){
try{
if(activityFeed.children[i].innerText.match(new RegExp(blockWordValue,"i"))){
blockRequire = false;
}
}
catch(err){
if(activityFeed.children[i].innerText.toLowerCase().match(useScripts.blockWordValue.toLowerCase())){
blockRequire = false;
}
}
}
if(useScripts.statusBorder){
if(activityFeed.children[i].classList.contains("activity-anime_list") || activityFeed.children[i].classList.contains("activity-manga_list")){
let blockerMap = {
"plans": "PLANNING",
"watched": "CURRENT",
"read": "CURRENT",
"completed": "COMPLETED",
"paused": "PAUSED",
"dropped": "DROPPED",
"rewatched": "REPEATING",
"reread": "REPEATING"
};
let status = blockerMap[
Object.keys(blockerMap).find(
key => activityFeed.children[i].querySelector(".status").innerText.includes(key)
)
]
if(status === "CURRENT"){
activityFeed.children[i].style.borderRightWidth = "0px";
//nothing
}
else if(status === "COMPLETED"){
activityFeed.children[i].style.borderRightStyle = "solid";
activityFeed.children[i].style.borderRightWidth = "5px";
if(useScripts.CSSgreenManga && activityFeed.children[i].classList.contains("activity-anime_list")){
activityFeed.children[i].style.borderRightColor = "rgb(var(--color-blue))";
}
else{
activityFeed.children[i].style.borderRightColor = "rgb(var(--color-green))";
}
}
else{
activityFeed.children[i].style.borderRightStyle = "solid";
activityFeed.children[i].style.borderRightWidth = "5px";
activityFeed.children[i].style.borderRightColor = distributionColours[status];
}
}
}
if(
(!useScripts.feedCommentFilter || (
actionLikes >= likeFilterBoxInput.value
&& (likeFilterBoxInput.value >= 0 || actionLikes < -likeFilterBoxInput.value)
&& actionReplies >= commentFilterBoxInput.value
&& (commentFilterBoxInput.value >= 0 || actionReplies < -commentFilterBoxInput.value)
))
&& !duplicates.has(actionHref)
&& blockRequire
&& blockList.every(function(blocker){
if(blocker.user){
if(activityFeed.children[i].querySelector(".name").innerText.toLowerCase() !== blocker.user.toLowerCase()){
return true;
}
};
if(blocker.media){
if(activityFeed.children[i].classList.contains("activity-text")){
return true;
}
else{
let titleId = activityFeed.children[i].querySelector(".status .title").href.match(/\/(anime|manga)\/(\d+)/)[2];
if(titleId !== blocker.media){
return true;
}
}
};
if(blocker.status){
if(activityFeed.children[i].classList.contains("activity-text")){
return true;
}
else if(blocker.status === "status"){
return true;
}
else if(blocker.status === "anime"){
if(!activityFeed.children[i].classList.contains("activity-anime_list")){
return true;
}
}
else if(blocker.status === "manga"){
if(!activityFeed.children[i].classList.contains("activity-manga_list")){
return true;
}
}
else if(blocker.status === "planning"){
if(!activityFeed.children[i].querySelector(".status").innerText.match(/^plans/)){
return true;
}
}
else if(blocker.status === "watching"){
if(!activityFeed.children[i].querySelector(".status").innerText.match(/^watched/)){
return true;
}
}
else if(blocker.status === "reading"){
if(!activityFeed.children[i].querySelector(".status").innerText.match(/^read/)){
return true;
}
}
else if(blocker.status === "completing"){
if(!activityFeed.children[i].querySelector(".status").innerText.match(/^completed/)){
return true;
}
}
else if(blocker.status === "pausing"){
if(!activityFeed.children[i].querySelector(".status").innerText.match(/^paused/)){
return true;
}
}
else if(blocker.status === "dropping"){
if(!activityFeed.children[i].querySelector(".status").innerText.match(/^dropped/)){
return true;
}
}
else if(blocker.status === "rewatching"){
if(!activityFeed.children[i].querySelector(".status").innerText.match(/^rewatched/)){
return true;
}
}
else if(blocker.status === "rereading"){
if(!activityFeed.children[i].querySelector(".status").innerText.match(/^reread/)){
return true;
}
}
};
return false;
})
){
if(
useScripts.SFWmode
&& activityFeed.children[i].classList.contains("activity-text")
&& badWords.some(word => activityFeed.children[i].querySelector(".activity-markdown").innerText.match(word))
){
activityFeed.children[i].style.opacity= 0.5;
}
else{
activityFeed.children[i].style.display = "";
}
}
else{
activityFeed.children[i].style.display = "none";
};
duplicates.add(actionHref);
};
};
if(useScripts.feedCommentFilter){
filterBox = create("div","hohFeedFilter",false,activityFeedWrap);
create("span","hohDescription","At least ",filterBox);
activityFeedWrap.style.position = "relative";
activityFeedWrap.children[0].childNodes[0].nodeValue = "";
commentFilterBoxInput = create("input",false,false,filterBox);
commentFilterBoxInput.type = "number";
commentFilterBoxInput.value = useScripts.feedCommentComments;
commentFilterBoxLabel = create("span",false," comments, ",filterBox);
likeFilterBoxInput = create("input",false,false,filterBox);
likeFilterBoxInput.type = "number";
likeFilterBoxInput.value = useScripts.feedCommentLikes;
likeFilterBoxLabel = create("span",false," likes",filterBox);
allFilterBox = create("button",false,"⟳",filterBox,"padding:0px;");
commentFilterBoxInput.onchange = function(){
useScripts.feedCommentComments = commentFilterBoxInput.value;
useScripts.save();
postRemover();
};
likeFilterBoxInput.onchange = function(){
useScripts.feedCommentLikes = likeFilterBoxInput.value;
useScripts.save();
postRemover();
};
allFilterBox.onclick = function(){
commentFilterBoxInput.value = 0;
likeFilterBoxInput.value = 0;
useScripts.feedCommentComments = 0;
useScripts.feedCommentLikes = 0;
useScripts.save();
postRemover();
};
}
let mutationConfig = {
attributes: false,
childList: true,
subtree: false
};
let observer = new MutationObserver(function(){
postRemover();setTimeout(postRemover,500);
});
observer.observe(activityFeed,mutationConfig);
let observerObserver = new MutationObserver(function(){//Who police police? The police police police police
activityFeed = activityFeedWrap.querySelector(".activity-feed");
if(activityFeed){
observer.disconnect();
observer = new MutationObserver(function(){
postRemover();setTimeout(postRemover,500);
});
observer.observe(activityFeed,mutationConfig);
}
});
observerObserver.observe(activityFeedWrap,mutationConfig);
postRemover();
let waiter = function(){
setTimeout(function(){
if(location.pathname.match(/^\/home\/?$/)){
postRemover();
waiter();
};
},10000);
};waiter();
};
function expandRight(){
if(!location.pathname.match(/^\/home\/?$/)){
return;
};
let possibleFullWidth = document.querySelector(".home.full-width");
if(possibleFullWidth){
let homeContainer = possibleFullWidth.parentNode;
let sideBar = document.querySelector(".activity-feed-wrap")
if(!sideBar){
setTimeout(expandRight,100);
return;
};
sideBar = sideBar.nextElementSibling;
sideBar.insertBefore(possibleFullWidth,sideBar.firstChild);
let setSemantics = function(){
let toggle = document.querySelector(".size-toggle.fa-compress");
if(toggle){
toggle.onclick = function(){
homeContainer.insertBefore(possibleFullWidth,homeContainer.firstChild);
};
}
else{
setTimeout(setSemantics,200);
};
};setSemantics();
}
}
function mangaGuess(cleanAnime){
if(cleanAnime){
let possibleMangaGuess = document.querySelector(".data-set .value[data-media-id]");
if(possibleMangaGuess){
while(possibleMangaGuess.children.length){
possibleMangaGuess.lastChild.remove();
};
};
return;
};
let URLstuff = location.pathname.match(/^\/manga\/(\d+)\/?(.*)?/);
if(!URLstuff){
return;
};
let possibleReleaseStatus = Array.from(
document.querySelectorAll(".data-set .value")
).find(
element => element.innerText.match(/^Releasing/)
);
if(!possibleReleaseStatus){
setTimeout(mangaGuess,200);
return;
}
if(possibleReleaseStatus.dataset.mediaId === URLstuff[1]){
if(possibleReleaseStatus.children.length !== 0){
return;
}
}
else{
while(possibleReleaseStatus.children.length){
possibleReleaseStatus.lastChild.remove()
};
};
possibleReleaseStatus.dataset.mediaId = URLstuff[1];
const variables = {id: parseInt(URLstuff[1]),userName: whoAmI};
let query = `
query($id: Int,$userName: String){
Page(page: 1){
activities(
mediaId: $id,
sort: ID_DESC
){
... on ListActivity{
progress
userId
}
}
}
MediaList(
userName: $userName,
mediaId: $id
){
progress
}
}`;
let possibleMyStatus = document.querySelector(".actions .list .add");
const simpleQuery = !possibleMyStatus || possibleMyStatus.innerText === "Add to List" || possibleMyStatus.innerText === "Planning";
if(simpleQuery){
query = `
query($id: Int){
Page(page: 1){
activities(
mediaId: $id,
sort: ID_DESC
){
... on ListActivity{
progress
userId
}
}
}
}`;
};
let highestChapterFinder = function(data){
if(possibleReleaseStatus.children.length !== 0){
return;
}
let guesses = [];
let userIdCache = new Set();
data.data.Page.activities.forEach(function(activity){
if(activity.progress){
let chapterMatch = parseInt(activity.progress.match(/\d+$/)[0]);
if(!userIdCache.has(activity.userId)){
guesses.push(chapterMatch);
userIdCache.add(activity.userId);
};
};
});
guesses.sort(VALUE_DESC);
if(guesses.length){
let bestGuess = guesses[0];
if(guesses.length > 2){
let diff = guesses[0] - guesses[1];
let inverseDiff = 1 + Math.ceil(25/(diff+1));
if(guesses.length >= inverseDiff){
if(guesses[1] === guesses[inverseDiff]){
bestGuess = guesses[1];
};
};
};
if(commonUnfinishedManga.hasOwnProperty(variables.id)){
if(bestGuess < commonUnfinishedManga[variables.id].chapters){
bestGuess = commonUnfinishedManga[variables.id].chapters;
};
};
if(simpleQuery){
if(bestGuess){
create("span","hohGuess"," (" + bestGuess + "?)",possibleReleaseStatus);
}
}
else{
bestGuess = Math.max(bestGuess,data.data.MediaList.progress);
if(bestGuess){
if(bestGuess === data.data.MediaList.progress){
create("span","hohGuess"," (" + bestGuess + "?)",possibleReleaseStatus,"color:rgb(var(--color-green));");
}
else{
create("span","hohGuess"," (" + bestGuess + "?)",possibleReleaseStatus);
create("span","hohGuess"," [+" + (bestGuess - data.data.MediaList.progress) + "]",possibleReleaseStatus,"color:rgb(var(--color-red));");
}
}
};
};
};
try{
generalAPIcall(query,variables,highestChapterFinder,"hohMangaGuess" + variables.id,30*60*1000);
}
catch(e){
sessionStorage.removeItem("hohMangaGuess" + variables.id);
}
}
if(useScripts.ALbuttonReload){
let logo = document.querySelector(".logo");
if(logo){
logo.onclick = function(){
if(location.pathname.match(/\/home\/?$/)){//we only want this behaviour here
window.location.reload(false);//reload page, but use cache if possible
}
}
}
}
function enumerateSubmissionStaff(){
if(!location.pathname.match(/^\/edit/)){
return;
};
setTimeout(enumerateSubmissionStaff(),500);
let staffFound = [];
let staffEntries = document.querySelectorAll(".staff-row .col > .image");
Array.from(staffEntries).forEach(function(staff){
let enumerate = staffFound.filter(a => a === staff.href).length;
if(enumerate === 1){
let firstStaff = document.querySelector(".staff-row .col > .image[href=\"" + staff.href.replace("https://anilist.co","") + "\"]");
if(!firstStaff.previousSibling){
firstStaff.parentNode.insertBefore(
create("span","hohEnumerateStaff",1),
firstStaff
)
};
}
if(enumerate > 0){
if(staff.previousSibling){
staff.previousSibling.innerText = enumerate + 1;
}
else{
staff.parentNode.insertBefore(
create("span","hohEnumerateStaff",(enumerate + 1)),
staff
)
}
};
staffFound.push(staff.href);
});
}
function addMALscore(type,id){
if(!location.pathname.match(/^\/(anime|manga)/)){
return;
};
let MALscore = document.getElementById("hohMALscore");
if(MALscore){
if(parseInt(MALscore.dataset.id) === id){
return;
}
else{
MALscore.remove();
}
};
let MALserial = document.getElementById("hohMALserialization");
if(MALserial){
if(parseInt(MALserial.dataset.id) === id){
return;
}
else{
MALserial.remove();
}
};
let possibleReleaseStatus = Array.from(document.querySelectorAll(".data-set .type"));
const MALlocation = possibleReleaseStatus.find(element => element.innerText === "Mean Score");
if(MALlocation){
MALscore = create("div","data-set");
MALscore.id = "hohMALscore";
MALscore.dataset.id = id;
MALlocation.parentNode.parentNode.insertBefore(MALscore,MALlocation.parentNode.nextSibling);
if(type === "manga"){
MALserial = create("div","data-set");
MALserial.id = "hohMALserialization";
MALserial.dataset.id = id;
MALlocation.parentNode.parentNode.insertBefore(MALserial,MALlocation.parentNode.nextSibling.nextSibling);
}
generalAPIcall("query($id:Int){Media(id:$id){idMal}}",{id:id},function(data){
if(data.data.Media.idMal){
let handler = function(response){
let score = response.responseText.match(/ratingValue.+?(\d+\.\d+)/);
if(score && useScripts.MALscore){
MALscore.style.paddingBottom = "14px";
create("a",["type","newTab","external"],"MAL Score",MALscore)
.href = "https://myanimelist.net/" + type + "/" + data.data.Media.idMal;
create("div","value",score[1],MALscore);
}
if(type === "manga" && useScripts.MALserial){
let serialization = response.responseText.match(/Serialization:<\/span>\n.*?href="(.*?)"\stitle="(.*?)"/);
if(serialization){
MALserial.style.paddingBottom = "14px";
create("div","type","Serialization",MALserial);
let link = create("a",["value","newTab","external"],serialization[2],MALserial)
link.href = "https://myanimelist.net" + serialization[1];
}
}
let adder = function(){
let possibleOverview = document.querySelector(".overview .grid-section-wrap:last-child");
if(!possibleOverview){
setTimeout(adder,500);
return;
}
(possibleOverview.querySelector(".hohRecContainer") || {remove: ()=>{}}).remove();
let recContainer = create("div",["grid-section-wrap","hohRecContainer"],false,possibleOverview);
create("h2",false,"MAL recs",recContainer);
let pattern = /class="picSurround">(.*?)<\/div>/g;
let matching = [];
let matchingItem;
while((matchingItem = pattern.exec(response.responseText)) && matching.length < 5){//single "=" is intended, we are setting the value of each match, not comparing
matching.push(matchingItem)
}
if(!matching.length){
recContainer.style.display = "none"
}
matching.forEach(function(item){
let idMal = item[2];
let description = item[4];
let rec = create("div","hohRec",false,recContainer);
let recImage = create("a","hohBackgroundCover",false,rec,"border-radius: 3px;");
let recTitle = create("a","title",false,rec,"position:absolute;top:35px;left:80px;color:rgb(var(--color-blue));");
recTitle.innerText = "MAL ID " + idMal;
let recDescription = create("p",false,false,rec,"font-size: 1.4rem;line-height: 1.5;");
recDescription.innerHTML = description;
generalAPIcall("query($idMal:Int,$type:MediaType){Media(idMal:$idMal,type:$type){id title{romaji native english} coverImage{large color} siteUrl}}",{idMal:idMal,type:item[1].toUpperCase()},function(data){
if(!data){
return;
};
recImage.style.backgroundColor = data.data.Media.coverImage.color || "rgb(var(--color-foreground))";
recImage.style.backgroundImage = "url(\"" + data.data.Media.coverImage.large + "\")";
recImage.href = data.data.Media.siteUrl;
if(useScripts.titleLanguage === "NATIVE" && data.data.Media.title.native){
recTitle.innerText = data.data.Media.title.native;
}
else if(useScripts.titleLanguage === "ENGLISH" && data.data.Media.title.english){
recTitle.innerText = data.data.Media.title.english;
}
else{
recTitle.innerText = data.data.Media.title.romaji;
}
recTitle.href = data.data.Media.siteUrl;
},"hohIDmalReverse" + idMal);
})
};
if(useScripts.MALrecs){
adder()
}
}
if(window.GM_xmlhttpRequest){
GM_xmlhttpRequest({
method: "GET",
anonymous: true,
url: "https://myanimelist.net/" + type + "/" + data.data.Media.idMal + "/placeholder/userrecs",
onload: function(response){handler(response)}
})
}
else{
let oReq = new XMLHttpRequest();
oReq.addEventListener("load",function(){handler(this)});
oReq.open("GET","https://myanimelist.net/" + type + "/" + data.data.Media.idMal + "/placeholder/userrecs");
oReq.send();
}
}
},"hohIDmal" + id);
}
else{
setTimeout(() => {addMALscore(type,id)},200)
}
}
function cencorMediaPage(id){
if(!location.pathname.match(/^\/(anime|manga)/)){
return
};
let possibleLocation = document.querySelectorAll(".tags .tag .name");
if(possibleLocation.length){
if(possibleLocation.some(
tag => badTags.some(
bad => tag.innerText.toLowerCase().includes(bad)
)
)){
let content = document.querySelector(".page-content");
if(content){
content.classList.add("hohCencor")
}
}
}
else{
setTimeout(() => {cencorMediaPage(id)},200)
}
}
function addEntryScore(id,tries){
if(!location.pathname.match(/^\/(anime|manga)/)){
return
};
let existing = document.getElementById("hohEntryScore");
if(existing){
if(existing.dataset.mediaId === id && !tries){
return
}
else{
existing.remove()
}
};
let possibleLocation = document.querySelector(".actions .list .add");
if(possibleLocation){
let miniHolder = create("div","#hohEntryScore",false,possibleLocation.parentNode.parentNode,"position:relative;");
miniHolder.dataset.mediaId = id;
let type = possibleLocation.innerText;
if(type === "Reading" || type === "Completed" || type === "Watching" || type === "Paused" || type === "Repeating" || type === "Dropped"){
generalAPIcall(
"query($id:Int,$name:String){MediaList(mediaId:$id,userName:$name){score progress}}",
{id: id,name: whoAmI},
function(data){
let MediaList = data.data.MediaList;
let scoreSpanContainer = create("div","hohMediaScore",false,miniHolder);
let scoreSpan = create("span",false,false,scoreSpanContainer);
let minScore = 1;
let maxScore = 100;
let stepSize = 1;
if(["POINT_10","POINT_10_DECIMAL"].includes(userObject.mediaListOptions.scoreFormat)){
maxScore = 10
}
if(userObject.mediaListOptions.scoreFormat === "POINT_10_DECIMAL"){
stepSize = 0.1
}
if(MediaList.score){
scoreSpan.innerHTML = scoreFormatter(MediaList.score,userObject.mediaListOptions.scoreFormat,whoAmI);
if(useScripts.accessToken && ["POINT_100","POINT_10","POINT_10_DECIMAL"].includes(userObject.mediaListOptions.scoreFormat)){
let updateScore = function(isUp){
let score = MediaList.score;
if(isUp){
MediaList.score += stepSize
}
else{
MediaList.score -= stepSize
}
if(MediaList.score >= minScore && MediaList.score <= maxScore){
scoreSpan.innerHTML = scoreFormatter(MediaList.score,userObject.mediaListOptions.scoreFormat,whoAmI);
authAPIcall(
`mutation($id:Int,$score:Float){
SaveMediaListEntry(mediaId:$id,score:$score){
score
}
}`,
{id: id,score: MediaList.score},
data => {}
);
let blockingCache = JSON.parse(sessionStorage.getItem("hohEntryScore" + id + whoAmI));
blockingCache.data.data.MediaList.score = MediaList.score.roundPlaces(1);
blockingCache.time = NOW();
sessionStorage.setItem("hohEntryScore" + id + whoAmI,JSON.stringify(blockingCache));
}
else if(MediaList.score < minScore){
MediaList.score = minScore
}
else if(MediaList.score > maxScore){
MediaList.score = maxScore
}
};
let changeMinus = create("span","hohChangeScore","-",false,"padding:2px;position:absolute;left:-1px;top:-2.5px;");
scoreSpanContainer.insertBefore(changeMinus,scoreSpanContainer.firstChild);
let changePluss = create("span","hohChangeScore","+",scoreSpanContainer,"padding:2px;");
changeMinus.onclick = function(){updateScore(false)};
changePluss.onclick = function(){updateScore(true)};
}
};
if(type !== "Completed"){
let progressPlace = create("span","hohMediaScore",false,miniHolder,"right:0px;");
let progressVal = create("span",false,MediaList.progress,progressPlace);
if(useScripts.accessToken){
let changePluss = create("span","hohChangeScore","+",progressPlace,"padding:2px;position:absolute;top:-2.5px;");
changePluss.onclick = function(){
MediaList.progress++;
authAPIcall(
`mutation($id:Int,$progress:Int){
SaveMediaListEntry(mediaId:$id,progress:$progress){
progress
}
}`,
{id: id,progress: MediaList.progress},
data => {}
);
progressVal.innerText = MediaList.progress;
};
}
};
},
"hohEntryScore" + id + whoAmI,30*1000
);
}
else if(type === "Add to List" && (tries || 0) < 10){
setTimeout(function(){addEntryScore(id,(tries || 0) + 1)},200);
}
}
else{
setTimeout(function(){addEntryScore(id)},200);
}
}
function notificationCake(){
let notificationDot = document.querySelector(".notification-dot");
if(notificationDot && (!notificationDot.childElementCount)){
authAPIcall(
queryAuthNotifications,
{page:1,name:whoAmI},
function(data){
let Page = data.data.Page;
let User = data.data.User;
let types = [];
let names = [];
for(var i=0;i",false,"font-weight:bolder;");
timeContainer.insertBefore(codeLink,timeContainer.firstChild);
codeLink.onclick = function(){
let activityMarkdown = document.querySelector(".activity-markdown");
if(activityMarkdown.style.display === "none"){
document.querySelector(".hohMarkdownSource").style.display = "none";
activityMarkdown.style.display = "initial";
}
else{
activityMarkdown.style.display = "none";
let markdownSource = document.querySelector(".hohMarkdownSource");
if(markdownSource){
markdownSource.style.display = "initial";
}
else{
generalAPIcall("query($id:Int){Activity(id:$id){...on MessageActivity{text:message}...on TextActivity{text}}}",{id:id},function(data){
if(!location.pathname.match(id) || !data){
return;
};
markdownSource = create("div",["activity-markdown","hohMarkdownSource"],data.data.Activity.text,activityMarkdown.parentNode);
},"hohGetMarkdown" + id,20*1000);
}
}
}
}
function addActivityLinks(activityID){
let arrowCallback = function(data){
let adder = function(link){
if(!location.pathname.includes("/activity/" + activityID)){
return;
};
let activityLocation = document.querySelector(".activity-entry");
if(activityLocation){
activityLocation.appendChild(link);
return;
}
else{
setTimeout(function(){adder(link)},200);
}
};
let queryPrevious;
let queryNext;
let variables = {
userId: data.data.Activity.userId || data.data.Activity.recipientId,
createdAt: data.data.Activity.createdAt
};
if(data.data.Activity.type === "ANIME_LIST" || data.data.Activity.type === "MANGA_LIST"){
variables.mediaId = data.data.Activity.media.id;
queryPrevious = `
query ($userId: Int,$mediaId: Int,$createdAt: Int){
Activity(
userId: $userId,
mediaId: $mediaId,
createdAt_lesser: $createdAt,
sort: ID_DESC
){
... on ListActivity{siteUrl createdAt id}
}
}`;
queryNext = `
query($userId: Int,$mediaId: Int,$createdAt: Int){
Activity(
userId: $userId,
mediaId: $mediaId,
createdAt_greater: $createdAt,
sort: ID
){
... on ListActivity{siteUrl createdAt id}
}
}`;
}
else if(data.data.Activity.type === "TEXT"){
queryPrevious = `
query($userId: Int,$createdAt: Int){
Activity(
userId: $userId,
type: TEXT,
createdAt_lesser: $createdAt,
sort: ID_DESC
){
... on TextActivity{siteUrl createdAt id}
}
}`;
queryNext = `
query($userId: Int,$createdAt: Int){
Activity(
userId: $userId,
type: TEXT,
createdAt_greater: $createdAt,
sort: ID
){
... on TextActivity{siteUrl createdAt id}
}
}`;
}
else if(data.data.Activity.type === "MESSAGE"){
let link = create("a","hohPostLink","↑",false,"left:-25px;top:25px;");
link.href = "/user/" + data.data.Activity.recipient.name + "/";
link.title = data.data.Activity.recipient.name + "'s profile";
adder(link);
variables.messengerId = data.data.Activity.messengerId;
queryPrevious = `
query($userId: Int,$messengerId: Int,$createdAt: Int){
Activity(
userId: $userId,
type: MESSAGE,
messengerId: $messengerId,
createdAt_lesser: $createdAt,
sort: ID_DESC
){
... on MessageActivity{siteUrl createdAt id}
}
}`;
queryNext = `
query($userId: Int,$messengerId: Int,$createdAt: Int){
Activity(
userId: $userId,
type: MESSAGE,
messengerId: $messengerId,
createdAt_greater: $createdAt,
sort: ID
){
... on MessageActivity{siteUrl createdAt id}
}
}`;
}
else{//unknown new types of activities
return;
};
if(data.previous){
if(data.previous !== "FIRST"){
let link = create("a","hohPostLink","←",false,"left:-25px;");
link.href = data.previous;
link.rel = "prev";
link.title = "Previous activity";
adder(link);
}
}
else{
data.previous = "FIRST";
generalAPIcall(queryPrevious,variables,function(pdata){
if(!pdata){
return;
}
let link = create("a","hohPostLink","←",false,"left:-25px;");
link.title = "Previous activity";
link.rel = "prev";
link.href = pdata.data.Activity.siteUrl;
adder(link);
data.previous = pdata.data.Activity.siteUrl;
sessionStorage.setItem("hohActivity" + activityID,JSON.stringify(data));
pdata.data.Activity.type = data.data.Activity.type;
pdata.data.Activity.userId = variables.userId;
pdata.data.Activity.media = data.data.Activity.media;
pdata.data.Activity.messengerId = data.data.Activity.messengerId;
pdata.data.Activity.recipientId = data.data.Activity.recipientId;
pdata.data.Activity.recipient = data.data.Activity.recipient;
pdata.next = document.URL;
sessionStorage.setItem("hohActivity" + pdata.data.Activity.id,JSON.stringify(pdata));
});
}
if(data.next){
let link = create("a","hohPostLink","→",false,"right:-25px;");
link.href = data.next;
link.rel = "next";
link.title = "Next activity";
adder(link);
}
else{
generalAPIcall(queryNext,variables,function(pdata){
if(!pdata){
return;
}
let link = create("a","hohPostLink","→",false,"right:-25px;");
link.href = pdata.data.Activity.siteUrl;
link.rel = "next";
link.title = "Next activity";
adder(link);
data.next = pdata.data.Activity.siteUrl;
sessionStorage.setItem("hohActivity" + activityID,JSON.stringify(data));
pdata.data.Activity.type = data.data.Activity.type;
pdata.data.Activity.userId = variables.userId;
pdata.data.Activity.media = data.data.Activity.media;
pdata.data.Activity.messengerId = data.data.Activity.messengerId;
pdata.data.Activity.recipientId = data.data.Activity.recipientId;
pdata.data.Activity.recipient = data.data.Activity.recipient;
pdata.previous = document.URL;
sessionStorage.setItem("hohActivity" + pdata.data.Activity.id,JSON.stringify(pdata));
});
};
sessionStorage.setItem("hohActivity" + activityID,JSON.stringify(data));
}
let possibleCache = sessionStorage.getItem("hohActivity" + activityID);
if(possibleCache){
arrowCallback(JSON.parse(possibleCache));
}
else{
generalAPIcall(`
query($id: Int){
Activity(id: $id){
... on ListActivity{
type
userId
createdAt
media{id}
}
... on TextActivity{
type
userId
createdAt
}
... on MessageActivity{
type
recipientId
recipient{name}
messengerId
createdAt
}
}
}`,{id:activityID},arrowCallback);
}
}
function addBrowseFilters(type){
if(!location.pathname.match(/^\/search/)){
return;
};
let sorts = document.querySelector(".hohAlready");
if(!sorts){
sorts = document.querySelector(".filter-group .el-select-dropdown .el-select-dropdown__list");
if(!sorts){
setTimeout(function(){addBrowseFilters(type)},200);
return;
};
sorts.classList.add("hohAlready");
};
let alreadyAdded = document.querySelectorAll(".hohSorts");
alreadyAdded.forEach(function(already){
already.remove();
});
let URLredirect = function(property,value){
let url = new URLSearchParams(location.search);
url.set(property,value);
window.location.href = location.protocol + "//" + location.host + location.pathname + "?" + url.toString();
};
if(type === "anime"){
let episodeSort = create("li",["el-select-dropdown__item","hohSorts"],false,sorts);
create("span",false,"Episodes ↓",episodeSort);
let episodeSortb = create("li",["el-select-dropdown__item","hohSorts"],false,sorts);
create("span",false,"Episodes ↑",episodeSortb);
for(var i=0;i user.name).join(",") + "\n";
shows.forEach(function(show){
let display = users.every(function(user,index){
if(user.demand === 1 && show.score[index] === 0){
return false;
}
else if(user.demand === -1 && show.score[index] !== 0){
return false;
};
return (!user.status || show.status[index] === user.status);
});
if(formatFilter.value !== "all"){
if(formatFilter.value !== show.format){
display = false;
};
};
if(show.numberWatched < ratingFilter.value){
display = false;
};
if(!display){
return;
};
csvContent += "\"" + show.title.replace(/"/g,"\"\"") + "\"," + show.digest + "," + show.score.join(",") + "\n";
});
let filename = capitalize(type) + " table";
if(users.length === 1){
filename += " for " + users[0].name;
}
else if(users.length === 2){
filename += " for " + users[0].name + " and " + users[1].name;
}
else if(users.length > 2){
filename += " for " + users[0].name + ", " + users[1].name + " and others";
}
filename += ".csv";
saveAs(csvContent,filename,true);
};
jsonButton.onclick = function(){
let jsonData = {
users: users,
formatFilter: formatFilter.value,
digestValue: digestSelect.value,
type: capitalize(type),
version: "1.00",
scriptInfo: scriptInfo,
url: document.URL,
timeStamp: NOW(),
media: shows
}
let filename = capitalize(type) + " table";
if(users.length === 1){
filename += " for " + users[0].name;
}
else if(users.length === 2){
filename += " for " + users[0].name + " and " + users[1].name;
}
else if(users.length > 2){
filename += " for " + users[0].name + ", " + users[1].name + " and others";
}
filename += ".json";
saveAs(jsonData,filename);
}
let sortShows = function(){
let averageCalc = function(scoreArray,weight){
let sum = 0;
let dividents = 0;
scoreArray.forEach(function(score){
if(score){
sum += score;
dividents++;
};
});
return {
average: ((dividents + (weight || 0)) ? (sum/(dividents + (weight || 0))) : 0),
dividents: dividents
};
};
let sortingModes = {
"average": function(show){
show.digest = averageCalc(show.score).average;
},
"average0": function(show){
show.digest = averageCalc(show.score,1).average;
},
"standardDeviation": function(show){
let average = averageCalc(show.score);
let variance = 0;
show.digest = 0;
if(average.dividents){
show.score.forEach(function(score){
if(score){
variance += Math.pow(score - average.average,2);
};
});
variance = variance/average.dividents;
show.digest = Math.sqrt(variance);
};
},
"absoluteDeviation": function(show){
let average = averageCalc(show.score);
let variance = 0;
show.digest = 0;
if(average.dividents){
show.score.forEach(function(score){
if(score){
variance += Math.abs(score - average.average);
};
});
variance = variance/average.dividents;
show.digest = Math.sqrt(variance);
};
},
"max": function(show){
show.digest = Math.max(...show.score);
},
"min": function(show){
show.digest = Math.min(...show.score.filter(TRUTHY)) || 0;
},
"difference": function(show){
let mini = Math.min(...show.score.filter(TRUTHY)) || 0;
let maks = Math.max(...show.score);
show.digest = maks - mini;
},
"ratings": function(show){
show.digest = show.score.filter(TRUTHY).length;
},
"planned": function(show){
show.digest = show.status.filter(value => value === "PLANNING").length;
},
"current": function(show){
show.digest = show.status.filter(value => (value === "CURRENT" || value === "REPEATING")).length;
},
"favourites": function(show){
show.digest = show.favourite.filter(TRUTHY).length;
},
"median": function(show){
let newScores = show.score.filter(TRUTHY);
if(newScores.length === 0){
show.digest = 0;
}
else{
show.digest = Stats.median(newScores);
};
},
"popularity": function(show){
show.digest = show.popularity;
},
"averageScore": function(show){
show.digest = show.averageScore;
},
"averageScoreDiff": function(show){
if(!show.averageScore){
show.digest = 0;
return;
};
show.digest = averageCalc(show.score).average - show.averageScore;
}
};
if(ratingMode === "user"){
shows.sort(function(a,b){
return b.score[guser] - a.score[guser];
});
}
else if(ratingMode === "userInverse"){
shows.sort(function(b,a){
return b.score[guser] - a.score[guser];
});
}
else if(ratingMode === "title"){
shows.sort(ALPHABETICAL(a => a.title));
}
else if(ratingMode === "titleInverse"){
shows = shows.sort(ALPHABETICAL(a => a.title)).reverse();
}
else{
shows.forEach(sortingModes[ratingMode]);
if(inverse){
shows.sort((b,a) => b.digest - a.digest);
}
else{
shows.sort((a,b) => b.digest - a.digest);
}
};
};
let drawTable = function(){
while(table.childElementCount > 2){
table.lastChild.remove();
};
let columnAmounts = [];
users.forEach(function(element){
columnAmounts.push({sum:0,amount:0});
})
shows.forEach(function(show){
let display = users.every(function(user,index){
if(user.demand === 1 && show.score[index] === 0){
return false;
}
else if(user.demand === -1 && show.score[index] !== 0){
return false;
};
return (!user.status || show.status[index] === user.status);
});
if(formatFilter.value !== "all"){
if(formatFilter.value !== show.format){
display = false;
};
};
if(show.numberWatched < ratingFilter.value){
display = false;
};
if(!display){
return;
};
let row = create("tr","hohAnimeTable");
row.onclick = function(){
if(this.style.background === "rgb(var(--color-blue),0.5)"){
this.style.background = "unset";
}
else{
this.style.background = "rgb(var(--color-blue),0.5)";
}
}
let showID = create("td",false,false,false,"max-width:250px;");
create("a","newTab",show.title,showID)
.href = "/" + type + "/" + show.id + "/" + safeURL(show.title);
let showAverage = create("td");
if(show.digest){
let fractional = show.digest % 1;
showAverage.innerText = show.digest.roundPlaces(3);
[
{s:"½",v:1/2},
{s:"⅓",v:1/3},
{s:"¼",v:1/4},
{s:"¾",v:3/4},
{s:"⅔",v:2/3},
{s:"⅙",v:1/6},
{s:"⅚",v:5/6},
{s:"⅐",v:1/7}
].find(symbol => {
if(Math.abs(fractional - symbol.v) < 0.0001){
showAverage.innerText = Math.floor(show.digest) + " " + symbol.s;
return true;
}
return false;
});
};
row.appendChild(showID);
row.appendChild(showAverage);
for(var i=0;i amount.amount > 0)){
let lastRow = create("tr",false,false,table);
create("td",false,false,lastRow);
create("td",false,false,lastRow);
columnAmounts.forEach(amount => {
let averageCel = create("td",false,"–",lastRow);
if(amount.amount){
averageCel.innerText = (amount.sum/amount.amount).roundPlaces(2);
}
})
}
};
let changeUserURL = function(){
const baseState = location.protocol + "//" + location.host + location.pathname;
let params = "";
if(users.length){
params += "&users=" + users.map(user => user.name + (user.demand ? (user.demand === -1 ? "-" : "*") : "")).join(",");
}
if(formatFilter.value !== "all"){
params += "&filter=" + encodeURIComponent(formatFilter.value);
};
if(ratingFilter.value !== 1){
params += "&minRatings=" + encodeURIComponent(ratingFilter.value);
};
if(systemFilter.checked){
params += "&ratingSystems=true";
};
if(colourFilter.checked){;
params += "&fullColour=true";
};
if(ratingMode !== "average"){;
params += "&sort=" + ratingMode;
};
if(params.length){
params = "?" + params.substring(1);
}
current = baseState + params;
history.replaceState({},"",baseState + params);
};
let drawUsers = function(){
while(table.childElementCount){
table.lastChild.remove();
};
let userRow = create("tr");
let resetCel = create("td",false,false,userRow);
let resetButton = create("button",["hohButton","button"],"Reset",resetCel,"margin-top:0px;");
resetButton.onclick = function(){
users = [];
shows = [];
drawUsers();
changeUserURL();
};
let digestCel = create("td");
digestSelect = create("select");
let addOption = function(value,text){
let newOption = create("option",false,text,digestSelect);
newOption.value = value;
};
addOption("average","Average");
addOption("median","Median");
addOption("average0","Average~0");
addOption("min","Minimum");
addOption("max","Maximum");
addOption("difference","Difference");
addOption("standardDeviation","Std. Deviation");
addOption("absoluteDeviation","Abs. Deviation");
addOption("ratings","#Ratings");
addOption("planned","#Planning");
addOption("current","#Current");
addOption("favourites","#Favourites");
addOption("popularity","$Popularity");
addOption("averageScore","$Score");
addOption("averageScoreDiff","$Score diff.");
if(["title","titleInverse","user","userInverse"].includes(ratingMode)){
digestSelect.value = ratingMode;
};
digestSelect.oninput = function(){
ratingMode = digestSelect.value;
sortShows();
drawTable();
changeUserURL();
};
digestCel.appendChild(digestSelect);
userRow.appendChild(digestCel);
users.forEach(function(user,index){
let userCel = create("td",false,false,userRow);
let avatar = create("img",false,false,userCel);
avatar.src = listCache[user.name].data.MediaListCollection.user.avatar.medium;
let name = create("span",false,user.name,userCel);
name.style.padding = "8px";
let remove = create("span","hohAnimeTableRemove","✕",userCel);
remove.onclick = function(){
deleteUser(index);
};
});
let addCel = create("td");
let addInput = create("input",false,false,addCel);
let addButton = create("button",["button","hohButton"],"Add",addCel,"margin-top:0px;");
addButton.style.cursor = "pointer";
addButton.onclick = function(){
if(addInput.value !== ""){
addUser(addInput.value);
addButton.innerText = "...";
addButton.disabled = true;
addInput.readOnly = true;
};
};
userRow.appendChild(addCel);
let headerRow = create("tr");
let typeCel = create("th");
let downArrowa = create("span","hohArrowSort","▼",typeCel);
downArrowa.onclick = function(){
ratingMode = "title";
sortShows();
drawTable();
};
let typeCelLabel = create("span",false,capitalize(type),typeCel);
let upArrowa = create("span","hohArrowSort","▲",typeCel);
upArrowa.onclick = function(){
ratingMode = "titleInverse";
sortShows();
drawTable();
};
headerRow.appendChild(typeCel);
let digestSortCel = create("td");
digestSortCel.style.textAlign = "center";
let downArrow = create("span","hohArrowSort","▼",digestSortCel);
downArrow.onclick = function(){
ratingMode = digestSelect.value;
inverse = false;
sortShows(digestSelect.value);
drawTable();
};
let upArrow = create("span","hohArrowSort","▲",digestSortCel);
upArrow.onclick = function(){
ratingMode = digestSelect.value;
inverse = true;
sortShows();
drawTable();
};
headerRow.appendChild(digestSortCel);
users.forEach(function(user,index){
let userCel = create("td");
userCel.style.textAlign = "center";
userCel.style.position = "relative";
let filter = create("span");
if(user.demand === 0){
filter.innerText = "☵";
}
else if(user.demand === 1){
filter.innerText = "✓";
filter.style.color = "green";
}
else{
filter.innerText = "✕";
filter.style.color = "red";
};
filter.classList.add("hohFilterSort");
filter.onclick = function(){
if(filter.innerText === "☵"){
filter.innerText = "✓";
filter.style.color = "green";
user.demand = 1;
}
else if(filter.innerText === "✓"){
filter.innerText = "✕";
filter.style.color = "red";
user.demand = -1;
}
else{
filter.innerText = "☵";
filter.style.color = "";
user.demand = 0;
};
drawTable();
changeUserURL();
};
let downArrow = create("span","hohArrowSort","▼");
downArrow.onclick = function(){
ratingMode = "user";
guser = index;
sortShows();
drawTable();
};
let upArrow = create("span","hohArrowSort","▲");
upArrow.onclick = function(){
ratingMode = "userInverse";
guser = index;
sortShows();
drawTable();
};
let statusFilterDot = create("div","hohStatusDot");
const stati = ["COMPLETED","CURRENT","PLANNING","PAUSED","DROPPED","REPEATING","NOT"];
statusFilterDot.onclick = function(){
if(user.status === "NOT"){
user.status = false;
statusFilterDot.style.background = "rgb(var(--color-background))";
statusFilterDot.title = "all";
}
else if(user.status === "REPEATING"){
user.status = "NOT";
statusFilterDot.style.background = `center / contain no-repeat url('data:image/svg+xml;utf8,')`;
statusFilterDot.title = "no status";
}
else if(user.status === false){
user.status = "COMPLETED";
statusFilterDot.style.background = distributionColours["COMPLETED"];
statusFilterDot.title = "completed";
}
else{
user.status = stati[stati.indexOf(user.status) + 1];
statusFilterDot.style.background = distributionColours[user.status];
statusFilterDot.title = user.status.toLowerCase();
};
drawTable();
};
userCel.appendChild(downArrow);
userCel.appendChild(filter);
userCel.appendChild(upArrow);
userCel.appendChild(statusFilterDot);
headerRow.appendChild(userCel);
});
userRow.classList.add("hohUserRow");
headerRow.classList.add("hohHeaderRow");
table.appendChild(userRow);
table.appendChild(headerRow);
};
let addUser = function(userName,paramDemand){
let handleData = function(data,cached){
users.push({
name: userName,
demand: (paramDemand ? (paramDemand === "-" ? -1 : 1) : 0),
system: data.data.MediaListCollection.user.mediaListOptions.scoreFormat,
status: false
});
let list = returnList(data,true);
if(!cached){
list.forEach(function(alia){
alia.media.title = alia.media.title.romaji;
if(useScripts.titleLanguage === "NATIVE" && alia.media.title.native){
alia.media.title = alia.media.title.native;
}
else if(useScripts.titleLanguage === "ENGLISH" && alia.media.title.english){
alia.media.title = alia.media.title.english;
}
if(aliases.has(alia.mediaId)){
alia.media.title = aliases.get(alia.mediaId)
}
alia.scoreRaw = convertScore(alia.score,data.data.MediaListCollection.user.mediaListOptions.scoreFormat);
});
};
shows.sort(function(a,b){return a.id - b.id;});
let listPointer = 0;
let userIndeks = 0;
if(shows.length){
userIndeks = shows[0].score.length;
};
let favs = data.data.MediaListCollection.user.favourites.fav.nodes.concat(
data.data.MediaListCollection.user.favourites.fav2.nodes
).concat(
data.data.MediaListCollection.user.favourites.fav3.nodes
).map(media => media.id);
let createEntry = function(mediaEntry){
let entry = {
id: mediaEntry.mediaId,
average: mediaEntry.scoreRaw,
title: mediaEntry.media.title,
format: mediaEntry.media.format,
score: Array(userIndeks).fill(0),
scorePersonal: Array(userIndeks).fill(0),
status: Array(userIndeks).fill("NOT"),
progress: Array(userIndeks).fill(false),
numberWatched: mediaEntry.scoreRaw ? 1 : 0,
favourite: Array(userIndeks).fill(false),
averageScore: mediaEntry.media.averageScore,
popularity: mediaEntry.media.popularity
};
entry.score.push(mediaEntry.scoreRaw);
entry.scorePersonal.push(mediaEntry.score);
entry.status.push(mediaEntry.status);
if(mediaEntry.status !== "PLANNING" && mediaEntry.status !== "COMPLETED"){
entry.progress.push(mediaEntry.progress + "/" + (mediaEntry.media.chapters || mediaEntry.media.episodes || ""));
}
else{
entry.progress.push(false);
}
entry.favourite.push(favs.includes(entry.id));
return entry;
};
shows.forEach(function(show){
show.score.push(0);
show.scorePersonal.push(0);
show.status.push("NOT");
show.progress.push(false);
show.favourite.push(false);
});
for(var i=0;i status === "NOT")
});
if(guser === index){
guser = false;
}
else if(guser > index){
guser--;
};
sortShows();
drawUsers();
drawTable();
changeUserURL();
};
formatFilter.oninput = function(){drawTable();changeUserURL()};
ratingFilter.oninput = function(){drawTable();changeUserURL()};
systemFilter.onclick = function(){drawTable();changeUserURL()};
colourFilter.onclick = function(){drawTable();changeUserURL()};
let searchParams = new URLSearchParams(location.search);
let paramFormat = searchParams.get("filter");
if(paramFormat){
formatFilter.value = paramFormat;
};
let paramRating = searchParams.get("minRatings");
if(paramRating){
ratingFilter.value = paramRating;
};
let paramSystem = searchParams.get("ratingSystems");
if(paramSystem){
systemFilter.checked = (paramSystem === "true");
};
let paramColour = searchParams.get("fullColour");
if(paramColour){
colourFilter.checked = (paramColour === "true");
};
let paramSort = searchParams.get("sort");
if(paramSort){
ratingMode = paramSort;
};
let paramUsers = searchParams.get("users");
if(paramUsers){
paramUsers.split(",").forEach(function(user){
let paramDemand = user.match(/(\*|\-)$/);
if(paramDemand){
paramDemand = paramDemand[0];
}
user = user.replace(/(\*|\-)$/,"");
if(user === "~"){
addUser(whoAmI,paramDemand);
}
else{
addUser(user,paramDemand);
}
});
}
else{
addUser(whoAmI);
addUser(userA);
}
}
function addFollowCount(){
let URLstuff = location.pathname.match(/^\/user\/(.*)\/social/)
if(!URLstuff){
return;
};
generalAPIcall("query($name:String){User(name:$name){id}}",{name: decodeURIComponent(URLstuff[1])},function(data){
generalAPIcall("query($id:Int!){Page(perPage:1){pageInfo{total} followers(userId:$id){id}}}",{id:data.data.User.id},function(data){
let target = document.querySelector(".filter-group");
if(target){
target.style.position = "relative";
let followCount = "65536+";
if(data){
followCount = data.data.Page.pageInfo.total;
};
create("span",false,followCount,target.children[2],"position:absolute;right:3px;");
};
});
//these two must be separate calls, because they are allowed to fail individually (too many followers)
generalAPIcall("query($id:Int!){Page(perPage:1){pageInfo{total} following(userId:$id){id}}}",{id:data.data.User.id},function(data){
let target = document.querySelector(".filter-group");
if(target){
target.style.position = "relative";
let followCount = "65536+";
if(data){
followCount = data.data.Page.pageInfo.total;
};
create("span",false,followCount,target.children[1],"position:absolute;right:3px;");
};
});
},"hohIDlookup" + decodeURIComponent(URLstuff[1]).toLowerCase());
}
function embedHentai(){
if(!document.URL.match(/^https:\/\/anilist\.co\/(home|user|forum|activity)/)){
return;
};
if(useScripts.SFWmode){//saved you there
return;
};
setTimeout(embedHentai,1000);
let mediaEmbeds = document.querySelectorAll(".media-embed");
let bigQuery = [];//collects all on a page first so we only have to send 1 API query.
mediaEmbeds.forEach(function(embed){
if(embed.children.length === 0 && !embed.classList.contains("hohMediaEmbed")){//if( "not-rendered-natively" && "not-rendered-by-this sript" )
embed.classList.add("hohMediaEmbed");
let createEmbed = function(data){
if(!data){
return;
};
embed.innerText = "";
let eContainer = create("div",false,false,embed);
let eEmbed = create("div","embed",false,eContainer);
let eCover = create("div","cover",false,eEmbed);
eCover.style.backgroundImage = "url(" + data.data.Media.coverImage.large + ")";
let eWrap = create("div","wrap",false,eEmbed);
let mediaTitle = data.data.Media.title.romaji;
if(useScripts.titleLanguage === "NATIVE" && data.data.Media.title.native){
mediaTitle = data.data.Media.title.native;
}
else if(useScripts.titleLanguage === "ENGLISH" && data.data.Media.title.english){
mediaTitle = data.data.Media.title.english;
};
let eTitle = create("div","title",mediaTitle,eWrap);
let eInfo = create("div","info",false,eWrap);
let eGenres = create("div","genres",false,eInfo);
data.data.Media.genres.forEach(function(genre,index){
let eGenre = create("span",false,genre,eGenres);
let comma = create("span",false,", ",eGenre);
if(index === data.data.Media.genres.length - 1){
comma.style.display = "none";
};
});
create("span",false,distributionFormats[data.data.Media.format],eInfo);
create("span",false," · " + distributionStatus[data.data.Media.status],eInfo);
if(data.data.Media.season){
create("span",false,
" · " + capitalize(data.data.Media.season.toLowerCase()) + " " + data.data.Media.startDate.year,
eInfo
);
}
else if(data.data.Media.startDate.year){
create("span",false,
" · " + data.data.Media.startDate.year,
eInfo
);
}
if(data.data.Media.averageScore){
create("span",false," · " + data.data.Media.averageScore + "%",eInfo);
}
else if(data.data.Media.meanScore){//fallback if it's not popular enough, better than nothing
create("span",false," · " + data.data.Media.meanScore + "%",eInfo);
}
}
bigQuery.push({
query: "query($mediaId:Int,$type:MediaType){Media(id:$mediaId,type:$type){title{romaji native english} coverImage{large} genres format status season meanScore averageScore startDate{year}}}",
variables: {
mediaId: +embed.dataset.mediaId,
type: embed.dataset.mediaType.toUpperCase()
},
callback: createEmbed,
cacheKey: "hohMedia" + embed.dataset.mediaId
});
};
});
queryPacker(bigQuery);
}
function addForumMedia(){
if(location.pathname !== "/home"){
return;
}
let forumThreads = Array.from(document.querySelectorAll(".home .forum-wrap .thread-card .category"));
if(!forumThreads.length){
setTimeout(addForumMedia,200);
return;
};
if(forumThreads.some(function(thread){
return (thread && (thread.innerText.toLowerCase() === "anime" || thread.innerText.toLowerCase() === "manga"))
})){
generalAPIcall("query{Page(perPage:3){threads(sort:REPLIED_AT_DESC){title mediaCategories{title{romaji native english}}}}}",{},function(data){
if(location.pathname !== "/home"){
return;
}
data.data.Page.threads.forEach(function(thread,index){
if(thread.mediaCategories.length && (forumThreads[index].innerText.toLowerCase() === "anime" || forumThreads[index].innerText.toLowerCase() === "manga")){
let title = thread.mediaCategories[0].title.romaji;
if(useScripts.titleLanguage === "NATIVE" && thread.mediaCategories[0].title.native){
title = thread.mediaCategories[0].title.native;
}
else if(useScripts.titleLanguage === "ENGLISH" && thread.mediaCategories[0].title.english){
title = thread.mediaCategories[0].title.english;
}
if(title.length > 40){
forumThreads[index].title = title;
title = title.slice(0,35) + "…";
};
forumThreads[index].innerText = title;
}
});
});
}
}
function addImageFallback(){
if(!document.URL.match(/(\/home|\/user\/)/)){
return;
}
setTimeout(addImageFallback,1000);
let mediaImages = document.querySelectorAll(".media-preview-card:not(.hohFallback) .content .title");
mediaImages.forEach(function(cover){
cover.parentNode.parentNode.classList.add("hohFallback");
if(cover.parentNode.parentNode.querySelector(".hohFallback")){return};
let fallback = create("span","hohFallback",cover.textContent,cover.parentNode.parentNode);
if(useScripts.titleLanguage === "ROMAJI"){
fallback.innerHTML = cover.textContent.replace(/\S{3}(a|☆|\-|e|i|ou|(o|u)(?!u|\s)|n(?!a|e|i|o|u))(?)/gi,m => m + "");
/* create word break opportunities for 'break-word' in nice places in romaji
- after vowels, or 'ou' or 'uu'. Those pairs should not be broken
- If there's a 'n' from 'ん', the break opportunity should be delayed to after it.
- 'ん' is determined by 'not followed by vowel. This doesn't work in cases of '[...]んお[...]' vs '[...]の[...]', but that's a shortcomming of romaji
- don't break early in words, that just looks awkward. just before the last character also looks weird.
- don't break off punctuation or numbers at the end of words*/
}
});
}
function linkFixer(){
if(location.pathname !== "/home"){
return;
}
let recentReviews = document.querySelector(".recent-reviews h2.section-header");
let recentThreads = document.querySelector(".recent-threads h2.section-header");
if(recentReviews && recentThreads){
recentReviews.innerText = "";
create("a",false,"Recent Reviews",recentReviews)
.href = "/reviews";
recentThreads.innerText = "";
create("a",false,"Forum Activity",recentThreads)
.href = "/forum/overview";
}
else{
setTimeout(linkFixer,2000);//invisible change, does not take priority
}
}
function addReviewConfidence(){
generalAPIcall("query{Page(page:1,perPage:30){reviews(sort:ID_DESC){id rating ratingAmount}}}",{},function(data){
let adder = function(){
if(location.pathname !== "/reviews"){
return;
}
let locationForIt = document.querySelector(".recent-reviews .review-wrap");
if(!locationForIt){
setTimeout(adder,200);
return;
}
data.data.Page.reviews.forEach(function(review,index){
let wilsonLowerBound = wilson(review.rating,review.ratingAmount).left
let extraScore = create("span",false,"~" + Math.round(100*wilsonLowerBound));
extraScore.style.color = "hsl(" + wilsonLowerBound*120 + ",100%,50%)";
extraScore.style.marginRight = "3px";
let parent = locationForIt.children[index].querySelector(".votes");
parent.insertBefore(extraScore,parent.firstChild);
if(wilsonLowerBound < 0.05){
locationForIt.children[index].style.opacity = "0.5";
}
});
};adder();
},"hohRecentReviews",30*1000);
}
function addRelationStatusDot(id){
if(!location.pathname.match(/^\/(anime|manga)/)){
return;
};
let relations = document.querySelector(".relations");
if(relations){
if(relations.classList.contains("hohRelationStatusDots")){
return
};
relations.classList.add("hohRelationStatusDots");
};
authAPIcall(
`query($id: Int){
Media(id:$id){
relations{
nodes{
id
type
mediaListEntry{status}
}
}
recommendations(sort:RATING_DESC){
nodes{
mediaRecommendation{
id
type
mediaListEntry{status}
}
}
}
}
}`,
{id: id},
function(data){
let adder = function(){
let mangaAnimeMatch = document.URL.match(/^https:\/\/anilist\.co\/(anime|manga)\/(\d+)\/?([^/]*)?\/?(.*)?/);
if(!mangaAnimeMatch){
return;
}
if(mangaAnimeMatch[2] !== id){
return;
}
let rels = data.data.Media.relations.nodes.filter(media => media.mediaListEntry);
if(rels){
relations = document.querySelector(".relations");
if(relations){
relations.classList.add("hohRelationStatusDots");
relations.querySelectorAll(".hohStatusDot").forEach(dot => dot.remove());
rels.forEach(function(media){
let target = relations.querySelector("[href^=\"/" + media.type.toLowerCase() + "/" + media.id + "/\"]");
if(target){
let statusDot = create("div","hohStatusDot",false,target);
statusDot.style.background = distributionColours[media.mediaListEntry.status];
statusDot.title = media.mediaListEntry.status.toLowerCase();
}
})
}
else{
setTimeout(adder,300);
}
}
};adder();
let recsAdder = function(){
let mangaAnimeMatch = document.URL.match(/^https:\/\/anilist\.co\/(anime|manga)\/(\d+)\/?([^/]*)?\/?(.*)?/);
if(!mangaAnimeMatch){
return;
}
if(mangaAnimeMatch[2] !== id){
return;
};
let recs = data.data.Media.recommendations.nodes.map(
item => item.mediaRecommendation
).filter(
item => item.mediaListEntry
);
if(recs.length){
let findCard = document.querySelector(".recommendation-card");
if(findCard){
findCard = findCard.parentNode;
recs.forEach(media => {
let target = findCard.querySelector("[href^=\"/" + media.type.toLowerCase() + "/" + media.id + "/\"]");
if(target){
let statusDot = create("div","hohStatusDot",false,target);
statusDot.style.background = distributionColours[media.mediaListEntry.status];
statusDot.title = media.mediaListEntry.status.toLowerCase();
}
})
}
else{
setTimeout(recsAdder,300);
}
}
};recsAdder();
},
"hohRelationStatusDot" + id,2*60*1000,
false,false,
function(data){
let adder = function(){
let mangaAnimeMatch = document.URL.match(/^https:\/\/anilist\.co\/(anime|manga)\/(\d+)\/?([^/]*)?\/?(.*)?/);
if(!mangaAnimeMatch){
return;
}
if(mangaAnimeMatch[2] !== id){
return;
}
let rels = data.data.Media.relations.nodes.filter(media => media.mediaListEntry);
if(rels){
relations = document.querySelector(".relations");
if(relations && !relations.classList.contains("hohRelationStatusDots")){
relations.classList.add("hohRelationStatusDots");
rels.forEach(function(media){
let target = relations.querySelector("[href^=\"/" + media.type.toLowerCase() + "/" + media.id + "/\"]");
if(target){
let statusDot = create("div","hohStatusDot",false,target);
statusDot.style.background = distributionColours[media.mediaListEntry.status];
statusDot.title = media.mediaListEntry.status.toLowerCase();
}
})
}
else{
setTimeout(adder,300);
}
}
};adder();
}
)
}
function selectMyThreads(){
if(document.URL !== "https://anilist.co/user/" + whoAmI + "/social#my-threads"){
return;
}
let target = document.querySelector(".filter-group span:nth-child(4)");
if(!target){
setTimeout(selectMyThreads,100);
}
else{
target.click();
}
}
function addMyThreadsLink(){
if(!document.URL.match(/^https:\/\/anilist\.co\/forum\/?(overview|search\?.*|recent|new|subscribed)?$/)){
return;
};
if(document.querySelector(".hohMyThreads")){
return;
};
let target = document.querySelector(".filters");
if(!target){
setTimeout(addMyThreadsLink,100);
}
else{
let link = create("a",["hohMyThreads","link"],"My Threads",target);
link.href = "https://anilist.co/user/" + whoAmI + "/social#my-threads";
}
}
function moreImports(){
if(document.URL !== "https://anilist.co/settings/import"){
return;
}
let target = document.querySelector(".content .import");
if(!target){
setTimeout(moreImports,200);
return;
};
create("hr","hohSeparator",false,target,"margin-bottom:40px;");
let apAnime = create("div",["section","hohImport"],false,target);
create("h2",false,"Anime-Planet: Import Anime List",apAnime);
let apAnimeCheckboxContainer = create("label","el-checkbox",false,apAnime);
let apAnimeOverwrite = createCheckbox(apAnimeCheckboxContainer);
create("span","el-checkbox__label","Overwrite anime already on my list",apAnimeCheckboxContainer);
let apAnimeDropzone = create("div","dropbox",false,apAnime);
let apAnimeInput = create("input","input-file",false,apAnimeDropzone);
let apAnimeDropText = create("p",false,"Drop list JSON file here or click to upload",apAnimeDropzone);
apAnimeInput.type = "file";
apAnimeInput.name = "json";
apAnimeInput.accept = "application/json";
let apManga = create("div",["section","hohImport"],false,target);
create("h2",false,"Anime-Planet: Import Manga List",apManga);
let apMangaCheckboxContainer = create("label","el-checkbox",false,apManga);
let apMangaOverwrite = createCheckbox(apMangaCheckboxContainer);
create("span","el-checkbox__label","Overwrite manga already on my list",apMangaCheckboxContainer);
let apMangaDropzone = create("div","dropbox",false,apManga);
let apMangaInput = create("input","input-file",false,apMangaDropzone);
let apMangaDropText = create("p",false,"Drop list JSON file here or click to upload",apMangaDropzone);
apMangaInput.type = "file";
apMangaInput.name = "json";
apMangaInput.accept = "application/json";
let resultsArea = create("div","importResults",false,target);
let resultsErrors = create("div",false,false,resultsArea,"color:red;padding:5px;");
let resultsWarnings = create("div",false,false,resultsArea,"color:orange;padding:5px;");
let resultsStatus = create("div",false,false,resultsArea,"padding:5px;");
let pushResults = create("button",["hohButton","button"],"Import all selected",resultsArea,"display:none;");
let resultsTable = create("div",false,false,resultsArea);
let apImport = function(type,file){
let reader = new FileReader();
reader.readAsText(file,"UTF-8");
reader.onload = function(evt){
let data;
try{
data = JSON.parse(evt.target.result);
}
catch(e){
resultsErrors.innerText = "error parsing JSON";
}
if(data.export.type !== type){
resultsErrors.innerText = "error wrong list";
return;
}
if(data.user.name.toLowerCase() !== whoAmI.toLowerCase()){
resultsWarnings.innerText = "List for \"" + data.user.name + "\" loaded, but currently signed in as \"" + whoAmI + "\". Are you sure this is right?";
}
else if((new Date()) - (new Date(data.export.date)) > 1000*86400*30){
resultsWarnings.innerText = "This list is " + round(((new Date()) - (new Date(data.export.date)))/(1000*86400*30)) + " days old. Did you upload the right one?";
}
resultsStatus.innerText = "Trying to find matching media...";
let shows = [];
let drawShows = function(){
while(resultsTable.childElementCount){
resultsTable.lastChild.remove();
}
shows.sort(function(b,a){
return a.titles[0].levDistance - b.titles[0].levDistance
});
shows.forEach(function(show){
let row = create("div","hohImportRow",false,resultsTable);
if(show.isAnthology){
create("div","hohImportEntry",show.apData.map(a => a.name).join(", "),row);
}
else{
create("div","hohImportEntry",show.apData.name,row);
}
create("span",false,"→",row);
let aniEntry = create("div","hohImportEntry",false,row,"margin-left:50px");
let aniLink = create("a",["link","newTab"],show.titles[0].title,aniEntry);
aniLink.href = "/" + type + "/" + show.titles[0].id;
let button = createCheckbox(row);
row.style.backgroundColor = "hsl(" + (120 - Math.min(show.titles[0].levDistance,12)*10) + ",30%,50%)";
if(show.titles[0].levDistance > 8){
button.checked = false;
show.toImport = false;
}
else{
button.checked = true;
show.toImport = true;
}
button.oninput = function(){
show.toImport = button.checked;
}
});
};
const apAnthologies = {
"The Dragon Dentist": 20947,
"Hill Climb Girl": 20947,
"20min Walk From Nishi-Ogikubo Station": 20947,
"Collection of Key Animation Films": 20947,
"(Making of) Evangelion: Another Impact": 20947,
"Sex and Violence with Mach Speed": 20947,
"Memoirs of Amorous Gentlemen": 20947,
"Denkou Choujin Gridman: boys invent great hero": 20947,
"Evangelion: Another Impact": 20947,
"Bureau of Proto Society": 20947,
"Cassette Girl": 20947,
"Bubu & Bubulina": 20947,
"I can Friday by day!": 20947,
"Three Fallen Witnesses": 20947,
"Robot on the Road": 20947,
"Comedy Skit 1989": 20947,
"Power Plant No.33": 20947,
"Me! Me! Me! Chronic": 20947,
"Endless Night": 20947,
"Neon Genesis IMPACTS": 20947,
"Obake-chan": 20947,
"Hammerhead": 20947,
"Girl": 20947,
"Yamadeloid": 20947,
"Me! Me! Me!": 20947,
"Ibuseki Yoruni": 20947,
"Rapid Rouge": 20947,
"Tomorrow from there": 20947,
"The Diary of Ochibi": 20947,
"until You come to me.": 20947,
"Tsukikage no Tokio": 20947,
"Carnage": 20947,
"Iconic Field": 20947,
"The Ultraman (2015)": 20947,
"Kanoun": 20947,
"Ragnarok": 20947,
"Death Note Rewrite 1: Visions of a God": 2994,
"Death Note Rewrite 2: L's Successors": 2994,
}
const apMappings = {
"Rebuild of Evangelion: Final": 3786,
"KonoSuba – God’s blessing on this wonderful world!! Movie: Legend of Crimson": 102976,
"Puella Magi Madoka Magica: Magica Quartet x Nisioisin": 20891,
"Kanye West: Good Morning": 8626,
"Patlabor 2: The Movie": 1096,
"She and Her Cat": 1004,
"Star Blazers: Space Battleship Yamato 2199": 12029,
"Digimon Season 3: Tamers": 874,
"The Anthem of the Heart": 20968,
"Digimon Movie 1: Digimon Adventure": 2961,
"Love, Chunibyo & Other Delusions!: Sparkling... Slapstick Noel": 16934,
"The Labyrinth of Grisaia Special": 21312,
"Candy Boy EX01": 5116,
"Candy Boy EX02": 6479,
"Attack on Titan 3rd Season": 99147,
"Attack on Titan 2nd Season": 20958,
"Nichijou - My Ordinary Life: Episode 0": 8857,
"March Comes in like a Lion 2nd Season": 98478,
"KonoSuba – God’s blessing on this wonderful world!! 2 OVA": 97996,
"KonoSuba – God’s blessing on this wonderful world!! OVA": 21574,
"Laid-Back Camp Specials": 101206,
"Spice and Wolf II OVA": 6007,
"Mob Psycho 100 Specials": 102449
}
let bigQuery = [];
let myFastMappings = [];
data.entries.forEach(function(entry,index){
if(entry.status === "won't watch"){
return;
};
if(apAnthologies[entry.name]){
let already = myFastMappings.findIndex(function(mapping){
return mapping.id === apAnthologies[entry.name]
});
if(already !== -1){
myFastMappings[already].entries.push(entry);
}
else{
myFastMappings.push({
entries: [entry],
isAnthology: true,
id: apAnthologies[entry.name]
})
}
return;
}
if(apMappings[entry.name]){
myFastMappings.push({
entries: [entry],
id: apMappings[entry.name]
})
return;
}
bigQuery.push({
query: `query($search:String){Page(perPage:3){media(type:${type.toUpperCase()},search:$search){title{romaji english native} id synonyms}}}`,
variables: {search: entry.name},
callback: function(dat){
let show = {
apData: entry,
aniData: dat.data.Page.media
}
show.titles = [];
show.aniData.forEach(function(hit){
show.titles.push({
title: hit.title.romaji,
id: hit.id,
levDistance: Math.min(
levDist(show.apData.name,hit.title.romaji),
levDist(show.apData.name,hit.title.romaji.toUpperCase()),
levDist(show.apData.name,hit.title.romaji.toLowerCase())
)
});
if(hit.title.native){
show.titles.push({
title: hit.title.native,
id: hit.id,
levDistance: levDist(show.apData.name,hit.title.native)
});
}
if(hit.title.english){
show.titles.push({
title: hit.title.english,
id: hit.id,
levDistance: Math.min(
levDist(show.apData.name,hit.title.english),
levDist(show.apData.name,hit.title.english.toUpperCase()),
levDist(show.apData.name,hit.title.english.toLowerCase())
)
});
}
hit.synonyms.forEach(function(synonym){
show.titles.push({
title: synonym,
id: hit.id,
levDistance: levDist(show.apData.name,synonym)
});
});
});
show.titles.sort(function(a,b){
return a.levDistance - b.levDistance
});
shows.push(show);
drawShows();
}
});
if(index % 40 === 0){
queryPacker(bigQuery);
bigQuery = [];
}
});
let apStatusMap = {
"want to read": "PLANNING",
"stalled": "PAUSED",
"read": "COMPLETED",
"reading": "CURRENT",
"watched": "COMPLETED",
"want to watch": "PLANNING",
"dropped": "DROPPED",
"watching": "CURRENT"
}
queryPacker(bigQuery,function(){
setTimeout(function(){
resultsStatus.innerText = "Please review the media matches. The worst matches are on top.";
pushResults.style.display = "inline";
pushResults.onclick = function(){
pushResults.style.display = "none";
if(!useScripts.accessToken){
alert("Not signed in to the script. Can't do any changes to your list\n Go to settings > apps to sign in");
return;
}
authAPIcall(
`query($name: String,$listType: MediaType){
Viewer{name mediaListOptions{scoreFormat}}
MediaListCollection(userName: $name, type: $listType){
lists{
entries{
mediaId
}
}
}
}`,
{
listType: type.toUpperCase(),
name: whoAmI
},
function(data){
if(data.data.Viewer.name !== whoAmI){
alert("Signed in as\"" + whoAmI + "\" to Anilist, but as \"" + data.data.Viewer.name + "\" to the script.\n Go to settings > apps, revoke Aniscript's permissions, and sign in with the scirpt again to fix this.");
return;
};
let list = returnList(data,true).map(a => a.mediaId);
shows = shows.filter(function(show){
if(!show.toImport){
return false;
}
if(type === "anime"){
if(!apAnimeOverwrite.checked && list.includes(show.titles[0].id)){
return false;
}
}
else{
if(!apMangaOverwrite.checked && list.includes(show.titles[0].id)){
return false;
}
}
return true;
});
if(!shows.length){
return;
};
let mutater = function(show,index){
if(index + 1 < shows.length){
setTimeout(function(){
mutater(shows[index + 1],index + 1);
},1000);
}
let status = false;
if(show.isAnthology){
status = "CURRENT";
}
else{
status = apStatusMap[show.apData.status];
}
if(!status){
console.log("Unknown status: " + show.apData.status);
return;
}
let score = 0;
if(!show.isAnthology){
score = show.apData.rating*2;
if(data.data.Viewer.mediaListOptions.scoreFormat === "POINT_100"){
score = show.apData.rating*20;
}
else if(data.data.Viewer.mediaListOptions.scoreFormat === "POINT_5"){
score = Math.floor(show.apData.rating);
if(show.apData.rating === 0.5){
score = 1
}
}
else if(data.data.Viewer.mediaListOptions.scoreFormat === "POINT_3"){
if(show.apData.rating === 0){
score = 0
}
else if(show.apData.rating < 2.5){
score = 1
}
else if(show.apData.rating < 4){
score = 2
}
else{
score = 3
}
};
};
let progress = 0;
let progressVolumes = 0;
let repeat = 0;
if(show.isAnthology){
progress = show.apData.length;
}
else{
repeat = show.apData.times - 1;
if(status === "DROPPED" || status === "PAUSED" || status === "CURRENT"){
if(type === "anime"){
progress = show.apData.eps;
}
else{
progress = show.apData.ch;
}
}
}
if(type === "manga"){
progressVolumes = show.apData.vol;
}
if(progress){
authAPIcall(
`mutation(
$mediaId: Int,
$status: MediaListStatus,
$score: Float,
$progress: Int,
$progressVolumes: Int,
$repeat: Int
){
SaveMediaListEntry(
mediaId: $mediaId,
status: $status,
score: $score,
progress: $progress,
progressVolumes: $progressVolumes,
repeat: $repeat
){
id
}
}`,
{
mediaId: show.titles[0].id,
status: status,
score: score,
progress: progress,
progressVolumes: progressVolumes,
repeat: repeat
},
data => {}
)
}
else{
authAPIcall(
`mutation(
$mediaId: Int,
$status: MediaListStatus,
$score: Float,
$repeat: Int
){
SaveMediaListEntry(
mediaId: $mediaId,
status: $status,
score: $score,
repeat: $repeat
){
id
}
}`,
{
mediaId: show.titles[0].id,
status: status,
score: score,
repeat: repeat
},
data => {}
)
}
resultsStatus.innerText = (index + 1) + " of " + shows.length + " entries imported";
};
mutater(shows[0],0);
})
};
},2000);
});
bigQuery = [];
myFastMappings.forEach(function(entry){
bigQuery.push({
query: `query($id:Int){Media(type:${type.toUpperCase()},id:$id){title{romaji english native} id}}`,
variables: {id: entry.id},
callback: function(dat){
if(entry.isAnthology){
let show = {
apData: entry.entries,
directMapping: true,
isAnthology: true,
aniData: dat.data.Media,
titles: [{title: dat.data.Media.title.romaji,id: entry.id,levDistance: 0}]
}
shows.push(show);
drawShows();
}
else{
let show = {
apData: entry.entries[0],
directMapping: true,
aniData: dat.data.Media,
titles: [{title: dat.data.Media.title.romaji,id: entry.id,levDistance: 0}]
}
shows.push(show);
drawShows();
}
}
});
});
queryPacker(bigQuery);
}
reader.onerror = function(evt){
resultsErrors.innerText = "error reading file";
}
}
apAnimeInput.onchange = function(){
apImport("anime",apAnimeInput.files[0]);
}
apMangaInput.onchange = function(){
apImport("manga",apMangaInput.files[0]);
}
create("hr","hohSeparator",false,target,"margin-bottom:40px;");
let alAnime = create("div",["section","hohImport"],false,target);
create("h2",false,"AniList: Export Anime List",alAnime);
let alAnimeButton = create("button",["button","hohButton"],"Export",alAnime);
alAnimeButton.onclick = function(){
generalAPIcall(
`
query($name: String!){
MediaListCollection(userName: $name, type: ANIME){
lists{
name
isCustomList
isSplitCompletedList
entries{
... mediaListEntry
}
}
}
User(name: $name){
name
id
mediaListOptions{
scoreFormat
}
}
}
fragment mediaListEntry on MediaList{
mediaId
status
progress
repeat
notes
priority
hiddenFromStatusLists
customLists
advancedScores
startedAt{
year
month
day
}
completedAt{
year
month
day
}
updatedAt
createdAt
media{
idMal
title{romaji native english}
}
score
}
`,
{name: whoAmI},
function(data){
data.data.version = "1.00";
data.data.scriptInfo = scriptInfo;
data.data.url = document.URL;
data.data.timeStamp = NOW();
saveAs(data.data,"AnilistAnimeList.json");
}
);
}
create("h2",false,"AniList: Export Manga List",alAnime,"margin-top:20px;");
let alMangaButton = create("button",["button","hohButton"],"Export",alAnime);
alMangaButton.onclick = function(){
generalAPIcall(
`
query($name: String!){
MediaListCollection(userName: $name, type: ANIME){
lists{
name
isCustomList
isSplitCompletedList
entries{
... mediaListEntry
}
}
}
User(name: $name){
name
id
mediaListOptions{
scoreFormat
}
}
}
fragment mediaListEntry on MediaList{
mediaId
status
progress
progressVolumes
repeat
notes
priority
hiddenFromStatusLists
customLists
advancedScores
startedAt{
year
month
day
}
completedAt{
year
month
day
}
updatedAt
createdAt
media{
idMal
title{romaji native english}
}
score
}
`,
{name: whoAmI},
function(data){
data.data.version = "1.00";
data.data.scriptInfo = scriptInfo;
data.data.url = document.URL;
data.data.timeStamp = NOW();
saveAs(data.data,"AnilistMangaList.json");
}
);
};
let malExport = function(data,type){
let xmlContent = "";
saveAs(xmlContent,type.toLowerCase() + "list_0_-_0.xml",true);
}
}
function addSocialThemeSwitch(){
let URLstuff = location.pathname.match(/^\/user\/(.*)\/social/)
if(!URLstuff){
return;
};
if(document.querySelector(".filters .hohThemeSwitch")){
return;
};
let target = document.querySelector(".filters");
if(!target){
setTimeout(addSocialThemeSwitch,100);
return;
}
let themeSwitch = create("div",["theme-switch","hohThemeSwitch"],false,target,"width:70px;");
let listView = create("span",false,false,themeSwitch);
let cardView = create("span","active",false,themeSwitch);
listView.innerHTML = svgAssets.listView;
cardView.innerHTML = svgAssets.cardView;
listView.onclick = function(){
document.querySelector(".hohThemeSwitch .active").classList.remove("active");
listView.classList.add("active");
document.querySelector(".user-social").classList.add("listView");
}
cardView.onclick = function(){
document.querySelector(".hohThemeSwitch .active").classList.remove("active");
cardView.classList.add("active");
document.querySelector(".user-social.listView").classList.remove("listView");
}
let traitorTracer = create("button",["button","hohButton"],"⇌",target,"padding:5px;");
traitorTracer.onclick = function(){
traitorTracer.setAttribute("disabled","disabled");
let query = `
query($userId: Int!){
a1:Page(page:1){following(userId: $userId,sort: USERNAME){name}}
a2:Page(page:2){following(userId: $userId,sort: USERNAME){name}}
a3:Page(page:3){following(userId: $userId,sort: USERNAME){name}}
a4:Page(page:4){following(userId: $userId,sort: USERNAME){name}}
a5:Page(page:5){following(userId: $userId,sort: USERNAME){name}}
a6:Page(page:6){following(userId: $userId,sort: USERNAME){name}}
a7:Page(page:7){following(userId: $userId,sort: USERNAME){name}}
a8:Page(page:8){following(userId: $userId,sort: USERNAME){name}}
a9:Page(page:9){following(userId: $userId,sort: USERNAME){name}}
a10:Page(page:10){following(userId: $userId,sort: USERNAME){name}}
a11:Page(page:11){following(userId: $userId,sort: USERNAME){name}}
a12:Page(page:12){following(userId: $userId,sort: USERNAME){name}}
}`;
let traitorText = traitorTracer.parentNode.querySelector(".filter-group .active").childNodes[0].textContent.trim();
if(traitorText === "Following"){
query = `
query($userId: Int!){
a1:Page(page:1){followers(userId: $userId,sort: USERNAME){name}}
a2:Page(page:2){followers(userId: $userId,sort: USERNAME){name}}
a3:Page(page:3){followers(userId: $userId,sort: USERNAME){name}}
a4:Page(page:4){followers(userId: $userId,sort: USERNAME){name}}
a5:Page(page:5){followers(userId: $userId,sort: USERNAME){name}}
a6:Page(page:6){followers(userId: $userId,sort: USERNAME){name}}
a7:Page(page:7){followers(userId: $userId,sort: USERNAME){name}}
a8:Page(page:8){followers(userId: $userId,sort: USERNAME){name}}
a9:Page(page:9){followers(userId: $userId,sort: USERNAME){name}}
a10:Page(page:10){followers(userId: $userId,sort: USERNAME){name}}
a11:Page(page:11){followers(userId: $userId,sort: USERNAME){name}}
a12:Page(page:12){followers(userId: $userId,sort: USERNAME){name}}
}`
}
else if(traitorText !== "Followers"){
return;
};
generalAPIcall("query($name:String){User(name:$name){id}}",{name: decodeURIComponent(URLstuff[1])},function(data){
generalAPIcall(
query,
{userId: data.data.User.id},
function(people){
traitorTracer.removeAttribute("disabled");
let users = new Set(
[].concat(
...Object.keys(people.data).map(
a => people.data[a].following || people.data[a].followers
)
).map(a => a.name)
);
document.querySelectorAll(".user-follow .follow-card > .name").forEach(function(place){
if(!users.has(place.textContent.trim())){
place.parentNode.style.border = "7px solid red";
}
});
}
)
},"hohIDlookup" + decodeURIComponent(URLstuff[1]).toLowerCase());
};
}
function addCompactBrowseSwitch(){
let URLstuff = location.pathname.match(/^\/search\//)
if(!URLstuff){
return;
};
if(document.querySelector(".search-page-unscoped .hohThemeSwitch")){
return;
};
let target = document.querySelector(".search-page-unscoped");
if(!target){
setTimeout(addCompactBrowseSwitch,100);
return;
}
let themeSwitch = create("div",["theme-switch","hohThemeSwitch"],false,target);
let compactListView = create("span",false,false,themeSwitch);
let listView = create("span",false,false,themeSwitch);
let compactView = create("span","active",false,themeSwitch);
let cardView = create("span",false,false,themeSwitch);
compactListView.innerHTML = svgAssets.listView;
listView.innerHTML = svgAssets.bigListView;
compactView.innerHTML = svgAssets.compactView;
cardView.innerHTML = svgAssets.cardView;
compactView.onclick = function(){
document.querySelector(".hohThemeSwitch .active").classList.remove("active");
compactView.classList.add("active");
target.classList.remove("cardView");
target.classList.remove("listView");
target.classList.remove("compactListView");
}
cardView.onclick = function(){
document.querySelector(".hohThemeSwitch .active").classList.remove("active");
cardView.classList.add("active");
target.classList.add("cardView");
target.classList.remove("listView");
target.classList.remove("compactListView");
}
listView.onclick = function(){
document.querySelector(".hohThemeSwitch .active").classList.remove("active");
listView.classList.add("active");
target.classList.add("cardView");
target.classList.add("listView");
target.classList.remove("compactListView");
}
compactListView.onclick = function(){
document.querySelector(".hohThemeSwitch .active").classList.remove("active");
compactListView.classList.add("active");
target.classList.add("cardView");
target.classList.remove("listView");
target.classList.add("compactListView");
}
}
function addStudioBrowseSwitch(){
let URLstuff = location.pathname.match(/^\/studio\//)
if(!URLstuff){
return;
};
if(document.querySelector(".studio-page-unscoped .hohThemeSwitch")){
return;
};
let target = document.querySelector(".studio-page-unscoped");
if(!target){
setTimeout(addStudioBrowseSwitch,100);
return;
}
let themeSwitch = create("div",["theme-switch","hohThemeSwitch"],false,target);
target.classList.add("cardView");
let compactListView = create("span",false,false,themeSwitch);
let listView = create("span",false,false,themeSwitch);
let compactView = create("span",false,false,themeSwitch);
let cardView = create("span","active",false,themeSwitch);
compactListView.innerHTML = svgAssets.listView;
listView.innerHTML = svgAssets.bigListView;
compactView.innerHTML = svgAssets.compactView;
cardView.innerHTML = svgAssets.cardView;
compactView.onclick = function(){
document.querySelector(".hohThemeSwitch .active").classList.remove("active");
compactView.classList.add("active");
target.classList.remove("cardView");
target.classList.remove("listView");
target.classList.remove("compactListView");
}
cardView.onclick = function(){
document.querySelector(".hohThemeSwitch .active").classList.remove("active");
cardView.classList.add("active");
target.classList.add("cardView");
target.classList.remove("listView");
target.classList.remove("compactListView");
}
listView.onclick = function(){
document.querySelector(".hohThemeSwitch .active").classList.remove("active");
listView.classList.add("active");
target.classList.add("cardView");
target.classList.add("listView");
target.classList.remove("compactListView");
}
compactListView.onclick = function(){
document.querySelector(".hohThemeSwitch .active").classList.remove("active");
compactListView.classList.add("active");
target.classList.add("cardView");
target.classList.remove("listView");
target.classList.add("compactListView");
}
}
function viewAdvancedScores(url){
let URLstuff = url.match(/^https:\/\/anilist\.co\/user\/(.+)\/(anime|manga)list\/?/);
let name = decodeURIComponent(URLstuff[1]);
generalAPIcall(
`query($name:String!){
User(name:$name){
mediaListOptions{
animeList{advancedScoringEnabled}
mangaList{advancedScoringEnabled}
}
}
}`,
{name: name},function(data){
if(
!(
(URLstuff[2] === "anime" && data.data.User.mediaListOptions.animeList.advancedScoringEnabled)
|| (URLstuff[2] === "manga" && data.data.User.mediaListOptions.mangaList.advancedScoringEnabled)
)
){
return;
};
generalAPIcall(
`query($name:String!,$listType:MediaType){
MediaListCollection(userName:$name,type:$listType){
lists{
entries{mediaId advancedScores}
}
}
}`,
{name: name,listType: URLstuff[2].toUpperCase()},
function(data2){
let list = new Map(returnList(data2,true).map(a => [a.mediaId,a.advancedScores]));
let finder = function(){
if(!document.URL.match(/^https:\/\/anilist\.co\/user\/(.+)\/(anime|manga)list\/?/)){
return;
};
document.querySelectorAll(
".list-entries .entry .title > a:not(.hohAdvanced)"
).forEach(function(entry){
entry.classList.add("hohAdvanced");
let key = parseInt(entry.href.match(/\/(\d+)\//)[1]);
let dollar = create("span","hohAdvancedDollar","$",entry.parentNode);
let advanced = list.get(key);
let reasonable = Object.keys(advanced).map(
key => [key,advanced[key]]
).filter(
a => a[1]
);
dollar.title = reasonable.map(
a => a[0] + ": " + a[1]
).join("\n");
if(!reasonable.length){
dollar.style.display = "none";
};
});
setTimeout(finder,1000);
};finder();
}
)
});
};
function randomButtons(){
let list = [
{data:"users",single:"user"},
{data:"media(type: ANIME)",single:"anime"},
{data:"media(type: MANGA)",single:"manga"},
{data:"characters",single:"character"},
{data:"staff",single:"staff"},
{data:"reviews",single:"review"}
];
list.forEach(function(item,index){
let adder = function(data){
let place = document.querySelectorAll("section > .heading > h3");
if(place.length <= index){
setTimeout(function(){adder(data)},200);
return;
}
let currentText = place[index].innerText;
place[index].innerText = "";
let link = create("a","link",currentText,place[index],"cursor:pointer;");
let selected = Math.floor(Math.random()*data.data.Page.pageInfo.total);
link.onclick = function(){
generalAPIcall(
`query($page:Int){
Page(page:$page){
${item.data}{id}
}
}`,
{page: Math.ceil(selected / 50)},
function(data){
window.location.href = "https://anilist.co/" + item.single + "/" + data.data.Page[item.data.replace(/\(.*\)/,"")][selected % 50].id + "/";
}
);
}
};
generalAPIcall(
`query($page:Int){
Page(page:$page){
pageInfo{total}
${item.data}{id}
}
}`,
{page: 1},
adder
);
});
let speedAdder = function(data){
if(!data){
return;
}
let place = document.querySelector(".page-content .container section");
if(!place){
setTimeout(function(){speedAdder(data)},200);
return;
};
let activityContainer = create("div",false,false,place.parentNode);
create("h3","heading","Current Activity",activityContainer);
create("p",false,Math.round((3600*199/(data.data.act1.activities[0].createdAt - data.data.act2.activities[9].createdAt))) + " activities/hour",activityContainer);
let activities = data.data.text.activities;
create("p",false,(3600*(activities.length - 1)/(activities[0].createdAt - activities[activities.length - 1].createdAt)).roundPlaces(1) + " status posts/hour",activityContainer);
activities = data.data.message.activities;
create("p",false,(3600*(activities.length - 1)/(activities[0].createdAt - activities[activities.length - 1].createdAt)).roundPlaces(1) + " messages/hour",activityContainer);
};
generalAPIcall(
`query{
act1:Page(page: 1,perPage:10){
activities(sort:ID_DESC){
... on TextActivity{createdAt}
... on MessageActivity{createdAt}
... on ListActivity{createdAt}
}
}
act2:Page(page: 20,perPage:10){
activities(sort:ID_DESC){
... on TextActivity{createdAt}
... on MessageActivity{createdAt}
... on ListActivity{createdAt}
}
}
text:Page{
activities(sort:ID_DESC,type:TEXT){
... on TextActivity{createdAt}
}
}
message:Page{
activities(sort:ID_DESC,type:MESSAGE){
... on MessageActivity{createdAt}
}
}
}`,
{},
speedAdder
);
}
function possibleBlocked(oldURL){
let URLstuff = oldURL.match(/\/user\/(.*?)\/?$/);
let name = decodeURIComponent(URLstuff[1]);
const query = `
query($userName: String) {
User(name: $userName){
id
}
}`;
let variables = {
userName: name
}
if(name !== whoAmI){
generalAPIcall(query,variables,data => {
let notFound = document.querySelector(".not-found");
name = name.split("/")[0];
if(notFound){
if(name.includes("submissions")){
notFound.innerText = "This entry was denied";
}
else if(data){
notFound.innerText = name + " has blocked you";
}
else{
notFound.innerText = name + " does not exist or has a private profile";
}
notFound.style.paddingTop = "200px";
notFound.style.fontSize = "2rem";
}
});
};
}
function hideGlobalFeed(){
if(!location.pathname.match(/^\/home/)){
return;
};
let toggle = document.querySelector(".feed-type-toggle");
if(!toggle){
setTimeout(hideGlobalFeed,100);
return;
};
toggle.children[1].style.display = "none";
if(toggle.children[1].classList.contains("active")){
toggle.children[0].click();
};
};
function yearStepper(){
if(!location.pathname.match(/\/user\/.*\/(anime|manga)list/)){
return;
}
let slider = document.querySelector(".el-slider");
if(!slider){
setTimeout(yearStepper,200);
return;
};
const maxYear = parseInt(slider.getAttribute("aria-valuemax"));
const minYear = parseInt(slider.getAttribute("aria-valuemin"));
const yearRange = maxYear - minYear;
let clickSlider = function(year){//thanks, mator!
let runway = slider.children[0];
let r = runway.getBoundingClientRect();
const x = r.left + r.width * ((year - minYear) / yearRange);
const y = r.top + r.height / 2;
runway.dispatchEvent(new MouseEvent("click",{
clientX: x,
clientY: y
}));
};
let adjuster = function(delta){
let heading = slider.previousElementSibling;
if(heading.children.length === 0){
if(delta === -1){
clickSlider(maxYear);
}
else{
clickSlider(minYear);
}
}
else{
let current = parseInt(heading.children[0].innerText);
clickSlider(current + delta);
};
};
if(document.querySelector(".hohStepper")){
return;
};
slider.style.position = "relative";
let decButton = create("span","hohStepper","<",slider,"left:-27px;font-size:200%;top:0px;");
let incButton = create("span","hohStepper",">",slider,"right:-27px;font-size:200%;top:0px;");
decButton.onclick = function(){
adjuster(-1);
};
incButton.onclick = function(){
adjuster(1);
};
}
function profileBackground(){
if(useScripts.SFWmode){
return;
};
let URLstuff = location.pathname.match(/^\/user\/(.*?)\/?$/);
const query = `
query($userName: String) {
User(name: $userName){
about
}
}`;
let variables = {
userName: decodeURIComponent(URLstuff[1])
}
generalAPIcall(query,variables,data => {
if(!data){
return;
};
let jsonMatch = (data.data.User.about || "").match(/^/);
if(!jsonMatch){
let target = document.querySelector(".user-page-unscoped");
if(target){
target.style.background = "unset";
}
return;
};
try{
let jsonData = JSON.parse(jsonMatch[1]);
if(jsonData.background){
let adder = function(){
if(!location.pathname.match(/^\/user\/(.*?)\/?$/)){
return;
};
let target = document.querySelector(".user-page-unscoped");
if(target){
target.style.background = jsonData.background;
}
else{
setTimeout(adder,200);
}
};adder();
};
}
catch(e){
console.warn("Invalid profile JSON for " + variables.userName + ". Aborting.");
console.log(jsonMatch[1]);
};
},"hohProfileBackground" + variables.userName,30*1000);
}
function addCustomCSS(){
if(useScripts.SFWmode){
return;
};
let URLstuff = location.pathname.match(/^\/user\/([^/]*)\/?/);
if(!customStyle.textContent || (decodeURIComponent(URLstuff[1]) !== currentUserCSS)){
const query = `
query($userName: String) {
User(name: $userName){
about
}
}`;
let variables = {
userName: decodeURIComponent(URLstuff[1])
}
generalAPIcall(query,variables,data => {
customStyle.textContent = "";
if(!data){
return;
};
let jsonMatch = (data.data.User.about || "").match(/^/);
if(!jsonMatch){
return;
};
try{
let jsonData = JSON.parse(jsonMatch[1]);
if(jsonData.customCSS){
customStyle.textContent = jsonData.customCSS;
currentUserCSS = decodeURIComponent(URLstuff[1]);
};
}
catch(e){
console.warn("Invalid profile JSON for " + variables.userName + ". Aborting.");
console.log(jsonMatch[1]);
};
},"hohProfileBackground" + variables.userName,30*1000);
};
}
function termsFeed(){
let page = 1;
let location = document.querySelector(".container");
location.parentNode.style.background = "rgb(39,44,56)";
location.parentNode.style.color = "rgb(159,173,189)";
let terms = create("div",["container","termsFeed"],false,location.parentNode,"max-width: 1100px;margin-left:170px;margin-right:170px;");
location.style.display = "none";
let policy = create("button",["hohButton","button"],"View Privacy Policy instead",terms,"font-size:1rem;color:initial;");
policy.onclick = function(){
location.style.display = "initial";
terms.style.display = "none";
};
if(!useScripts.accessToken){
create("p",false,"This module does not work without signing in to the script",terms);
let loginURL = create("a",false,"Sign in with the script",terms);
loginURL.href = authUrl;
loginURL.style.color = "rgb(61,180,242)";
return;
};
let browseSettings = create("div",false,false,terms,"margin-top:10px;");
let onlyGlobal = createCheckbox(browseSettings);
create("span",false,"Global",browseSettings,"margin-right:5px;");
let onlyStatus = createCheckbox(browseSettings);
create("span",false,"Text posts",browseSettings,"margin-right:5px;");
let onlyReplies = createCheckbox(browseSettings);
create("span",false,"Has replies",browseSettings,"margin-right:5px;");
let onlyForum = createCheckbox(browseSettings);
create("span",false,"Forum",browseSettings,"margin-right:5px;");
let onlyReviews = createCheckbox(browseSettings);
create("span",false,"Reviews",browseSettings);
create("br",false,false,browseSettings);
create("br",false,false,browseSettings);
let onlyUser = createCheckbox(browseSettings);
create("span",false,"User",browseSettings,"margin-right:5px;");
let onlyUserInput = create("input",false,false,browseSettings,"background:rgb(31,35,45);border-width:0px;margin-left:20px;border-radius:3px;color:rgb(159,173,189);margin-right: 10px;padding:3px;");
let onlyMedia = createCheckbox(browseSettings);
create("span",false,"Media",browseSettings,"margin-right:5px;");
let onlyMediaResult = {id: 0,type: "ANIME"};
let onlyMediaInput = create("input",false,false,browseSettings,"background:rgb(31,35,45);border-width:0px;margin-left:20px;border-radius:3px;color:rgb(159,173,189);margin-right: 10px;padding:3px;");
let mediaDisplayResults = create("div",false,false,browseSettings,"margin-top:5px;");
let dataUsers = new Set([whoAmI]);
let dataMedia = new Set();
let dataUsersList = create("datalist","#userDatalist",false,browseSettings);
let dataMediaList = create("datalist","#userMedialist",false,browseSettings);
onlyUserInput.setAttribute("list","userDatalist");
onlyMediaInput.setAttribute("list","userMedialist");
let feed = create("div","hohFeed",false,terms);
let topNav = create("div",false,false,feed,"position:relative;min-height:60px;margin-bottom:15px;");
let loading = create("p",false,"Loading...",topNav);
let pageCount = create("p",false,"Page 1",topNav);
let statusInput = create("div",false,false,topNav);
let onlySpecificActivity = false;
let statusInputTitle = create("input",false,false,statusInput,"display:none;border-width: 1px;padding: 4px;border-radius: 2px;color: rgb(159, 173, 189);background: rgb(var(--color-foreground));");
statusInputTitle.placeholder = "Title";
let inputArea = create("textarea",false,false,statusInput,"width: 99%;border-width: 1px;padding: 4px;border-radius: 2px;color: rgb(159, 173, 189);resize: vertical;");
create("br",false,false,statusInput);
let cancelButton = create("button",["hohButton","button"],"Cancel",statusInput,"background:rgb(31,35,45);display:none;color: rgb(159, 173, 189);");
let publishButton = create("button",["hohButton","button"],"Publish",statusInput,"display:none;");
inputArea.placeholder = "Write a status...";
let topPrevious = create("button",["hohButton","button"],"Refresh",topNav,"position:fixed;top:120px;left:calc(5% - 50px);z-index:50;");
let topNext = create("button",["hohButton","button"],"Next →",topNav,"position:fixed;top:120px;right:calc(5% - 50px);z-index:50;");
let feedContent = create("div",false,false,feed);
let notiLink = create("a",["link","newTab"],"",topNav,"position:fixed;top:10px;right:10px;color:rgb(var(--color-blue));text-decoration:none;");
notiLink.href = "/notifications";
let lastUpdated = 0;
let buildPage = function(activities,type,requestTime){
if(requestTime < lastUpdated){
return;
}
lastUpdated = requestTime;
loading.innerText = "";
pageCount.innerText = "Page " + page;
if(page === 1){
topPrevious.innerText = "Refresh";
}
else{
topPrevious.innerText = "← Previous";
};
while(feedContent.childElementCount){
feedContent.lastChild.remove();
};
activities.forEach(function(activity){
let act = create("div","activity",false,feedContent);
let diff = NOW() - (new Date(activity.createdAt * 1000)).valueOf();
let time = create("span",["time","hohMonospace"],formatTime(Math.round(diff/1000),"short"),act,"width:50px;position:absolute;left:1px;top:2px;");
time.title = (new Date(activity.createdAt * 1000)).toLocaleString();
let content = create("div",false,false,act,"margin-left:60px;position:relative;");
let user = create("a",["link","newTab"],activity.user.name,content);
user.href = "/user/" + activity.user.name + "/";
let actions = create("div","actions",false,content,"position:absolute;text-align:right;");
let replyWrap = create("span",["action","hohReplies"],false,actions,"display:inline-block;min-width:35px;margin-left:2px");
let replyCount = create("span","count",(activity.replies.length || activity.replyCount ? activity.replies.length || activity.replyCount : " "),replyWrap);
let replyIcon = create("span",false,false,replyWrap);
replyIcon.innerHTML = svgAssets.reply;
replyWrap.style.cursor = "pointer";
replyIcon.children[0].style.width = "13px";
replyIcon.stylemarginLeft = "-2px";
let likeWrap = create("span",["action","hohLikes"],false,actions,"display:inline-block;min-width:35px;margin-left:2px");
likeWrap.title = activity.likes.map(a => a.name).join("\n");
let likeCount = create("span","count",(activity.likes.length ? activity.likes.length : " "),likeWrap);
let heart = create("span",false,"♥",likeWrap,"position:relative;");
let likeQuickView = create("div","hohLikeQuickView",false,heart);
if(type === "review"){
heart.innerText = activity.rating + "/" + activity.ratingAmount
};
likeWrap.style.cursor = "pointer";
if(activity.likes.some(like => like.name === whoAmI)){
likeWrap.classList.add("hohILikeThis");
};
let likeify = function(likes,likeQuickView){
while(likeQuickView.childElementCount){
likeQuickView.lastChild.remove()
}
if(likes.length === 0){}
else if(likes.length === 1){
create("span",false,likes[0].name,likeQuickView,`color: hsl(${Math.abs(hashCode(likes[0].name)) % 360},50%,50%)`);
}
else if(likes.length === 2){
let name1 = create("span",false,likes[0].name.slice(0,(likes[0].name.length <= 6 ? likes[0].name.length : 4)),likeQuickView,`color: hsl(${Math.abs(hashCode(likes[0].name)) % 360},50%,50%)`);
create("span",false," & ",likeQuickView);
let name2 = create("span",false,likes[1].name.slice(0,(likes[1].name.length <= 6 ? likes[1].name.length : 4)),likeQuickView,`color: hsl(${Math.abs(hashCode(likes[1].name)) % 360},50%,50%)`);
name1.onmouseover = function(){
name1.innerText = likes[0].name;
}
name2.onmouseover = function(){
name2.innerText = likes[1].name;
}
}
else if(likes.length === 3){
let name1 = create("span",false,likes[0].name.slice(0,(likes[0].name.length <= 3 ? likes[0].name.length : 2)),likeQuickView,`color: hsl(${Math.abs(hashCode(likes[0].name)) % 360},50%,50%)`);
create("span",false,", ",likeQuickView);
let name2 = create("span",false,likes[1].name.slice(0,(likes[1].name.length <= 3 ? likes[1].name.length : 2)),likeQuickView,`color: hsl(${Math.abs(hashCode(likes[1].name)) % 360},50%,50%)`);
create("span",false," & ",likeQuickView);
let name3 = create("span",false,likes[2].name.slice(0,(likes[2].name.length <= 3 ? likes[1].name.length : 2)),likeQuickView,`color: hsl(${Math.abs(hashCode(likes[2].name)) % 360},50%,50%)`);
name1.onmouseover = function(){
name1.innerText = likes[0].name;
}
name2.onmouseover = function(){
name2.innerText = likes[1].name;
}
name3.onmouseover = function(){
name3.innerText = likes[2].name;
}
}
else if(likes.length === 4){
likes.forEach(like => {
let name = create("span",false,like.name.slice(0,(like.name.length <= 3 ? like.name.length : 2)),likeQuickView,`color: hsl(${Math.abs(hashCode(like.name)) % 360},50%,50%)`);
create("span",false,", ",likeQuickView);
name.onmouseover = function(){
name.innerText = like.name;
}
});
likeQuickView.lastChild.remove();
}
else if(likes.length === 5 || likes.length === 6){
likes.forEach(like => {
let name = create("span",false,like.name.slice(0,2),likeQuickView,`color: hsl(${Math.abs(hashCode(like.name)) % 360},50%,50%)`);
create("span",false," ",likeQuickView);
name.onmouseover = function(){
name.innerText = like.name;
}
name.onmouseout = function(){
name.innerText = like.name.slice(0,2);
}
});
likeQuickView.lastChild.remove();
}
else if(likes.length < 12){
likes.forEach(like => {
let name = create("span",false,like.name[0],likeQuickView,`color: hsl(${Math.abs(hashCode(like.name)) % 360},50%,50%)`);
create("span",false," ",likeQuickView);
name.onmouseover = function(){
name.innerText = like.name;
}
name.onmouseout = function(){
name.innerText = like.name[0];
}
});
likeQuickView.lastChild.remove();
}
else if(likes.length <= 20){
likes.forEach(like => {
let name = create("span",false,like.name[0],likeQuickView,`color: hsl(${Math.abs(hashCode(like.name)) % 360},50%,50%)`);
name.onmouseover = function(){
name.innerText = " " + like.name + " ";
}
name.onmouseout = function(){
name.innerText = like.name[0];
}
});
}
};
likeify(activity.likes,likeQuickView);
likeWrap.onclick = function(){
authAPIcall(
"mutation($id:Int){ToggleLike(id:$id,type:" + type.toUpperCase() + "){id}}",
{id: activity.id},
data => {}
);
if(likeWrap.classList.contains("hohILikeThis")){
activity.likes.splice(activity.likes.findIndex(user => user.name === whoAmI),1);
if(activity.likes.length === 0){
likeCount.innerText = " "
}
else{
likeCount.innerText = activity.likes.length
}
}
else{
activity.likes.push({name: whoAmI});
likeCount.innerText = activity.likes.length;
};
likeWrap.classList.toggle("hohILikeThis");
likeWrap.title = activity.likes.map(a => a.name).join("\n");
likeify(activity.likes,likeQuickView);
};
replyWrap.onclick = function(){
if(act.querySelector(".replies")){
act.lastChild.remove();
}
else if(type === "thread"){
window.location = "https://anilist.co/forum/thread/" + activity.id + "/";//remove when implemented
let createReplies = data => {
let replies = create("div","replies",false,act);
data.data.threadReplies.forEach(function(repy){
});
};
//generalAPIcall(``,{},createReplies)
}
else{
let createReplies = function(){
let replies = create("div","replies",false,act);
activity.replies.forEach(reply => {
let rep = create("div","reply",false,replies);
let ndiff = NOW() - (new Date(reply.createdAt * 1000)).valueOf();
let time = create("span",["time","hohMonospace"],formatTime(Math.round(ndiff/1000),"short"),rep,"width:50px;position:absolute;left:1px;top:2px;");
time.title = (new Date(activity.createdAt * 1000)).toLocaleString();
let user = create("a",["link","newTab"],reply.user.name,rep,"margin-left: 60px;");
user.href = "/user/" + reply.user.name + "/";
let text = create("div","status",false,rep,"padding-bottom:10px;margin-left:5px;max-width:100%;");
if(useScripts.termsFeedNoImages && !activity.renderingPermission){
let cleanText = reply.text.replace(//g,img => {
let link = img.match(//)[2];
return "[" + (link.length > 200 ? link.slice(0,200) + "…" : link) + "]";
})
text.innerHTML = cleanText;
}
else{
text.innerHTML = reply.text;
}
Array.from(text.querySelectorAll(".youtube")).forEach(ytLink => {
create("a",["link","newTab"],"Youtube " + ytLink.id,ytLink)
.href = "https://www.youtube.com/watch?v=" + ytLink.id;
});
let actions = create("div","actions",false,rep,"position:absolute;text-align:right;right:4px;bottom:0px;");
let likeWrap = create("span",["action","hohLikes"],false,actions,"display:inline-block;min-width:35px;margin-left:2px");
likeWrap.title = reply.likes.map(a => a.name).join("\n");
let likeCount = create("span","count",(reply.likes.length ? reply.likes.length : " "),likeWrap);
let heart = create("span",false,"♥",likeWrap,"position:relative;");
let likeQuickView = create("div","hohLikeQuickView",false,heart,"position:absolute;bottom:0px;left:30px;font-size:70%;white-space:nowrap;");
likeWrap.style.cursor = "pointer";
if(reply.likes.some(like => like.name === whoAmI)){
likeWrap.classList.add("hohILikeThis");
};
likeify(reply.likes,likeQuickView);
likeWrap.onclick = function(){
authAPIcall(
"mutation($id:Int){ToggleLike(id:$id,type:ACTIVITY_REPLY){id}}",
{id: reply.id},
data => {}
);
if(likeWrap.classList.contains("hohILikeThis")){
reply.likes.splice(reply.likes.findIndex(user => user.name === whoAmI),1);
if(reply.likes.length === 0){
likeCount.innerText = " ";
}
else{
likeCount.innerText = reply.likes.length;
};
}
else{
reply.likes.push({name: whoAmI});
likeCount.innerText = reply.likes.length;
};
likeWrap.classList.toggle("hohILikeThis");
likeWrap.title = reply.likes.map(a => a.name).join("\n");
likeify(reply.likes,likeQuickView);
};
});
let statusInput = create("div",false,false,replies);
let inputArea = create("textarea",false,false,statusInput,"width: 99%;border-width: 1px;padding: 4px;border-radius: 2px;color: rgb(159, 173, 189);resize: vertical;");
let cancelButton = create("button",["hohButton","button"],"Cancel",statusInput,"background:rgb(31,35,45);display:none;color: rgb(159, 173, 189);");
let publishButton = create("button",["hohButton","button"],"Publish",statusInput,"display:none;");
inputArea.placeholder = "Write a reply...";
inputArea.onfocus = function(){
cancelButton.style.display = "inline";
publishButton.style.display = "inline";
};
cancelButton.onclick = function(){
inputArea.value = "";
cancelButton.style.display = "none";
publishButton.style.display = "none";
document.activeElement.blur();
};
publishButton.onclick = function(){
loading.innerText = "Publishing reply...";
authAPIcall(
`mutation($text: String,$activityId: Int){
SaveActivityReply(text: $text,activityId: $activityId){
id
user{name}
likes{name}
text(asHtml: true)
createdAt
}
}`,
{text: inputArea.value,activityId: activity.id},
data => {
loading.innerText = "";
activity.replies.push(data.data.SaveActivityReply);
replyCount.innerText = activity.replies.length;
act.lastChild.remove();
createReplies();
}
);
inputArea.value = "";
cancelButton.style.display = "none";
publishButton.style.display = "none";
document.activeElement.blur();
};
};createReplies();
};
};
let status;
if(activity.type === "TEXT" || activity.type === "MESSAGE"){
status = create("div",false,false,content,"padding-bottom:10px;width:95%;overflow-wrap:anywhere;");
if(useScripts.termsFeedNoImages){
let cleanText = activity.text.replace(//g,img => {
let link = img.match(//)[2];
return "[" + (link.length > 200 ? link.slice(0,200) + "…" : link) + "]";
})
status.innerHTML = cleanText;
if(cleanText !== activity.text){
let render = create("a",false,"IMG",act,"position:absolute;top:2px;right:50px;width:10px;cursor:pointer;");
render.onclick = () => {
activity.renderingPermission = true;
status.innerHTML = activity.text;
render.style.display = "none";
}
}
}
else{
status.innerHTML = activity.text;
}
Array.from(status.querySelectorAll(".youtube")).forEach(ytLink => {
create("a",["link","newTab"],ytLink.id,ytLink)
.href = ytLink.id
});
if(activity.user.name === whoAmI && activity.type === "TEXT" && type !== "thread"){
let edit = create("a",false,"Edit",act,"position:absolute;top:2px;right:40px;width:10px;cursor:pointer;font-size:small;color:inherit;");
if(useScripts.termsFeedNoImages){
edit.style.right = "80px"
}
edit.onclick = function(){
loading.innerText = "Loading activity " + activity.id + "...";
if(terms.scrollIntoView){
terms.scrollIntoView({"behavior": "smooth","block": "start"})
}
else{
document.body.scrollTop = document.documentElement.scrollTop = 0
};
authAPIcall(
`query($id: Int){
Activity(id: $id){
... on TextActivity{
text(asHtml: false)
}
}
}`,
{id: activity.id},
data => {
if(!data){
onlySpecificActivity = false;
loading.innerText = "Failed to load activity";
}
inputArea.focus();
onlySpecificActivity = activity.id;
loading.innerText = "Editing activity " + activity.id;
inputArea.value = data.data.Activity.text;
}
)
}
}
act.classList.add("text");
actions.style.right = "21px";
actions.style.bottom = "4px";
}
else{
status = create("span",false," " + activity.status,content);
if(activity.progress){
create("span",false," " + activity.progress + " of",content);
};
let title = activity.media.title.romaji;
if(useScripts.titleLanguage === "NATIVE" && activity.media.title.native){
title = activity.media.title.native;
}
else if(useScripts.titleLanguage === "ENGLISH" && activity.media.title.english){
title = activity.media.title.english;
};
dataMedia.add(title);
if(aliases.has(activity.media.id)){
title = aliases.get(activity.media.id)
}
let media = create("a",["link","newTab"]," " + title,content);
media.href = "/" + activity.media.type.toLowerCase() + "/" + activity.media.id + "/" + safeURL(title) + "/";
if(activity.media.type === "MANGA" && useScripts.CSSgreenManga){
media.style.color = "rgb(var(--color-green))";
};
act.classList.add("list");
actions.style.right = "21px";
actions.style.top = "2px";
if(useScripts.statusBorder){
let blockerMap = {
"plans": "PLANNING",
"watched": "CURRENT",
"read": "CURRENT",
"completed": "COMPLETED",
"paused": "PAUSED",
"dropped": "DROPPED",
"rewatched": "REPEATING",
"reread": "REPEATING"
};
let status = blockerMap[
Object.keys(blockerMap).find(
key => activity.status.includes(key)
)
]
if(status === "CURRENT"){
//nothing
}
else if(status === "COMPLETED"){
act.style.borderLeftWidth = "3px";
act.style.marginLeft = "-2px";
if(useScripts.CSSgreenManga && activity.media.type === "ANIME"){
act.style.borderLeftColor = "rgb(var(--color-blue))";
}
else{
act.style.borderLeftColor = "rgb(var(--color-green))";
}
}
else{
act.style.borderLeftWidth = "3px";
act.style.marginLeft = "-2px";
act.style.borderLeftColor = distributionColours[status];
}
}
};
let link = create("a",["link","newTab"],false,act,"position:absolute;top:2px;right:4px;width:10px;");
link.innerHTML = svgAssets.link;
if(type === "thread"){
link.href = "https://anilist.co/forum/thread/" + activity.id + "/";
}
else{
link.href = "https://anilist.co/" + type + "/" + activity.id + "/";
}
if(activity.user.name === whoAmI){
let deleteActivity = create("span","hohDeleteActivity",svgAssets.cross,act);
deleteActivity.title = "Delete";
deleteActivity.onclick = function(){
authAPIcall(
"mutation($id: Int){Delete" + capitalize(type) + "(id: $id){deleted}}",
{id: activity.id},
function(data){
if(data.data.DeleteActivity.deleted){
act.style.display = "none"
}
}
)
}
}
dataUsers.add(activity.user.name);
activity.replies.forEach(reply => {
dataUsers.add(reply.user.name);
(reply.text.match(/@(.*?) {
dataUsers.add(user.slice(1,user.length-1))
})
})
});
if(terms.scrollIntoView){
terms.scrollIntoView({"behavior": "smooth","block": "start"})
}
else{
document.body.scrollTop = document.documentElement.scrollTop = 0;
};
while(dataUsersList.childElementCount){
dataUsersList.lastChild.remove();
}
dataUsers.forEach(user => {
create("option",false,false,dataUsersList)
.value = user;
});
while(dataMediaList.childElementCount){
dataMediaList.lastChild.remove();
}
dataMedia.forEach(media => {
create("option",false,false,dataMediaList)
.value = media;
});
};
let requestPage = function(npage,userID){
page = npage;
let types = [];
if(!onlyUser.checked){
types.push("MESSAGE");
}
if(onlyStatus.checked){
types.push("ANIME_LIST","MANGA_LIST");
};
let specificUser = onlyUserInput.value || whoAmI;
if(onlyUser.checked && !userID){
generalAPIcall("query($name:String){User(name:$name){id}}",{name: specificUser},function(data){
if(data){
requestPage(npage,data.data.User.id);
}
else{
loading.innerText = "Not Found";
}
},"hohIDlookup" + specificUser.toLowerCase());
return;
};
let requestTime = NOW();
if(onlyForum.checked){
authAPIcall(
`
query($page: Int){
Page(page: $page){
threads(sort:REPLIED_AT_DESC${(onlyUser.checked ? ",userId: " + userID : "")}${onlyMedia.checked && onlyMediaResult.id ? ",mediaCategoryId: " + onlyMediaResult.id : ""}){
id
createdAt
user{name}
text:body(asHtml: true)
likes{name}
title
replyCount
}
}
Viewer{unreadNotificationCount}
}`,
{page: npage},
function(data){
buildPage(data.data.Page.threads.map(thread => {
thread.type = "TEXT";
thread.replies = [];
thread.text = "" + thread.title + "
" + thread.text;
return thread
}).filter(thread => thread.replyCount || !onlyReplies.checked),"thread",requestTime);
if(data.data.Viewer){
notiLink.innerText = data.data.Viewer.unreadNotificationCount;
if(data.data.Viewer.unreadNotificationCount){
notiLink.title = data.data.Viewer.unreadNotificationCount + " unread notifications";
}
else{
notiLink.title = "no unread notifications";
}
};
}
);
}
else if(onlyReviews.checked){
authAPIcall(
`
query($page: Int){
Page(page: $page,perPage: 20){
reviews(sort:CREATED_AT_DESC${(onlyUser.checked ? ",userId: " + userID : "")}${onlyMedia.checked && onlyMediaResult.id ? ",mediaId: " + onlyMediaResult.id : ""}){
id
createdAt
user{name}
media{
id
type
title{romaji native english}
}
summary
body(asHtml: true)
rating
ratingAmount
}
}
Viewer{unreadNotificationCount}
}`,
{page: npage},
function(data){
buildPage(data.data.Page.reviews.map(review => {
review.type = "TEXT";
review.likes = [];
review.replies = [{
id: review.id,
user: review.user,
likes: [],
text: review.body,
createdAt: review.createdAt
}];
review.text = review.summary
return review
}),"review",requestTime);
if(data.data.Viewer){
notiLink.innerText = data.data.Viewer.unreadNotificationCount;
if(data.data.Viewer.unreadNotificationCount){
notiLink.title = data.data.Viewer.unreadNotificationCount + " unread notifications";
}
else{
notiLink.title = "no unread notifications";
}
};
}
);
}
else{
authAPIcall(
`
query($page: Int,$types: [ActivityType]){
Page(page: $page){
activities(${(onlyUser.checked || onlyGlobal.checked ? "" : "isFollowing: true,")}sort: ID_DESC,type_not_in: $types${(onlyReplies.checked ? ",hasReplies: true" : "")}${(onlyUser.checked ? ",userId: " + userID : "")}${(onlyGlobal.checked ? ",hasRepliesOrTypeText: true" : "")}${onlyMedia.checked && onlyMediaResult.id ? ",mediaId: " + onlyMediaResult.id : ""}){
... on MessageActivity{
id
type
createdAt
user:messenger{name}
text:message(asHtml: true)
likes{name}
replies{
id
user{name}
likes{name}
text(asHtml: true)
createdAt
}
}
... on TextActivity{
id
type
createdAt
user{name}
text(asHtml: true)
likes{name}
replies{
id
user{name}
likes{name}
text(asHtml: true)
createdAt
}
}
... on ListActivity{
id
type
createdAt
user{name}
status
progress
media{
id
type
title{romaji native english}
}
likes{name}
replies{
id
user{name}
likes{name}
text(asHtml: true)
createdAt
}
}
}
}
Viewer{unreadNotificationCount}
}`,
{page: npage,types:types},
function(data){
buildPage(data.data.Page.activities,"activity",requestTime);
if(data.data.Viewer){
notiLink.innerText = data.data.Viewer.unreadNotificationCount;
if(data.data.Viewer.unreadNotificationCount){
notiLink.title = data.data.Viewer.unreadNotificationCount + " unread notifications";
}
else{
notiLink.title = "no unread notifications";
}
};
}
);
}
};
requestPage(page);
let setInputs = function(){
statusInputTitle.style.display = "none";
if(onlyReviews.checked){
inputArea.placeholder = "Writing reviews not supported yet...";
publishButton.innerText = "Publish";
}
else if(onlyForum.checked){
inputArea.placeholder = "Write a forum post...";
statusInputTitle.style.display = "block";
publishButton.innerText = "Publish";
}
else if(onlyUser.checked && onlyUserInput.value && onlyUserInput.value.toLowerCase() !== whoAmI.toLowerCase()){
inputArea.placeholder = "Write a message...";
publishButton.innerText = "Send";
}
else{
inputArea.placeholder = "Write a status...";
publishButton.innerText = "Publish";
}
};
topPrevious.onclick = function(){
loading.innerText = "Loading...";
if(page === 1){
requestPage(1);
}
else{
requestPage(page - 1);
};
};
topNext.onclick = function(){
loading.innerText = "Loading...";
requestPage(page + 1);
};
onlyGlobal.onchange = function(){
loading.innerText = "Loading...";
statusInputTitle.style.display = "none";
inputArea.placeholder = "Write a status...";
onlyUser.checked = false;
onlyForum.checked = false;
onlyReviews.checked = false;
requestPage(1);
};
onlyStatus.onchange = function(){
loading.innerText = "Loading...";
onlyForum.checked = false;
onlyReviews.checked = false;
onlyMedia.checked = false;
requestPage(1);
};
onlyReplies.onchange = function(){
loading.innerText = "Loading...";
onlyReviews.checked = false;
requestPage(1);
};
onlyUser.onchange = function(){
setInputs();
loading.innerText = "Loading...";
onlyGlobal.checked = false;
requestPage(1);
};
onlyForum.onchange = function(){
setInputs();
loading.innerText = "Loading...";
onlyGlobal.checked = false;
onlyStatus.checked = false;
onlyReviews.checked = false;
requestPage(1);
};
onlyMedia.onchange = function(){
setInputs();
loading.innerText = "Loading...";
requestPage(1);
};
onlyReviews.onchange = function(){
setInputs();
onlyGlobal.checked = false;
onlyStatus.checked = false;
onlyForum.checked = false;
onlyReplies.checked = false;
loading.innerText = "Loading...";
requestPage(1);
}
let oldOnlyUser = "";
onlyUserInput.onfocus = function(){
oldOnlyUser = onlyUserInput.value;
};
let oldOnlyMedia = "";
onlyMediaInput.onfocus = function(){
oldOnlyMedia = onlyMediaInput.value;
};
onlyMediaInput.onblur = function(){
if(onlyMediaInput.value === oldOnlyMedia){
return;
}
if(onlyMediaInput.value === ""){
while(mediaDisplayResults.childElementCount){
mediaDisplayResults.lastChild.remove();
};
onlyMediaResult.id = false;
}
else{
if(!mediaDisplayResults.childElementCount){
create("span",false,"Searching...",mediaDisplayResults);
}
generalAPIcall(`
query($search: String){
Page(page:1,perPage:5){
media(search:$search,sort:SEARCH_MATCH){
title{romaji}
id
type
}
}
}`,
{search: onlyMediaInput.value},
function(data){
while(mediaDisplayResults.childElementCount){
mediaDisplayResults.lastChild.remove();
}
data.data.Page.media.forEach((media,index) => {
let result = create("span",["hohSearchResult",media.type.toLowerCase()],media.title.romaji,mediaDisplayResults);
if(index === 0){
result.classList.add("selected");
onlyMediaResult.id = media.id;
onlyMediaResult.type = media.type;
}
result.onclick = function(){
mediaDisplayResults.querySelector(".selected").classList.toggle("selected");
result.classList.add("selected");
onlyMediaResult.id = media.id;
onlyMediaResult.type = media.type;
onlyMedia.checked = true;
onlyStatus.checked = false;
loading.innerText = "Loading...";
requestPage(1);
}
});
if(data.data.Page.media.length){
onlyMedia.checked = true;
onlyStatus.checked = false;
loading.innerText = "Loading...";
requestPage(1);
}
else{
create("span",false,"No results found",mediaDisplayResults);
onlyMediaResult.id = false;
}
}
)
};
};
onlyUserInput.onblur = function(){
if(onlyForum.checked){
inputArea.placeholder = "Write a forum post...";
publishButton.innerText = "Publish";
}
else if(
(onlyUser.checked && onlyUserInput.value && onlyUserInput.value.toLowerCase() !== whoAmI.toLowerCase())
|| (oldOnlyUser !== onlyUserInput.value && onlyUserInput.value !== "")
){
inputArea.placeholder = "Write a message...";
publishButton.innerText = "Send";
}
else{
inputArea.placeholder = "Write a status...";
publishButton.innerText = "Publish";
}
if(oldOnlyUser !== onlyUserInput.value && onlyUserInput.value !== ""){
loading.innerText = "Loading...";
onlyUser.checked = true;
requestPage(1);
}
else if(onlyUser.checked && oldOnlyUser !== onlyUserInput.value){
loading.innerText = "Loading...";
requestPage(1);
}
};
onlyUserInput.addEventListener("keyup",function(event){
if(event.key === "Enter"){
onlyUserInput.blur();
}
});
onlyMediaInput.addEventListener("keyup",function(event){
if(event.key === "Enter"){
onlyMediaInput.blur();
}
});
inputArea.onfocus = function(){
cancelButton.style.display = "inline";
publishButton.style.display = "inline";
};
cancelButton.onclick = function(){
inputArea.value = "";
cancelButton.style.display = "none";
publishButton.style.display = "none";
loading.innerText = "";
onlySpecificActivity = false;
document.activeElement.blur();
};
publishButton.onclick = function(){
if(onlyForum.checked){
alert("Sorry, not implemented yet");
//loading.innerText = "Publishing forum post...";
return;
}
else if(onlyReviews.checked){
alert("Sorry, not implemented yet");
//loading.innerText = "Publishing review...";
return;
}
else if(onlySpecificActivity){
loading.innerText = "Publishing...";
authAPIcall(
"mutation($text: String,$id: Int){SaveTextActivity(id: $id,text: $text){id}}",
{text: inputArea.value,id: onlySpecificActivity},
function(data){
onlySpecificActivity = false;
requestPage(1);
}
);
}
else if(onlyUser.checked && onlyUserInput.value && onlyUserInput.value.toLowerCase() !== whoAmI.toLowerCase()){
loading.innerText = "Sending Message...";
generalAPIcall("query($name:String){User(name:$name){id}}",{name: onlyUserInput.value},function(data){
if(data){
authAPIcall(
"mutation($text: String,$recipientId: Int){SaveMessageActivity(message: $text,recipientId: $recipientId){id}}",
{
text: inputArea.value,
recipientId: data.data.User.id
},
function(data){
requestPage(1);
}
)
}
else{
loading.innerText = "Not Found";
}
},"hohIDlookup" + onlyUserInput.value.toLowerCase());
}
else{
loading.innerText = "Publishing...";
authAPIcall(
"mutation($text: String){SaveTextActivity(text: $text){id}}",
{text: inputArea.value},
function(data){
requestPage(1);
}
);
}
inputArea.value = "";
cancelButton.style.display = "none";
publishButton.style.display = "none";
document.activeElement.blur();
};
let sideBarContent = create("div","sidebar",false,feed,"position:absolute;left:20px;top:200px;max-width:150px;");
let buildPreview = function(data){
if(!data){
return;
}
while(sideBarContent.childElementCount){
sideBarContent.lastChild.remove();
};
let mediaLists = data.data.Page.mediaList.map(mediaList => {
if(aliases.has(mediaList.media.id)){
mediaList.media.title.userPreferred = aliases.get(mediaList.media.id)
}
return mediaList
});
mediaLists.slice(0,20).forEach(mediaList => {
let mediaEntry = create("div",false,false,sideBarContent,"border-bottom: solid;border-bottom-width: 1px;margin-bottom: 10px;border-radius: 3px;padding: 2px;");
create("a","link",mediaList.media.title.userPreferred,mediaEntry,"min-height:40px;display:inline-block;")
.href = "/anime/" + mediaList.media.id + "/" + safeURL(mediaList.media.title.userPreferred);
let progress = create("div",false,false,mediaEntry,"font-size: small;");
create("span",false,"Progress: ",progress);
let number = create("span",false,mediaList.progress + (mediaList.media.episodes ? "/" + mediaList.media.episodes : ""),progress);
let plusProgress = create("span",false,"+",progress,"padding-left:5px;padding-right:5px;cursor:pointer;");
let isBlocked = false;
plusProgress.onclick = function(e){
if(isBlocked){
return;
};
if(mediaList.media.episodes){
if(mediaList.progress < mediaList.media.episodes){
mediaList.progress++;
number.innerText = mediaList.progress + (mediaList.media.episodes ? "/" + mediaList.media.episodes : "");
isBlocked = true;
setTimeout(function(){
isBlocked = false;
},300);
if(mediaList.progress === mediaList.media.episodes){
plusProgress.innerText = "";
if(mediaList.status === "REWATCHING"){//don't overwrite the existing end date
authAPIcall(
`mutation($progress: Int,$id: Int){
SaveMediaListEntry(progress: $progress,id:$id,status:COMPLETED){id}
}`,
{id: mediaList.id,progress: mediaList.progress},
data => {}
);
}
else{
authAPIcall(
`mutation($progress: Int,$id: Int,$date:FuzzyDateInput){
SaveMediaListEntry(progress: $progress,id:$id,status:COMPLETED,completedAt:$date){id}
}`,
{
id: mediaList.id,
progress: mediaList.progress,
date: {
year: (new Date()).getUTCFullYear(),
month: (new Date()).getUTCMonth() + 1,
day: (new Date()).getUTCDate(),
}
},
data => {}
);
};
mediaEntry.style.backgroundColor = "rgba(0,200,0,0.1)";
}
else{
authAPIcall(
`mutation($progress: Int,$id: Int){
SaveMediaListEntry(progress: $progress,id:$id){id}
}`,
{id: mediaList.id,progress: mediaList.progress},
data => {}
);
}
localStorage.setItem("hohListPreview",JSON.stringify(data));
}
}
else{
mediaList.progress++;
number.innerText = mediaList.progress + (mediaList.media.episodes ? "/" + mediaList.media.episodes : "");
isBlocked = true;
setTimeout(function(){
isBlocked = false;
},300);
authAPIcall(
`mutation($progress: Int,$id: Int){
SaveMediaListEntry(progress: $progress,id:$id){id}
}`,
{id: mediaList.id,progress: mediaList.progress},
data => {}
);
localStorage.setItem("hohListPreview",JSON.stringify(data));
};
e.stopPropagation();
e.preventDefault();
return false
}
});
};
authAPIcall(
`query($name: String){
Page(page:1){
mediaList(type:ANIME,status_in:[CURRENT,REPEATING],userName:$name,sort:UPDATED_TIME_DESC){
id
priority
scoreRaw: score(format: POINT_100)
progress
status
media{
id
episodes
coverImage{large color}
title{userPreferred}
nextAiringEpisode{episode timeUntilAiring}
}
}
}
}`,{name: whoAmI},function(data){
localStorage.setItem("hohListPreview",JSON.stringify(data));
buildPreview(data,true);
}
);
buildPreview(JSON.parse(localStorage.getItem("hohListPreview")),false);
}
function scoreOverviewFixer(){
if(!document.URL.match(/^https:\/\/anilist\.co\/(anime|manga)\//)){
return;
}
let overview = document.querySelector(".media .overview");
if(!overview){
setTimeout(scoreOverviewFixer,300);
return;
}
let follows = overview.querySelectorAll(".follow");
if(follows.length){
follows.forEach(el => {
scoreColors(el);
});
}
else{
setTimeout(scoreOverviewFixer,300);
}
}
function meanScoreBack(){
let URLstuff = location.pathname.match(/^\/user\/(.*?)\/?$/);
const query = `
query($userName: String) {
User(name: $userName){
statistics{
anime{
episodesWatched
meanScore
}
manga{
volumesRead
meanScore
}
}
}
}`;
let variables = {
userName: decodeURIComponent(URLstuff[1])
}
generalAPIcall(query,variables,function(data){
if(!data){
return;
}
let adder = function(){
if(!location.pathname.match(/^\/user\/(.*?)\/?$/)){
return;
}
let possibleStatsWrap = document.querySelectorAll(".stats-wrap .stats-wrap");
if(possibleStatsWrap.length){
if(possibleStatsWrap.length === 2 && possibleStatsWrap[0].childElementCount === 3){
if(data.data.User.statistics.anime.meanScore){
let statAnime = create("div","stat",false,possibleStatsWrap[0]);
create("div","value",data.data.User.statistics.anime.episodesWatched,statAnime);
create("div","label","Total Episodes",statAnime);
let totalDays = possibleStatsWrap[0].children[1].children[0].innerText;
possibleStatsWrap[0].children[1].remove();
possibleStatsWrap[0].parentNode.querySelector(".milestone:nth-child(2)").innerText = totalDays + " Days Watched";
possibleStatsWrap[0].parentNode.classList.add("hohMilestones");
};
if(data.data.User.statistics.manga.meanScore){
let statManga = create("div","stat",false,possibleStatsWrap[1]);
create("div","value",data.data.User.statistics.manga.volumesRead,statManga);
create("div","label","Total Volumes",statManga);
let totalChapters = possibleStatsWrap[1].children[1].children[0].innerText;
possibleStatsWrap[1].children[1].remove();
possibleStatsWrap[1].parentNode.querySelector(".milestone:nth-child(2)").innerText = totalChapters + " Chapters Read";
possibleStatsWrap[1].parentNode.classList.add("hohMilestones");
};
}
else if(possibleStatsWrap[0].innerText.includes("Total Manga")){
if(data.data.User.statistics.manga.meanScore){
let statManga = create("div","stat",false,possibleStatsWrap[0]);
create("div","value",data.data.User.statistics.manga.volumesRead,statManga);
create("div","label","Total Volumes",statManga);
let totalChapters = possibleStatsWrap[0].children[1].children[0].innerText;
possibleStatsWrap[0].children[1].remove();
possibleStatsWrap[0].parentNode.querySelector(".milestone:nth-child(2)").innerText = totalChapters + " Chapters Read";
possibleStatsWrap[0].parentNode.classList.add("hohMilestones");
};
}
}
else{
setTimeout(adder,200);
}
};adder();
},"hohMeanScoreBack" + variables.userName,60*1000);
}
function betterReviewRatings(){
if(!location.pathname.match(/\/home/)){
return;
}
let reviews = document.querySelectorAll(".review-card .el-tooltip.votes");
if(!reviews.length){
setTimeout(betterReviewRatings,500);
return;
}
reviews.forEach(likeElement => {
likeElement.dispatchEvent(new Event("mouseenter"));
likeElement.dispatchEvent(new Event("mouseleave"));
});
setTimeout(function(){
reviews.forEach(likeElement => {
let likeExtra = document.getElementById(likeElement.attributes["aria-describedby"].value);
if(likeExtra){
let matches = likeExtra.innerText.match(/out of (\d+)/);
if(matches){
likeElement.childNodes[1].textContent += "/" + matches[1];
}
}
likeElement.style.bottom = "4px";
likeElement.style.right = "7px";
})
},200);
}
function betterListPreview(){
let errorHandler = function(e){
console.error(e);
console.warn("Alternative list preview failed. Trying to bring back the native one");
let hohListPreviewToRemove = document.getElementById("hohListPreview");
if(hohListPreviewToRemove){
hohListPreviewToRemove.remove();
};
document.querySelectorAll(".list-preview-wrap").forEach(wrap => {
wrap.style.display = "block";
});
}
try{//it's complex, and could go wrong. Furthermore, we want a specific behavour when it fails, namely bringing back the native preview
let hohListPreview = document.getElementById("hohListPreview");
if(hohListPreview){
return;
};
let buildPreview = function(data,overWrite){try{
if(!data){
return;
}
if(!hohListPreview){
overWrite = true;
let listPreviews = document.querySelectorAll(".list-previews h2");
if(!listPreviews.length){
setTimeout(function(){buildPreview(data)},200);
return;
};
hohListPreview = create("div","#hohListPreview");
listPreviews[0].parentNode.parentNode.parentNode.parentNode.insertBefore(hohListPreview,listPreviews[0].parentNode.parentNode.parentNode);
listPreviews.forEach(heading => {
if(!heading.innerText.includes("Manga")){
heading.parentNode.parentNode.style.display = "none";
}
});
};
if(overWrite){
let mediaLists = data.data.Page.mediaList.map((mediaList,index) => {
mediaList.index = index;
if(aliases.has(mediaList.media.id)){
mediaList.media.title.userPreferred = aliases.get(mediaList.media.id)
}
return mediaList
});
let notAiring = mediaLists.filter(
mediaList => !mediaList.media.nextAiringEpisode
)
let airing = mediaLists.filter(
mediaList => mediaList.media.nextAiringEpisode
).map(
mediaList => {
mediaList.points = 100/(mediaList.index + 1) + mediaList.priority/10 + (mediaList.scoreRaw || 60)/10;
if(mediaList.progress === mediaList.media.nextAiringEpisode.episode - 1){
mediaList.points -= 100/(mediaList.index + 1);
}
if(mediaList.media.nextAiringEpisode.timeUntilAiring < 60*60*24){
mediaList.points += 1;
if(mediaList.progress === mediaList.media.nextAiringEpisode.episode - 1){
mediaList.points += 1;
}
}
if(mediaList.media.nextAiringEpisode.timeUntilAiring < 60*60*12){
mediaList.points += 1;
if(mediaList.progress === mediaList.media.nextAiringEpisode.episode - 1){
mediaList.points += 2;
}
}
if(mediaList.media.nextAiringEpisode.timeUntilAiring < 60*60*3){
mediaList.points += 1;
if(mediaList.progress === mediaList.media.nextAiringEpisode.episode - 1){
mediaList.points += 2;
}
}
if(mediaList.media.nextAiringEpisode.timeUntilAiring < 60*60*1){
mediaList.points += 1;
if(mediaList.progress === mediaList.media.nextAiringEpisode.episode - 1){
mediaList.points += 3;
}
}
if(mediaList.media.nextAiringEpisode.timeUntilAiring < 60*10){
mediaList.points += 1;
if(mediaList.progress === mediaList.media.nextAiringEpisode.episode - 1){
mediaList.points += 5;
}
else if(mediaList.progress === mediaList.media.nextAiringEpisode.episode - 2){
mediaList.points += 2;
}
}
if(mediaList.progress === mediaList.media.nextAiringEpisode.episode - 2){
mediaList.points += 7;
if(mediaList.media.nextAiringEpisode.timeUntilAiring < 60*60*24*7){
if(mediaList.media.nextAiringEpisode.timeUntilAiring > 60*60*24*6){
mediaList.points += 3;
}
if(mediaList.media.nextAiringEpisode.timeUntilAiring > 60*60*24*7 - 60*60*3){
mediaList.points += 3;
}
if(mediaList.media.nextAiringEpisode.timeUntilAiring > 60*60*24*7 - 60*60*1){
mediaList.points += 3;
}
}
}
else if(mediaList.progress === mediaList.media.nextAiringEpisode.episode - 3){
mediaList.points += 2;
if(mediaList.media.nextAiringEpisode.timeUntilAiring < 60*60*24*7){
if(mediaList.media.nextAiringEpisode.timeUntilAiring > 60*60*24*6){
mediaList.points += 1;
}
if(mediaList.media.nextAiringEpisode.timeUntilAiring > 60*60*24*7 - 60*60*3){
mediaList.points += 1;
}
if(mediaList.media.nextAiringEpisode.timeUntilAiring > 60*60*24*7 - 60*60*1){
mediaList.points += 1;
}
}
}
return mediaList;
}
).sort(
(b,a) => a.points - b.points
);
let airingImportant = mediaLists.filter(
(mediaList,index) => mediaList.media.nextAiringEpisode && (
index < 20
|| mediaList.media.nextAiringEpisode.timeUntilAiring < 60*60*4
|| (
mediaList.media.nextAiringEpisode.timeUntilAiring < 60*60*12
&& mediaList.progress === mediaList.media.nextAiringEpisode.episode - 1
)
|| (
mediaList.media.nextAiringEpisode.timeUntilAiring > 60*60*24*6
&& mediaList.media.nextAiringEpisode.timeUntilAiring < 60*60*24*7
&& mediaList.progress === mediaList.media.nextAiringEpisode.episode - 2
)
)
).length;
if(airingImportant > 3){
airingImportant = Math.min(5*Math.ceil((airingImportant - 1)/5),airing.length)
}
while(hohListPreview.childElementCount){
hohListPreview.lastChild.remove();
};
let drawSection = function(list,name,moveExpander){
let airingSection = create("div","list-preview-wrap",false,hohListPreview,"margin-bottom: 20px;");
let airingSectionHeader = create("div","section-header",false,airingSection);
if(name === "Airing"){
create("a","asHeading",name,airingSectionHeader,"font-size: 1.4rem;font-weight: 500;")
.href = "https://anilist.co/airing";
}
else{
create("h2",false,name,airingSectionHeader,"font-size: 1.4rem;font-weight: 500;")
};
if(moveExpander){
airingSectionHeader.appendChild(document.querySelector(".size-toggle"));
};
let airingListPreview = create("div","list-preview",false,airingSection,"display:grid;grid-template-columns: repeat(5,85px);grid-template-rows: repeat(auto-fill,115px);grid-gap: 20px;padding: 20px;background: rgb(var(--color-foreground));");
list.forEach((air,index) => {
let card = create("div",["media-preview-card","small","hohFallback"],false,airingListPreview,"width: 85px;height: 115px;background: rgb(var(--color-foreground));border-radius: 3px;display: inline-grid;");
if(air.media.coverImage.color){
card.style.backgroundColor = air.media.coverImage.color;
};
if(index % 5 > 1){
card.classList.add("info-left");
};
let cover = create("a","cover",false,card,"background-position: 50%;background-repeat: no-repeat;background-size: cover;text-align: center;border-radius: 3px;");
cover.style.backgroundImage = "url(\"" + air.media.coverImage.large + "\")";
cover.href = "/anime/" + air.media.id + "/" + safeURL(air.media.title.userPreferred);
if(air.media.nextAiringEpisode){
let imageText = create("div","image-text",false,cover,"background: rgba(var(--color-overlay),.7);border-radius: 0 0 3px 3px;bottom: 0;color: rgba(var(--color-text-bright),.91);display: inline-block;font-weight: 400;left: 0;letter-spacing: .2px;margin-bottom: 0;position: absolute;transition: .3s;width: 100%;font-size: 1.1rem;line-height: 1.2;padding: 8px;");
let imageTextWrapper = create("div","countdown",false,imageText);
let createCountDown = function(){
while(imageTextWrapper.childElementCount){
imageTextWrapper.lastChild.remove();
}
create("span",false,"Ep " + air.media.nextAiringEpisode.episode + " - ",imageTextWrapper);
if(air.media.nextAiringEpisode.timeUntilAiring <= 0){
create("span",false,"Recently aired",imageTextWrapper);
return;
};
let days = Math.floor(air.media.nextAiringEpisode.timeUntilAiring/(60*60*24));
let hours = Math.floor((air.media.nextAiringEpisode.timeUntilAiring - days*(60*60*24))/3600);
let minutes = Math.round((air.media.nextAiringEpisode.timeUntilAiring - days*(60*60*24) - hours*3600)/60);
if(minutes === 60){
hours++;
minutes = 0;
if(hours === 24){
days++;
hours = 0;
}
};
if(days){
create("span",false,days + "d ",imageTextWrapper);
}
if(hours){
create("span",false,hours + "h ",imageTextWrapper);
}
if(minutes){
create("span",false,minutes + "m",imageTextWrapper);
}
setTimeout(function(){
air.media.nextAiringEpisode.timeUntilAiring -= 60;
createCountDown();
},60*1000);
};createCountDown();
const behind = air.media.nextAiringEpisode.episode - 1 - air.progress;
if(behind > 0){
create("div","behind-accent",false,imageText,"background: rgb(var(--color-red));border-radius: 0 0 2px 2px;bottom: 0;height: 5px;left: 0;position: absolute;transition: .2s;width: 100%;");
};
}
let imageOverlay = create("div","image-overlay",false,cover);
let plusProgress = create("div","plus-progress",air.progress + " +",imageOverlay);
let content = create("div","content",false,card);
if(air.media.nextAiringEpisode){
const behind = air.media.nextAiringEpisode.episode - 1 - air.progress;
if(behind > 0){
let infoHeader = create("div","info-header",false,content,"color: rgb(var(--color-blue));font-size: 1.2rem;font-weight: 500;margin-bottom: 8px;");
create("div",false,behind + " episode" + (behind > 1 ? "s" : "") + " behind",infoHeader);
}
}
let title = create("a","title",air.media.title.userPreferred,content,"font-size: 1.4rem;");
let info = create("div",["info","hasMeter"],false,content,"bottom: 12px;color: rgb(var(--color-text-lighter));font-size: 1.2rem;left: 12px;position: absolute;");
let pBar;
if(air.media.episodes && useScripts.progressBar){
pBar = create("meter",false,false,info);
pBar.value = air.progress;
pBar.min = 0;
pBar.max = air.media.episodes;
};
let progress = create("div",false,"Progress: " + air.progress + (air.media.episodes ? "/" + air.media.episodes : ""),info);
let isBlocked = false;
plusProgress.onclick = function(e){
if(isBlocked){
return;
};
if(air.media.episodes){
if(air.progress < air.media.episodes){
if(useScripts.progressBar){
pBar.value++;
}
air.progress++;
progress.innerText = "Progress: " + air.progress + (air.media.episodes ? "/" + air.media.episodes : "");
isBlocked = true;
setTimeout(function(){
plusProgress.innerText = air.progress + " +";
isBlocked = false;
},300);
if(air.progress === air.media.episodes){
progress.innerText += " Completed";
if(air.status === "REWATCHING"){//don't overwrite the existing end date
authAPIcall(
`mutation($progress: Int,$id: Int){
SaveMediaListEntry(progress: $progress,id:$id,status:COMPLETED){id}
}`,
{id: air.id,progress: air.progress},
data => {}
);
}
else{
authAPIcall(
`mutation($progress: Int,$id: Int,$date:FuzzyDateInput){
SaveMediaListEntry(progress: $progress,id:$id,status:COMPLETED,completedAt:$date){id}
}`,
{
id: air.id,
progress: air.progress,
date: {
year: (new Date()).getUTCFullYear(),
month: (new Date()).getUTCMonth() + 1,
day: (new Date()).getUTCDate(),
}
},
data => {}
);
}
}
else{
authAPIcall(
`mutation($progress: Int,$id: Int){
SaveMediaListEntry(progress: $progress,id:$id){id}
}`,
{id: air.id,progress: air.progress},
data => {}
);
}
localStorage.setItem("hohListPreview",JSON.stringify(data));
}
}
else{
air.progress++;
plusProgress.innerText = air.progress + " +";
isBlocked = true;
setTimeout(function(){
plusProgress.innerText = air.progress + " +";
isBlocked = false;
},300);
authAPIcall(
`mutation($progress: Int,$id: Int){
SaveMediaListEntry(progress: $progress,id:$id){id}
}`,
{id: air.id,progress: air.progress},
data => {}
);
localStorage.setItem("hohListPreview",JSON.stringify(data));
};
if(air.media.nextAiringEpisode){
if(air.progress === air.media.nextAiringEpisode - 1){
if(card.querySelector(".behind-accent")){
card.querySelector(".behind-accent").remove()
}
}
}
e.stopPropagation();
e.preventDefault();
return false
}
let fallback = create("span","hohFallback",air.media.title.userPreferred,card,"background-color: rgb(var(--color-foreground),0.6);padding: 3px;border-radius: 3px;");
if(useScripts.titleLanguage === "ROMAJI"){
fallback.innerHTML = air.media.title.userPreferred.replace(/\S{3}(a|☆|\-|e|i|ou|(o|u)(?!u|\s)|n(?!a|e|i|o|u))(?)/gi,m => m + "");
}
});
};
if(airingImportant > 3){
drawSection(
airing.slice(0,airingImportant),"Airing",true
);
drawSection(
notAiring.slice(0,5*Math.ceil((20 - airingImportant)/5)),"Anime in Progress"
);
}
else{
let remainderAiring = airing.slice(0,airingImportant).filter(air => air.index >= 20);
drawSection(mediaLists.slice(0,20 - remainderAiring.length).concat(remainderAiring),"Anime in Progress",true);
}
}
}catch(e){errorHandler(e)}}
authAPIcall(
`query($name: String){
Page(page:1){
mediaList(type:ANIME,status_in:[CURRENT,REPEATING],userName:$name,sort:UPDATED_TIME_DESC){
id
priority
scoreRaw: score(format: POINT_100)
progress
status
media{
id
episodes
coverImage{large color}
title{userPreferred}
nextAiringEpisode{episode timeUntilAiring}
}
}
}
}`,{name: whoAmI},function(data){
localStorage.setItem("hohListPreview",JSON.stringify(data));
buildPreview(data,true);
}
);
buildPreview(JSON.parse(localStorage.getItem("hohListPreview")),false);
}
catch(e){
errorHandler(e);
}
}
let urlChangedDependence = false;
if(useScripts.dropdownOnHover && whoAmI){
let addMouseover = function(){
let navThingy = document.querySelector(".nav .user .el-dropdown-link");
if(navThingy){
navThingy.onmouseover = function(){
let controls = document.getElementById(navThingy.attributes["aria-controls"].value);
if(!controls || controls.style.display === "none"){
navThingy.click();
}
}
}
else{
setTimeout(addMouseover,500);
}
};addMouseover();
}
if(useScripts.CSSverticalNav && whoAmI && !useScripts.mobileFriendly){
let addMouseover = function(){
let navThingy = document.querySelector(`.nav .links .link[href^="/user/"]`);
if(navThingy){
navThingy.style.position = "relative";
let hackContainer = create("div","subMenuContainer",false,false,"position:relative;width:100%;min-height:50px;z-index:134;display:inline-flex;");
navThingy.parentNode.insertBefore(hackContainer,navThingy);
hackContainer.appendChild(navThingy);
let subMenu = create("div","hohSubMenu",false,hackContainer);
create("a","hohSubMenuLink","Favourites",subMenu)
.href = "/user/" + whoAmI + "/favorites";
let linkStats = create("a","hohSubMenuLink","Stats",subMenu);
if(useScripts.mangaBrowse){
linkStats.href = "/user/" + whoAmI + "/stats/manga/overview";
}
else{
linkStats.href = "/user/" + whoAmI + "/stats/anime/overview";
}
create("a","hohSubMenuLink","Social",subMenu)
.href = "/user/" + whoAmI + "/social";
create("a","hohSubMenuLink","Reviews",subMenu)
.href = "/user/" + whoAmI + "/reviews";
create("a","hohSubMenuLink","Submissions",subMenu)
.href = "/user/" + whoAmI + "/submissions";
hackContainer.onmouseenter = function(){
subMenu.style.display = "inline";
}
hackContainer.onmouseleave = function(){
subMenu.style.display = "none";
}
}
else{
setTimeout(addMouseover,500);
}
};addMouseover();
}
let likeLoop = setInterval(function(){
document.querySelectorAll(
".activity-entry > .wrap > .actions .action.likes:not(.hohHandledLike)"
).forEach(thingy => {
thingy.classList.add("hohHandledLike");
thingy.onmouseover = function(){
if(thingy.classList.contains("hohLoadedLikes")){
return;
}
thingy.classList.add("hohLoadedLikes");
if(!thingy.querySelector(".count")){
return;
}
if(parseInt(thingy.querySelector(".count").innerText) <= 5){
return;
};
const id = parseInt(thingy.parentNode.parentNode.querySelector(`[href^="/activity/"`).href.match(/\d+/));
generalAPIcall(`
query($id: Int){
Activity(id: $id){
... on TextActivity{
likes{name}
}
... on MessageActivity{
likes{name}
}
... on ListActivity{
likes{name}
}
}
}`,
{id: id},
function(data){
thingy.title = data.data.Activity.likes.map(like => like.name).join("\n");
}
);
};
});
},300);
function singleActivityReplyLikes(id){
let adder = function(data){
if(!document.URL.includes("activity/" + id || !data)){
return;
};
let post = document.querySelector(".activity-entry > .wrap > .actions .action.likes");
if(!post){
setTimeout(function(){adder(data)},200);
return;
};
post.classList.add("hohLoadedLikes");
post.classList.add("hohHandledLike");
if(post.querySelector(".count") && !(parseInt(post.querySelector(".count").innerText) <= 5)){
post.title = data.data.Activity.likes.map(like => like.name).join("\n");
};
let smallAdder = function(){
if(!document.URL.includes("activity/" + id)){
return;
};
let actionLikes = document.querySelectorAll(".activity-replies .action.likes");
if(!actionLikes.length){
setTimeout(smallAdder,200);
return;
}
actionLikes.forEach((node,index) => {
if(node.querySelector(".count") && !(parseInt(node.querySelector(".count").innerText) <= 5)){
node.title = data.data.Activity.replies[index].likes.map(like => like.name).join("\n");
}
});
};
if(data.data.Activity.replies.length){
smallAdder();
}
}
generalAPIcall(`
query($id: Int){
Activity(id: $id){
... on TextActivity{
likes{name}
replies{likes{name}}
}
... on MessageActivity{
likes{name}
replies{likes{name}}
}
... on ListActivity{
likes{name}
replies{likes{name}}
}
}
}`,
{id: id},
adder
);
}
function forumLikes(){
let URLstuff = location.pathname.match(/^\/forum\/thread\/(\d+)/);
if(!URLstuff){
return;
}
let adder = function(data){
if((!data) || (!location.pathname.includes("forum/thread/" + URLstuff[1]))){
return
}
let button = document.querySelector(".footer .actions .button.like");
if(!button){
setTimeout(function(){adder(data)},200);
return;
}
button.title = data.data.Thread.likes.map(like => like.name).join("\n");
}
generalAPIcall(`
query($id: Int){
Thread(id: $id){
likes{name}
}
}`,
{id: parseInt(URLstuff[1])},
adder
);
}
if(useScripts.youtubeFullscreen){
setInterval(function(){
document.querySelectorAll(".youtube iframe").forEach(video => {
if(!video.hasAttribute("allowfullscreen")){
video.setAttribute("allowfullscreen","true");
}
});
},1000);
}
if(useScripts.mobileFriendly){
let addReviewLink = function(){
let footerPlace = document.querySelector(".footer .links section:last-child");
if(footerPlace){
let revLink = create("a",false,"Reviews",footerPlace,"display:block;padding:6px;");
revLink.href = "/reviews/";
}
else{
setTimeout(addReviewLink,500);
}
};addReviewLink();
}
let titleObserver = new MutationObserver(function(mutations){
let title = document.querySelector("head > title").textContent;
let titleMatch = title.match(/(.*)\s\((\d+)\)\s\((.*)\s\(\2\)\)(.*)/);//ugly nested paranthesis like "Tetsuwan Atom (1980) (Astro Boy (1980)) · AniList"
if(titleMatch){
//change to the form "Tetsuwan Atom (Astro Boy 1980) · AniList"
document.title = titleMatch[1] + " (" + titleMatch[3] + " " + titleMatch[2] + ")" + titleMatch[4];
}
if(document.URL.match(/^https:\/\/anilist\.co\/search\/characters/) && title !== "Find Characters · AniList"){
document.title = "Find Characters · AniList";
}
else if(document.URL.match(/^https:\/\/anilist\.co\/search\/staff/) && title !== "Find Staff · AniList"){
document.title = "Find Staff · AniList";
}
else if(document.URL.match(/^https:\/\/anilist\.co\/search\/studios/) && title !== "Find Studios · AniList"){
document.title = "Find Studios · AniList";
}
else if(document.URL.match(/^https:\/\/anilist\.co\/search\/anime/) && title !== "Find Anime · AniList"){
document.title = "Find Anime · AniList";
}
else if(document.URL.match(/^https:\/\/anilist\.co\/search\/manga/) && title !== "Find Manga · AniList"){
document.title = "Find Manga · AniList";
};
if(useScripts.SFWmode && title !== "Table of Contents"){
document.title = "Table of Contents";
}
});
if(document.title){
titleObserver.observe(document.querySelector("head > title"),{subtree: true, characterData: true, childList: true })
}
function handleScripts(url,oldURL){
if(url === "https://anilist.co/settings/apps"){
settingsPage()
}
else if(url === "https://anilist.co/notifications" && useScripts.notifications){
enhanceNotifications();
return;
}
else if(url === "https://anilist.co/reviews" && useScripts.reviewConfidence){
addReviewConfidence();
return;
}
else if(url === "https://anilist.co/user/" + whoAmI + "/social#my-threads"){
selectMyThreads()
}
else if(url === "https://anilist.co/settings/import" && useScripts.moreImports){
moreImports()
}
else if(url === "https://anilist.co/terms" && useScripts.termsFeed){
termsFeed()
}
else if(url === "https://anilist.co/site-stats"){
randomButtons()
}
else if(url === "https://anilist.co/404" && oldURL.match(/^https:\/\/anilist\.co\/user/)){
possibleBlocked(oldURL)
}
if(url.match(/^https:\/\/anilist\.co\/(anime|manga)\/\d*\/[\w\-]*\/social/)){
if(useScripts.socialTab){
enhanceSocialTab();
if(useScripts.accessToken){
enhanceSocialTabFeed()
}
};
if(useScripts.activityTimeline){
addActivityTimeline()
}
}
else{
stats.element = null;
stats.count = 0;
stats.scoreSum = 0;
stats.scoreCount = 0;
}
if(
url.match(/\/stats\/?/)
&& useScripts.moreStats
){
addMoreStats()
};
if(
url.match(/^https:\/\/anilist\.co\/home#access_token/)
){
let tokenList = location.hash.split("&").map(a => a.split("="));
useScripts.accessToken = tokenList[0][1];
useScripts.save();
location.replace(location.protocol + "//" + location.hostname + location.pathname);
};
if(
url.match(/^https:\/\/anilist\.co\/home#aniscripts-login/)
){
if(useScripts.accessToken){
alert("Already authorized. You can rewoke this under 'apps' in your Anilist settings")
}
else{
location.href = authUrl
}
};
if(url.match(/^https:\/\/anilist\.co\/user/)){
if(useScripts.completedScore || useScripts.droppedScore){//we also want this script to run on user pages
addCompletedScores()
};
if(useScripts.embedHentai){
embedHentai()
};
if(useScripts.noImagePolyfill || useScripts.SFWmode){
addImageFallback()
};
let adder = function(){
let banner = document.querySelector(".banner");
if(banner){
let bannerLink = create("a","hohDownload","⭳",banner);
const linkPlace = banner.style.backgroundImage.replace("url(","").replace(")","").replace('"',"").replace('"',"");
bannerLink.href = linkPlace;
bannerLink.title = "Banner Link";
if(linkPlace === "null"){
bannerLink.style.display = "none"
}
}
else{
setTimeout(adder,500)
}
};adder();
if(useScripts.milestones){
meanScoreBack()
};
if(useScripts.profileBackground){
profileBackground()
};
if(useScripts.customCSS){
addCustomCSS()
}
}
else{
customStyle.textContent = ""
}
if(
url.match(/^https:\/\/anilist\.co\/forum\/thread\/.*/)
){
if(useScripts.forumComments){
enhanceForum()
}
if(useScripts.embedHentai){
embedHentai()
};
forumLikes()
}
else if(
url.match(/^https:\/\/anilist\.co\/forum\/?(overview|search\?.*|recent|new|subscribed)?$/)
){
if(useScripts.myThreads){
addMyThreadsLink()
}
}
else if(url.match(/^https:\/\/anilist\.co\/staff\/.*/)){
if(useScripts.staffPages){
enhanceStaff()
}
if(useScripts.replaceStaffRoles){
replaceStaffRoles()
}
}
else if(
url.match(/^https:\/\/anilist\.co\/character\/.*/)
&& useScripts.characterFavouriteCount
){
enhanceCharacter()
}
else if(
url.match(/^https:\/\/anilist\.co\/studio\/.*/)
){
if(useScripts.studioFavouriteCount){
enhanceStudio()
}
if(useScripts.CSScompactBrowse){
addStudioBrowseSwitch()
};
}
else if(
url.match(/^https:\/\/anilist\.co\/edit/)
&& useScripts.enumerateSubmissionStaff
){
enumerateSubmissionStaff()
}
if(
url.match(/^https:\/\/anilist\.co\/user\/.*\/social/)
){
if(useScripts.CSSfollowCounter){
addFollowCount()
}
addSocialThemeSwitch();
};
if(
url.match(/^https:\/\/anilist\.co\/.+\/(anime|manga)list\/?(.*)?$/)
){
drawListStuff();
if(useScripts.viewAdvancedScores){
viewAdvancedScores(url)
}
if(useScripts.yearStepper){
yearStepper()
}
}
if(
url.match(/^https:\/\/anilist\.co\/user\/(.*)\/(anime|manga)list\/compare/)
&& useScripts.comparissionPage
){
addComparissionPage()
}
else{
let possibleHohCompareRemaining = document.querySelector(".hohCompare");
if(possibleHohCompareRemaining){
possibleHohCompareRemaining.remove()
}
};
if(url.match(/^https:\/\/anilist\.co\/search/)){
if(useScripts.CSScompactBrowse){
addCompactBrowseSwitch()
}
}
if(url.match(/^https:\/\/anilist\.co\/search\/characters/)){
if(useScripts.characterFavouriteCount){
enhanceCharacterBrowse()
};
document.title = "Find Characters · AniList";
}
else if(url.match(/^https:\/\/anilist\.co\/search\/staff/)){
if(useScripts.staffPages){
enhanceStaffBrowse()
};
document.title = "Find Staff · AniList";
}
else if(url.match(/^https:\/\/anilist\.co\/search\/studios/)){
document.title = "Find Studios · AniList";
}
else if(url.match(/^https:\/\/anilist\.co\/search\/anime/)){
document.title = "Find Anime · AniList";
setTimeout(() => {
if(document.URL.match(/^https:\/\/anilist\.co\/search\/anime/)){
document.title = "Find Anime · AniList"
}
},100);
if(useScripts.browseFilters){
addBrowseFilters("anime")
}
}
else if(url.match(/^https:\/\/anilist\.co\/search\/manga/)){
document.title = "Find Manga · AniList";
if(useScripts.browseFilters){
addBrowseFilters("manga");
};
};
let mangaAnimeMatch = url.match(/^https:\/\/anilist\.co\/(anime|manga)\/(\d+)\/?([^/]*)?\/?(.*)?/);
if(mangaAnimeMatch){
let adder = function(){
if(!document.URL.match(/^https:\/\/anilist\.co\/(anime|manga)\/?/)){
return;
};
let banner = document.querySelector(".banner");
if(banner){
let bannerLink = create("a","hohDownload","⭳",banner);
bannerLink.href = banner.style.backgroundImage.replace("url(","").replace(")","").replace('"',"").replace('"',"");
}
else{
setTimeout(adder,500);
}
};adder();
if(useScripts.tagDescriptions){
enhanceTags()
};
if(useScripts.subTitleInfo){
addSubTitleInfo()
}
if(useScripts.dubMarker && mangaAnimeMatch[1] === "anime"){
dubMarker()
}
else if(useScripts.mangaGuess && mangaAnimeMatch[1] === "manga"){
mangaGuess()
};
if(useScripts.mangaGuess && mangaAnimeMatch[1] === "anime"){
mangaGuess(true)
};
if(useScripts.MALscore || useScripts.MALserial || useScripts.MALrecs){
addMALscore(mangaAnimeMatch[1],mangaAnimeMatch[2])
};
if(useScripts.accessToken){
addRelationStatusDot(mangaAnimeMatch[2])
};
if(useScripts.entryScore && whoAmI){
addEntryScore(mangaAnimeMatch[2])
};
if(useScripts.SFWmode){
cencorMediaPage(mangaAnimeMatch[2])
};
let titleAliases = JSON.parse(localStorage.getItem("titleAliases"));
if(useScripts.shortRomaji){
titleAliases = shortRomaji.concat(titleAliases);
};
if(document.getElementById("hohAliasHeading")){
document.getElementById("hohAliasHeading").nextSibling.style.display = "block";
document.getElementById("hohAliasHeading").remove();
};
if(titleAliases){
const urlID = mangaAnimeMatch[2];
titleAliases.forEach(alias => {//can't just use a find, the latest alias takes priority (find in reverse?)
if(alias[0] === "css/"){
return;
};
if(alias[0].substring(7,alias[0].length-1) === urlID){
let newState = "/" + mangaAnimeMatch[1] + "/" + urlID + "/" + safeURL(alias[1]) + "/";
if(mangaAnimeMatch[4]){
newState += mangaAnimeMatch[4]
};
history.replaceState({},"",newState);
current = document.URL;
let titleReplacer = () => {
if(urlChangedDependence === false){//I have to kill these global flags with fire some day
return;
};
let mainTitle = document.querySelector("h1");//fragile, just like your heterosexuality
if(mainTitle){
let newHeading = create("h1","#hohAliasHeading",alias[1]);
mainTitle.parentNode.insertBefore(newHeading,mainTitle);
mainTitle.style.display = "none";
//mainTitle.innerText = alias[1];
return;
}
else{
urlChangedDependence = true;
setTimeout(titleReplacer,100);
}
};
urlChangedDependence = true;
titleReplacer();
};
});
};
if(useScripts.socialTab){
scoreOverviewFixer()
}
};
if(url.match(/^https:\/\/anilist\.co\/home\/?$/)){
if(useScripts.completedScore || useScripts.droppedScore){
addCompletedScores()
};
if(useScripts.betterListPreview && whoAmI && useScripts.accessToken && (!useScripts.mobileFriendly)){
betterListPreview()
};
if(useScripts.progressBar){
addProgressBar()
};
if(
(useScripts.feedCommentFilter && (!useScripts.mobileFriendly))
|| useScripts.blockList
|| useScripts.blockWord
|| useScripts.statusBorder
){
addFeedFilters()
};
if(useScripts.expandRight){
expandRight()
};
if(useScripts.embedHentai){
embedHentai()
};
if(useScripts.forumMedia){
addForumMedia()
};
if(useScripts.noImagePolyfill || useScripts.SFWmode){
addImageFallback()
};
if(useScripts.dblclickZoom){
addDblclickZoom()
};
if(useScripts.hideGlobalFeed){
hideGlobalFeed()
};
if(useScripts.betterReviewRatings){
betterReviewRatings()
};
if(useScripts.homeScroll){
let homeButton = document.querySelector(".nav .link[href=\"/home\"]");
if(homeButton){
homeButton.onclick = () => {
if(document.URL.match(/^https:\/\/anilist\.co\/home\/?$/)){
window.scrollTo({top: 0,behavior: "smooth"})
}
}
}
};
linkFixer();
}
let activityMatch = url.match(/^https:\/\/anilist\.co\/activity\/(\d+)/);
if(activityMatch){
if(useScripts.completedScore || useScripts.droppedScore){
addCompletedScores()
};
if(useScripts.activityTimeline){
addActivityLinks(activityMatch[1])
};
if(useScripts.embedHentai){
embedHentai()
};
if(useScripts.showMarkdown){
showMarkdown(activityMatch[1])
};
singleActivityReplyLikes(parseInt(activityMatch[1]))
};
if(url.match(/^https:\/\/anilist\.co\/edit/)){//seems to give mixed results. At least it's better than nothing
window.onbeforeunload = function(){
return "Page refresh has been intercepted to avoid an accidental loss of work";
};
};
if(useScripts.notifications && useScripts.accessToken && !useScripts.mobileFriendly){
notificationCake();
};
};
const useScriptsDefinitions = [
{id: "notifications",
description: "Improve notifications",
categories: ["Notifications","Login"]
},{id: "hideLikes",
description: "Hide like notifications. Will not affect the notification count",
categories: ["Notifications"]
},{id: "settingsTip",
description: "Show a notice on the notification page for where the script settings can be found",
categories: ["Notifications"]
},{id: "dismissDot",
description: "Show a spec to dismiss notifications when signed in",
categories: ["Notifications","Login"]
},{id: "socialTab",
description: "Media social tab average score, progress and notes",
categories: ["Media"]
},{id: "forumComments",
description: "Add a button to collapse comment threads in the forum",
categories: ["Forum"]
},{id: "forumMedia",
description: "Add the tagged media to the forum preview on the home page",
categories: ["Forum"]
},{id: "mangaBrowse",
description: "Make browse default to manga",
categories: ["Browse"]
},{id: "ALbuttonReload",
description: "Make the 'AL' button reload the feeds on the homepage",
categories: ["Navigation"]
},{id: "draw3x3",
description: "Add a button to lists to create 3x3's from list entries. Click the button, and then select nine entries",
categories: ["Lists"]
},{id: "aniscriptsAPI",
description: "Enable an API for other scripts to control automail [Don't enable this unless you know what you are doing]",
categories: ["Script","Login"]
},{id: "mobileFriendly",
description: "Mobile Friendly mode. Disables some modules not working properly on mobile, and adjusts others",
categories: ["Navigation","Script"]
},{id: "tagDescriptions",
description: "Show the definitions of tags when adding new ones to an entry",
categories: ["Media"]
},{id: "MALscore",
description: "Add MAL scores to media",
categories: ["Media"]
},{id: "MALserial",
description: "Add MAL serialization info to manga",
categories: ["Media"]
},{id: "MALrecs",
description: "Add MAL recs to media",
categories: ["Media"]
},{id: "subTitleInfo",
description: "Add basic data below the title on media pages",
categories: ["Media"]
},{id: "entryScore",
description: "Add your score and progress to anime pages",
categories: ["Media","Login"]
},{id: "reviewConfidence",
description: "Add confidence scores to reviews"
},{id: "betterReviewRatings",
description: "Add the total number of ratings to review ratings on the home page"
},{id: "activityTimeline",
description: "Link your activities in the social tab of media, and between individual activities",
categories: ["Media","Navigation"]
},{id: "browseFilters",
description: "Add more sorting options to browse",
categories: ["Browse"]
},{id: "enumerateSubmissionStaff",
description: "Enumerate the multiple credits for staff in the submission form to help avoid duplicates",
categories: ["Submissions","Profiles"]
},{id: "replaceStaffRoles",
description: "Add sorting to staff pages",
categories: ["Media","Login"]
},{id: "completedScore",
description: "Show the score on the activity when people complete something",
categories: ["Feeds"]
},{id: "droppedScore",
description: "Show the score on the activity when people drop something",
categories: ["Feeds"]
},{id: "tagIndex",
description: "Show an index of custom tags on anime and manga lists",
categories: ["Lists"]
},{id: "yearStepper",
description: "Add buttons to step the year slider up and down",
categories: ["Lists"]
},{id: "CSSfollowCounter",
description: "Follow count on social page",
categories: ["Profiles"],
},{id: "CSSsubmissionCounter",
description: "Add counters to your submission page",
categories: ["Submissions","Profiles"]
},{
id: "dubMarker",
subSettings: ["dubMarkerLanguage"],
description: "Add a notice on top of the other data on an anime page if a dub is available (works by checking for voice actors)",
categories: ["Media"]
},{
id: "dubMarkerLanguage",
requires: ["dubMarker"],
description: "",
type: "select",
categories: ["Media"],
values: ["English","German","Italian","Spanish","French","Korean","Portuguese","Hebrew","Hungarian"]
},{id: "mangaGuess",
description: "Make a guess for the number of chapters for releasing manga",
categories: ["Media"]
},{id: "CSSmobileTags",
description: "Don't hide tags from media pages on mobile",
categories: ["Media"]
},{id: "moreStats",
description: "Show an additional tab on the stats page",
categories: ["Stats"]
},{id: "replaceNativeTags",
description: "Full lists for tags, staff and studios in stats",
categories: ["Stats"]
},{id: "allStudios",
description: "Include companies that aren't animation studios in the extended studio table",
categories: ["Stats"]
},{id: "noRewatches",
description: "Don't include progress from rewatches/rereads in stats",
categories: ["Stats"]
},{id: "hideCustomTags",
description: "Hide the custom tags tables by default",
categories: ["Stats"]
},{id: "negativeCustomList",
description: "Add an entry in the custom tag tables with all media not on a custom list",
categories: ["Stats"]
},{id: "globalCustomList",
description: "Add an entry in the custom tag tables with all media",
categories: ["Stats"]
},{id: "timeToCompleteColumn",
description: "Add 'time to complete' info to the tag tables",
categories: ["Stats"]
},{id: "comparissionPage",
description: "Replace the native comparison feature",
categories: ["Lists","Profiles"]
},{id: "CSSsmileyScore",
description: "Give smiley ratings distinct colours [from userstyle]",
categories: ["Lists","Media"]
},{id: "CSSexpandFeedFilters",
description: "Expand the feed filters",
categories: ["Feeds"]
},{id: "hideGlobalFeed",
description: "Hide the global feed",
categories: ["Feeds"]
},{id: "feedCommentFilter",
description: "Add filter options to the feeds to hide posts with few comments or likes",
categories: ["Feeds"]
},{id: "statusBorder",
description: "Colour code the right border of activities by status",
categories: ["Feeds"]
},{id: "blockWord",
description: "Hide status posts containing this word:",
categories: ["Feeds"]
},{
id: "blockWordValue",
requires: ["blockWord"],
description: "",
type: "text",
categories: ["Feeds"]
},{id: "profileBackground",
description: "Enable profile backgrounds",
categories: ["Profiles","Login"]
},{
id: "profileBackgroundValue",
requires: ["profileBackground"],
description: "",
visible: false,
type: "text",
categories: ["Profiles"]
},{id: "colourPicker",
description: "Add a colour picker in the footer for adjusting the site themes",
categories: ["Script"]
},{id: "progressBar",
description: "Add progress bars to the progress lists",
categories: ["Feeds"]
},{id: "embedHentai",
description: "Make cards for links to age restricted content",
categories: ["Feeds"]
},{id: "betterListPreview",
description: "Alternative list preview",
categories: ["Feeds","Lists","Login"]
},{id: "homeScroll",
description: "Make the 'home' button scroll to the top on the home feed",
categories: ["Feeds"]
},{id: "CSSfavs",
description: "Use 5-width favourite layout [from userstyle]",
categories: ["Profiles"]
},{id: "CSScompactBrowse",
description: "Use a compact view in the browse section. Also makes various list views available",
categories: ["Browse"]
},{id: "customCSS",
description: "Enable custom profile CSS",
categories: ["Profiles","Login"]
},{id: "CSSgreenManga",
description: "Green titles for manga",
categories: ["Media","Feeds"]
},{id: "cleanSocial",
description: "Give a better space to the following list on the social tab [under development]",
categories: ["Media"]
},{id: "limitProgress10",
description: "Limit the 'in progress' sections to 10 entries",
categories: ["Feeds"]
},{id: "limitProgress8",
description: "Limit the 'in progress' sections to 8 entries",
categories: ["Feeds"]
},{id: "expandDescriptions",
description: "Automatically expand descriptions",
categories: ["Media"]
},{id: "showRecVotes",
description: "Always show the recommendation voting data",
categories: ["Media"]
},{id: "myThreads",
description: "Add a 'my threads' link in the forum",
categories: ["Forum","Profiles"]
},{id: "expandRight",
description: "Load the expanded view of 'in progress' in the usual place instead of full width if left in that state [weird hack]",
categories: ["Feeds"]
},{id: "noImagePolyfill",
description: "Add fallback text for missing images in the sidebar and favourite sections",
categories: ["Feeds","Profiles"]
},{id: "dropdownOnHover",
description: "Expand the user menu in the nav on hover instead of click",
categories: ["Navigation"]
},{id: "shortRomaji",
description: "Short romaji titles for everyday use. Life is too short for light novel titles",
categories: ["Feeds","Profiles","Lists"]
},{id: "CSSprofileClutter",
description: "Remove clutter from profiles (milestones, history chart, genres)",
categories: ["Profiles"]
},{id: "CSSdecimalPoint",
description: "Give whole numbers a \".0\" suffix when using the 10 point decimal scoring system",
categories: ["Lists"]
},{id: "viewAdvancedScores",
description: "View advanced scores",
categories: ["Lists"]
},{id: "dblclickZoom",
description: "Double click activities to zoom",
categories: ["Feeds"]
},{id: "youtubeFullscreen",
description: "Allow Youtube videos to play in fullscreen mode",
categories: ["Script"]
},{id: "termsFeed",
description: "Add a low bandwidth feed to the https://anilist.co/terms page",
categories: ["Feeds","Login"]
},{id: "termsFeedNoImages",
description: "Do not load images on the low bandwidth feed",
categories: ["Feeds","Login"]
},{id: "CSSbannerShadow",
description: "Remove banner shadows",
categories: ["Profiles","Media"]
},{id: "milestones",
description: "Add total episodes and volumes to profile milestones",
categories: ["Profiles"]
},{id: "CSSdarkDropdown",
description: "Use a dark menu dropdown in dark mode",
categories: ["Navigation"]
},{id: "moreImports",
description: "Add more list import and list export options",
categories: ["Script","Login"]
},{id: "plussMinus",
description: "Add + and - buttons to quickly change scores on your list",
categories: ["Lists","Login"]
},{id: "SFWmode",
description: "A less flashy version of the site for school or the workplace [under development]",
categories: ["Script"]
},{id: "CSSverticalNav",
description: "Alternative browse mode [with vertical navbar by Kuwabara]",
categories: ["Navigation"]
}
];
let current = "";
let mainLoop = setInterval(() => {
if(document.URL !== current){
urlChangedDependence = false;
let oldURL = current + "";
current = document.URL;
handleScripts(current,oldURL);
};
if(useScripts.expandDescriptions){
let expandPossible = document.querySelector(".description-length-toggle");
if(expandPossible){
expandPossible.click();
};
}
},200);
let tagDescriptions = {};
let expired = true;
let tagCache = localStorage.getItem("hohTagCache");
if(tagCache){
tagCache = JSON.parse(tagCache);
expired = (NOW() - tagCache.updated) > 3*60*60*1000;//three hours
};
if(expired){
generalAPIcall("query{MediaTagCollection{name description}}",{},data => {
data.data.MediaTagCollection.forEach(tag => {
tagDescriptions[tag.name] = tag.description;
});
localStorage.setItem("hohTagCache",JSON.stringify({
tags: tagDescriptions,
updated: NOW()
}));
});
}
else{
tagDescriptions = tagCache.tags;
};
console.log("Automail " + scriptInfo.version);
Object.keys(localStorage).forEach(key => {
if(key.includes("hohListActivityCall")){
let cacheItem = JSON.parse(localStorage.getItem(key));
if(cacheItem){
if(NOW() > cacheItem.time + cacheItem.duration){
localStorage.removeItem(key)
}
}
}
else if(key === "aniscriptsUsed"){
localStorage.removeItem(key);
}
});
if(useScripts.aniscriptsAPI){
if(document.aniscriptsAPI){
console.warn("Multiple copies of Automail running? Shutting down this instance.");
clearInterval(mainLoop);
clearInterval(likeLoop);
}
document.aniscriptsAPI = {
scriptInfo: scriptInfo,
generalAPIcall: generalAPIcall,//query,variables,callback[,cacheKey[,timeFresh[,useLocalStorage]]]
authAPIcall: authAPIcall,
queryPacker: queryPacker,
settings: useScripts,
logOut: function(){useScripts.accessToken = "";useScripts.save()}
}
}
})();