// ==UserScript==
// @name flickrAwardCounter
// @namespace http://www.phazeshift.co.uk/download/
// @description UserScript to count award images in Flickr photo comments
// @version 2.32
// @author phazeshift et al.
// @license MIT
// @include http*://*flickr.com/*photos/*/*
// @include http*://*flickr.com/groups/*/discuss*
// @include http*://*flickr.com/groups/*/pool*
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_xmlhttpRequest
// @grant GM_log
// @grant GM_registerMenuCommand
// @downloadURL none
// ==/UserScript==
/*
Installation
============
First you need a UserScript manager extension for your browser. The state of the art seems to be Tampermonkey these days.
Works with Firefox and Chrome. Even Edge I'm told. https://www.tampermonkey.net. For Safari, it now looks like the preferred manager
is Stay (extension + app) downloadable from the App Store. https://apps.apple.com/gb/app/stay-web-only-browsing/id1591620171.
Then visit the script's new home page at Greasy Fork: https://greasyfork.org/en/scripts/441654-flickrawardcounter
Click the green Install or Update button at the top left of the page. That's it.
You can now visit or reload one of the Flickr pages the script is modifying: photo details, group pool, group discuss.
Release Notes
============
v1.0 Counts the comments on the current photo page using javascript
v2.0 Counts the comments for a photo using the flickr API on Group, Pool and Photo pages
v2.1 Updated to be more compatible with other scripts; no longer removes PoolList class from pool page. Fixed reloading of comments when clicking Show all.
v2.2 Allows multiple images to be specified per award, (separated with ';') and allows dupes for certain people to be ignored (separated with ';')
v2.3 Config dialog allows more awards to be added instead of being off the page.
v2.4 Added Sort & Edit options to config. Added Auto update function.
v2.5 Added option to display number favourites.
v2.6 Fixed clear config option
v2.7 Changed search code to find text that isn't in image tags
v2.8 Added option to hide awards with count = 0
v2.9 Fixed multiple URL config option & counting multiple awards in single comment
Added option to save settings online and tidied config page
Fixed version check code
v2.10 Applied Alesas patch to work with the new flickr layout. Thanks to Alesa for the patch and Tambako for letting me know about the new layout.
Added option to display number of galleries.
v2.11 Fixed an issue that caused script version to be checked on every page load when running under some Greasemonkey emulators that don't support storing settings.
Changed SaveCloudSettings to use a post request to prevent errors with long URLs
Added option to export counter settings to a string
Fixed compatibility issue with 'Flickr Group Pool Admin - Warn + Delete' script
Updated Pool display technique to interfere less with other scripts
v2.12 Added Aleas patch for update check exception handler
Reverted change to pool handling as award counts were unreadable
Fixed detection of image url for pool photos after recent flickr change
v2.13 Fixed detection of image id for individual photos after recent flickr change
v2.14 Fixed count display spacing on comment threads
Fixed counter to work with new pool layout
v2.15 Fixed show all on group discussion page
v2.16 Fixed Flickr Urls to support https. Thanks to Dave_O1
Added support for justified pool layout
Added greasemonkey @grant metadata
v2.17 Fixed SSL support
Fixed single photo view
v2.18 Fixed discussion view
v2.19 Fixed retrieval of photo id
v2.20 Fixed retrieval of photo id again, using location instead of document content.
Added @version and @license GM tags.
MB 2022-03-17.
v2.21 Fixed pool view in 'new' layout as opposed to deprecated 'classic'.
Tweaked photo id extraction regular expression.
Policed global leaks and wayward var declarations.
Added @author tag.
MB 2022-03-24.
v2.22 Fixed discussion view in 'new' (default) layout format.
Awards pane in each photo of the 'new' pool layout now scrollable if too many awards to display.
MB 2022-03-28.
v2.23 Updated configuration panel to display properly in modern browsers.
Removed cloud export for settings (phazeshift endpoint no longer available).
Fixed script version check now based on Greasy Fork repository.
Displays update link in the configuration panel when new version is available.
MB 2022-04-14.
v2.24 Updated event handler so that awards for the selected photo are displayed directly
when going from one photo to the next or previous in photo page view, as well as when
clicking on a photo tile in the new standard pool and stream views. No more page reloading necessary.
Updated photo page to display actual comments separately from awards. Click link to alternate display.
Feature can be disabled/enabled at the bottom of the configuration panel.
MB 2022-04-22.
v2.25 Corrected an error in displaying comments elapsed time.
Updated separated comments display for comments / awards / both options.
Added optional display of fac configured awards only for awards and both options.
Display awards in columns in photo details page.
MB 2022-05-20.
v2.26 Substitute default buddy icon when loading of comment author's icon fails.
fac-only checkbox state sticks from one photo details page to the next.
comments/awards/both display mode sticks from one photo details page to the next.
corrects missing or faulty dimensions of award images automatically.
corrects protocol of award images from http to https automatically when loaded from flickr domain
to conform to the page's Content Security Policy.
Number of columns for awards display now defaults to 1, adjustable in configuration panel.
MB 2022-05-23.
v2.27 List comments/awards in reverse chronological order, most recent first.
Comment box moved on top of comments list.
New 'reverse comments' checkbox in configuration panel.
Corrected another error in displaying comments elapsed time.
MB 2022-06-01.
v2.28 Updated separated comments display to adapt to new (and clearer) Flickr photo page HTML coding. Well done Flickr :-)
New separate real comments and awards (fac / all) counts in the photo page.
Awards are Flickr comments containing either an image or a link.
Real comments are text only.
MB 2023-09-22.
v2.29 Corrected comments menu button encoding in 'separate awards' mode
so that own comments are editable and deletable when shown in a photo page published by somebody else.
MB 2023-09-24.
v2.30 Corrected comments/awards menu to adapt to modern javascript syntax for HTMLCollections.
Fixed display of awards on Photo page initial load to adapt to new Flickr Asynchronous loading of location information.
MB 2024-01-08
v2.31 Further corrected display of awards on Photo page to allow for photos without geotagging.
MB 2024-01-12
v2.32 Further corrected display of awards on Photo page to allow for photos without any dynamic loading information.
MB 2024-01-13
*/
// Config Stuff
var glblConfigAwards = undefined;
var glblAllPhotos = undefined;
var glblCommentsText = undefined;
var glblAuthors = {};
var glblLastPhotoId = undefined;
var glblPhotoId = undefined;
var glblMode = undefined;
var glblAllowDupesFrom = undefined;
var glblVersion = '2.32';
var glblServerVersion = glblVersion;
var glblLastCheckedVersion = undefined;
var glblScriptUrl = 'http://www.phazeshift.co.uk/files/flickrawardcounter.user.js';
var glblScriptVersionUrl = 'https://greasyfork.org/en/scripts/441654-flickrawardcounter.json';
var glblUpdateCheck = true;
var glblFavourites = false;
var glblGalleries = false;
var glblHideZeroCount = false;
var glblPostAwards = true;
var glblSeparateAwards = true;
var glblFacOnly = true;
var glblColumns = 1;
var glblCommentsDisplayTab = 'comments';
var glblReverseComments = true;
var glblApiKey = 'cf7bfd7c92fcbea46bb7bce79b81ead7';
const SinglePhotoMode = 'Single';
const DiscussMode = 'Group';
const PoolMode = 'Pool';
const ConfigureLink = '( configure )';
const AwardCounter = 'Flickr Award Counter ';
const PoolAwardXPath = "//div[@class='flickraward']";
const AwardInnerXPath = ".//span[@id='flickraward-awardcount-inner']";
const AwardFooterXPath = ".//span[@id='awardcount-awardfooter']";
const AwardToHideXPath = ".//span[@id='flickraward-awardcount-tohide']";
// Wait for an element before resolving a promise
// @param {String} querySelector - Selector of element to wait for
// @param {Integer} timeout - Milliseconds to wait before timing out, or 0 for no timeout
function waitForElement(querySelector, timeout) {
return new Promise((resolve, reject) => {
var timer = false;
if (document.querySelectorAll(querySelector).length) return resolve();
const observer = new MutationObserver(() => {
if (document.querySelectorAll(querySelector).length) {
observer.disconnect();
if(timer !== false) clearTimeout(timer);
return resolve();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
if (timeout) {
timer = setTimeout(() => {
observer.disconnect();
reject();
}, timeout);
}
});
}
// Parse cookies from cookie string
function cookieParser(s) {
if (s === '') {
return {};
}
let pairs = s.split(";");
let splittedPairs = pairs.map(cookie => cookie.split("="));
const cookieObj = splittedPairs.reduce(function (obj, cookie) {
obj[decodeURIComponent(cookie[0].trim())] = decodeURIComponent(cookie[1].trim());
return obj;
}, {})
return cookieObj;
}
function Save() {
GM_setValue('awards', CreateSaveAwardStr());
GM_setValue('awardsText', CreateSaveCommentsStr());
if (glblAllowDupesFrom) {
GM_setValue('awards-allow-dupes-from', glblAllowDupesFrom.join(';').toLowerCase());
}
GM_setValue('favourites', glblFavourites);
GM_setValue('galleries', glblGalleries);
GM_setValue('hidezerocount', glblHideZeroCount);
GM_setValue('separateawards', glblSeparateAwards);
GM_setValue('updatecheck', glblUpdateCheck);
GM_setValue('columns', glblColumns);
GM_setValue('postawards', glblPostAwards);
GM_setValue('reversecomments', glblReverseComments);
}
function SaveUpdateInfo() {
GM_setValue('serverversion', glblServerVersion);
if (glblLastCheckedVersion) { GM_setValue('lastcheckedversion',glblLastCheckedVersion.getTime().toString()); }
}
function GmSettingsWorking() {
GM_setValue('gmsettingstest',glblVersion);
return (glblVersion == GM_getValue('gmsettingstest',''));
}
function Load() {
var buf = '';
ParseSaveAwardStr(GM_getValue('awards', ''));
ParseSaveCommentsStr(GM_getValue('awardsText', ''));
buf = GM_getValue('awards-allow-dupes-from', '');
if (buf.length > 0){
glblAllowDupesFrom = buf.toLowerCase().split(';');
}
glblServerVersion = GM_getValue('serverversion',glblServerVersion);
buf = GM_getValue('lastcheckedversion');
if (buf && buf != ''){
glblLastCheckedVersion = new Date();
glblLastCheckedVersion.setTime(buf);
}
glblColumns = GM_getValue('columns', glblColumns);
glblFacOnly = GM_getValue('faconly', glblFacOnly);
glblCommentsDisplayTab = GM_getValue('displaytab', glblCommentsDisplayTab);
glblUpdateCheck = GM_getValue('updatecheck', glblUpdateCheck);
glblFavourites = GM_getValue('favourites',glblFavourites);
glblGalleries = GM_getValue('galleries',glblGalleries);
glblHideZeroCount = GM_getValue('hidezerocount',glblHideZeroCount);
glblSeparateAwards = GM_getValue('separateawards',glblSeparateAwards);
glblPostAwards = GM_getValue('postawards',glblPostAwards);
glblReverseComments = GM_getValue('reversecomments',glblReverseComments);
}
function CreateSaveAwardStr() {
var buf = '';
for (var i = 0; i < glblConfigAwards.length; i++) {
if (glblConfigAwards[i] != undefined) {
buf = buf + escape(glblConfigAwards[i].Name) + ',' + escape(glblConfigAwards[i].Url.join(';')) + "|";
}
}
buf = buf.substring(0, buf.length - 1);
return buf;
}
function CreateSaveCommentsStr() { //stringify award comments
var buf = '',
i, j, k, max;
for (i = 0; i < glblConfigAwards.length; i++) {
if (glblConfigAwards[i] != undefined && 'Comments' in glblConfigAwards[i]) {
buf += escape(glblConfigAwards[i].Name) + ',';
max = k = 0;
for (j = 0; j < glblConfigAwards[i].Comments.length; j++) {
if (glblConfigAwards[i].Comments[j].count > max) {
max = glblConfigAwards[i].Comments[j].count;
k = j;
}
}
buf += escape(glblConfigAwards[i].Comments[k].text) + '|';
}
}
buf = buf.substring(0, buf.length - 1);
return buf;
}
function ParseSaveAwardStr(buf) {
var Items = [],
Items2 = [];
glblConfigAwards = new Array();
if (buf == undefined) { return; }
Items = buf.split('|');
for (var i = 0; i < Items.length; i++) {
if (Items[i] != '')
{
Items2 = Items[i].split(',');
try {
AddAward(unescape(Items2[0]),unescape(Items2[1]));
} catch (ex) {
alert(ex)
}
}
}
}
function ParseSaveCommentsStr(buf) {
var elements = [],
name, text = '',
i, index = 0,
records = [],
fields = [];
if (! buf) {
return;
}
records = buf.split('|')
for (i = 0; i < records.length; i++) {
if (records[i]) {
fields = records[i].split(',');
name = unescape(fields[0]);
text = unescape(fields[1]);
index = FindAwardPosByName(name);
if (index != -1) {
glblConfigAwards[index].Comments = [];
glblConfigAwards[index].Comments.push({'text': text, 'count': 0});
}
}
}
}
function CmpConfigAwards(a, b) {
var x = a.Name.toLowerCase(),
y = b.Name.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function Sort() {
glblConfigAwards.sort(CmpConfigAwards);
ConfigDisplayAwards();
}
function SortOne(awardId, up) {
var tmpAward,
newPos,
i = FindAwardPosByName(awardId);
if (i == -1) {return; }
tmpAward = glblConfigAwards[i];
if (up) { newPos = i - 1; }
else { newPos = i + 1; }
if ((newPos < 0) || newPos > glblConfigAwards.length - 1) { return; }
glblConfigAwards[i] = glblConfigAwards[newPos];
glblConfigAwards[newPos] = tmpAward;
ConfigDisplayAwards();
}
function FindAwardByName(awardid) {
var i = FindAwardPosByName(awardid);
if (i == -1) return undefined;
return glblConfigAwards[i];
}
function FindAwardPosByName(awardid) {
var Award = {};
for (var i=0; i < glblConfigAwards.length; i++) {
if (glblConfigAwards[i] != undefined) {
Award = glblConfigAwards[i];
if (Award.Name == awardid) {
return i;
}
}
}
return -1;
}
function ConfigDisplayAwardRow(buf, Award, pos, total) {
buf = '
'
return buf;
}
function ConfigDisplayAwards() {
var varElement = document.getElementById('AwardCounterVarList'),
buf = '',
i,
Award,
awardAdded = false;
for (i = 0; i < glblConfigAwards.length; i++) {
if (glblConfigAwards[i]) {
Award = glblConfigAwards[i];
buf += ConfigDisplayAwardRow(buf, Award, i, glblConfigAwards.length - 1);
awardAdded = true;
}
}
if (!awardAdded) {
buf = '
None defined.
';
}
// Replace html with new stuff
varElement.innerHTML = buf;
}
function DeleteElement(elementname) {
var varElement = document.getElementById(elementname);
if (varElement) {
varElement.parentNode.removeChild(varElement);
}
}
function SafeSetElementValue(elename, elevalue) {
var varElement = document.getElementById(elename);
if (varElement) {
varElement.value = elevalue;
}
}
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function TrimArray(arr) {
for (var i = 0; i -1) return false;
if (Value.indexOf(',') > -1) return false;
return true;
}
function AddAward(Name, Url) {
var newAward = true;
if (!Name) {return};
if (!Url) {return};
Name = RemoveTags(Name);
var Award = FindAwardByName(Name);
if (!CheckString(Name)) {
throw('Name contains a \'|\' or a \',\' which isn\'t valid');
}
if (!CheckString(Url)) {
throw('Url contains a \'|\' or a \',\' which isn\'t valid');
}
if (Award != undefined) {
newAward = false;
}
if (newAward) {
Award = {"Name" : "", "Url" : ""};
}
Award.Name = Name;
Award.Url = TrimArray(Url.split(';'));
if (newAward) {
glblConfigAwards[glblConfigAwards.length] = Award;
}
}
function EditAward(Name) {
var Award = FindAwardByName(Name);
if (Award == undefined) return;
document.getElementById("AwardName").value = Award.Name;
document.getElementById("AwardUrl").value = Award.Url.join(';');
}
function RemoveAward(Name) {
var i = FindAwardPosByName(Name);
if (i != -1) {
glblConfigAwards[i] = undefined;
}
ConfigDisplayAwards();
}
function NewerVersion(serverVersion, currentVersion) {
serverVersion = serverVersion.split(".");
currentVersion = currentVersion.split(".");
var i;
for (i = 0; i < serverVersion.length; i++) {
if (parseInt(serverVersion[i]) > parseInt(currentVersion[i])) return true;
}
return false;
}
function CreateConfigPage() {
var newDiv = document.createElement('div'),
awardSeparationEnabled,
reverseCommentsEnabled,
reverseCommentsRow,
htmlTemplate = `
This is a small UserScript to count the number of awards given to photos in groups on Flickr.
It will count any number of different awards given by users.
It will ignore duplicate awards of the same type from a user.
To start, just add a name for the award below and paste the url of the image for the award, click Add, then click Save.
You can specify a list of users to allow duplicate awards on the same photo for.
Display awards in
show favourites
This option will show the number of users that have added a picture as a favourite.
This option is a little slower, as it requires a second call to flickr.
show galleries
This option will show the number of galleries a picture has been added to.
This option is a little slower, as it requires a second call to flickr.
hide zero count
This option will hide awards with a count of zero.
separate awards from comments
This option will show actual comments only in the comments pane.
Click 'show awards' to display awards instead.
reverse comments order
This option will show list comments and awards in reverse chronological order,
most recent first, and move the comment box to the top of the comments list.
post awards
This option will show a small selection box in all photos in group pages.
Click 'post awards' to award all selected photos in the page.
This option will allow you to save and restore your awards as a string that can be copied to a text file.
To save your settings, leave the box blank and click Export.
Copy the string that pops in the box and paste it somewhere else.
To load your settings, just paste a string
(copied from some text backup or another instance of FlickrAwardCounter)
in the box and click Import.