// ==UserScript== // @name flickrAwardCounter // @namespace http://www.phazeshift.co.uk/download/ // @description UserScript to count award images in Flickr photo comments // @version 2.23 // @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, Safari and Chrome. Even Edge I'm told. https://www.tampermonkey.net 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 Known Issues ============ Group pool and discuss pages in deprecated 'classic' layout cannot display the award links in Safari. That is not solvable at the script's level. The 'new' default layout should be used anyway. */ // Config Stuff var glblConfigAwards = undefined; var glblAllPhotos = undefined; var glblCommentsText = undefined; var glblLastPhotoId = undefined; var glblPhotoId = undefined; var glblMode = undefined; var glblAllowDupesFrom = undefined; var glblVersion = '2.23'; 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 glblCloudSettingsUrl = 'http://www.phazeshift.co.uk/flickrawardcountersettings.php?'; var glblCloudSettingsId = ""; var glblUpdateCheck = true; var glblFavourites = false; var glblGalleries = false; var glblHideZeroCount = false; 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']"; function Save() { GM_setValue('awards', CreateSaveAwardStr()); 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('updatecheck', glblUpdateCheck); SaveCloudSettingsId(); } function SaveCloudSettingsId() { GM_setValue('cloudsettingsid',glblCloudSettingsId); } 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', '')); 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); } glblUpdateCheck = GM_getValue('updatecheck', glblUpdateCheck); /* if (! GmSettingsWorking()) glblUpdateCheck = false; */ glblFavourites = GM_getValue('favourites',glblFavourites); glblGalleries = GM_getValue('galleries',glblGalleries); glblHideZeroCount = GM_getValue('hidezerocount',glblHideZeroCount); glblCloudSettingsId = GM_getValue('cloudsettingsid',glblCloudSettingsId); } 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 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 CmpConfigAwards(a,b) { var x = a["Name"].toLowerCase(); var 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 = '
Version **VERSION** © copyright 2007-2022 Phazeshift et al. Re-released under MIT License.
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.
Registered AwardsSort Delete All |
Award Name | Award Image Url | ||||
Add |
Allow Duplicates From | |||||
You can specify a list of users to allow duplicate awards on the same photo for. | |||||
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. |
Export settings | Export Import | ||||
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. |
Save Cancel |
Please update to version ' + glblServerVersion + '.
' : ''); htmlTemplate = htmlTemplate.replace('**Favourites**', (glblFavourites) ? ' checked="checked"' : ''); htmlTemplate = htmlTemplate.replace('**Galleries**', (glblGalleries) ? ' checked="checked"' : ''); htmlTemplate = htmlTemplate.replace('**HideZeroCount**', (glblHideZeroCount) ? ' checked="checked"' : ''); htmlTemplate = htmlTemplate.replace('**CloudSettingsId**', glblCloudSettingsId); newDiv.setAttribute('id','flickrawardconfig-container'); newDiv.innerHTML = htmlTemplate; document.body.insertBefore(newDiv, document.body.firstChild); } // =================================================================== // Handle Events function EventAdd() { try { var AwardName = document.getElementById("AwardName").value; var AwardUrl = document.getElementById("AwardUrl").value; AddAward(AwardName,AwardUrl); document.getElementById("AwardName").value = ''; document.getElementById("AwardUrl").value = ''; ConfigDisplayAwards(); } catch (ex) { alert(ex); } } function EventCancel() { Load(); DeleteElement("flickrawardconfig-container"); } function EventExportSettings() { document.getElementById("ExportSettings").value = CreateSaveAwardStr(); } function EventImportSettings() { ParseSaveAwardStr(document.getElementById("ExportSettings").value); ConfigDisplayAwards(); } function EventSaveCloudSettings() { /* glblCloudSettingsId = document.getElementById("AwardCloudSettingsId").value; SaveCloudSettingsId(); Save(); SaveCloudSettings(); */ } function EventLoadCloudSettings() { /* glblCloudSettingsId = document.getElementById("AwardCloudSettingsId").value; SaveCloudSettingsId(); LoadCloudSettings(); */ } function EventSave() { var buf = document.getElementById("AwardAllowDupesFrom").value; if (buf.length > 0) { glblAllowDupesFrom = TrimArray(buf.toLowerCase().split(';')); } glblFavourites = document.getElementById("AwardFavouritesEnabled").checked; glblGalleries = document.getElementById("AwardGalleriesEnabled").checked; glblHideZeroCount = document.getElementById("AwardHideZeroCountEnabled").checked; // glblCloudSettingsId = document.getElementById("AwardCloudSettingsId").value; Save(); EventCancel(); GetAwardCounts(); } function EventSortAll() { Sort(); } function GetIdFromClicked(clickedOn,eventType){ var idstart = clickedOn.indexOf(eventType) + eventType.length + 1; var awardid = clickedOn.substring(idstart,255); return unescape(awardid); } function EventRemove(clickedOn) { var awardid = GetIdFromClicked(clickedOn,'remove'); RemoveAward(awardid); } function EventEdit(clickedOn) { var awardid = GetIdFromClicked(clickedOn,'edit'); EditAward(awardid); } function EventSortOne(clickedOn,up) { var awardid; if (up) { awardid = GetIdFromClicked(clickedOn,'-sortup'); } else { awardid = GetIdFromClicked(clickedOn,'-sortdown'); } SortOne(awardid,up); } function EventCountShow(clickedOn) { var photoid = GetIdFromClicked(clickedOn, 'countshow'), theElement = GetDisplayElement(photoid); theElement = FindFirstElement(theElement, AwardInnerXPath); theElement.innerHTML = 'Retrieving comments, please wait...'; GetCommentsForPhotoId(photoid); } function EventCountAllShow() { glblAllPhotos = []; var PhotoDetails, theElement, PhotoId, allPhotoElements = document.evaluate( PoolAwardXPath, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); for (var i = 0; i < allPhotoElements.snapshotLength; i++) { theElement = allPhotoElements.snapshotItem(i); PhotoId = theElement.id.substring(theElement.id.lastIndexOf('-')+1,255); PhotoDetails = {}; PhotoDetails.PhotoId = PhotoId; PhotoDetails.Done = false; glblAllPhotos[i] = PhotoDetails; } theElement = document.getElementById('flickraward-awardcountall'); if (theElement) { theElement.innerHTML = 'Retrieving comments, please wait...'; } DisplayNextPhotoDetails(); } function EventCountHideAll() { ToggleAll(false) } function ToggleAll(Visible) { var theElement, PhotoId; var allPhotoElements = document.evaluate( PoolAwardXPath, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null); for (var i = 0; i < allPhotoElements.snapshotLength; i++) { theElement = allPhotoElements.snapshotItem(i); PhotoId = theElement.id.substring(theElement.id.lastIndexOf('-')+1,255); ToggleDisplayAwards(PhotoId,Visible); } ToggleShowHideAll(Visible); } function EventCountReshowAll() { ToggleAll(true); } function EventClear() { var Ok = confirm("Do you really want to delete the awards you have set up??"); if (!Ok) { return; } GM_setValue('awards', ''); GM_setValue('awards-allow-dupes-from', ''); GM_setValue('lastcheckedversion', ''); Load(); ConfigDisplayAwards(); } function EventCountPositionAndShow(clickedOn) { var PhotoId = GetIdFromClicked(clickedOn, 'countpositionandshow'), theElement = GetDisplayElement(PhotoId); theElement = FindFirstElement(theElement,AwardInnerXPath); theElement.innerHTML = 'Retrieving comments, please wait...'; ToggleDisplayAwards(PhotoId, true); GetCommentsForPhotoId(PhotoId); } function EventCountHide(clickedOn) { clickedOn = unescape(clickedOn); var idstart = clickedOn.indexOf('counthide') + 10; var PhotoId = clickedOn.substring(idstart,255); ToggleDisplayAwards(PhotoId, false); } function EventCountReshow(clickedOn) { clickedOn = unescape(clickedOn); var idstart = clickedOn.indexOf('countreshow') + 12; var PhotoId = clickedOn.substring(idstart,255); ToggleDisplayAwards(PhotoId,true); } function EventConfigPage() { // Do our config page stuff CreateConfigPage(); if (glblConfigAwards == undefined) { Load(); } ConfigDisplayAwards(); if (glblAllowDupesFrom) { var varElement = document.getElementById("AwardAllowDupesFrom"); varElement.value = glblAllowDupesFrom.join(';'); } } // =================================================================== // Configure Event Handler function EndsWith(str, substr){ return (str.lastIndexOf(substr) == str.length - substr.length); } function ConfigureEvents() { document.addEventListener('click', function(event) { // event.target is the element that was clicked var clickedOn = event.target.toString(); if (clickedOn.indexOf('#flickrawardconfig-') > -1) { if (EndsWith(clickedOn,'save')) { EventSave(); } if (EndsWith(clickedOn,'sort')) { EventSortAll(); } if (EndsWith(clickedOn,'cancel')) { EventCancel(); } if (EndsWith(clickedOn,'add')) { EventAdd(); } if (EndsWith(clickedOn,'exportsettings')) { EventExportSettings(); } if (EndsWith(clickedOn,'importsettings')) { EventImportSettings(); } if (EndsWith(clickedOn,'savecloudsettings')) { EventSaveCloudSettings(); } if (EndsWith(clickedOn,'loadcloudsettings')) { EventLoadCloudSettings(); } if (EndsWith(clickedOn,'configure')) { EventConfigPage(); } if (clickedOn.indexOf('-remove-') > 0) { EventRemove(clickedOn); } if (clickedOn.indexOf('-sortup-') > 0) { EventSortOne(clickedOn,true); } if (clickedOn.indexOf('-sortdown-') > 0) { EventSortOne(clickedOn,false); } if (clickedOn.indexOf('-edit-') > 0) { EventEdit(clickedOn); } if (clickedOn.indexOf('countshow') > 0) { EventCountShow(clickedOn); } if (clickedOn.indexOf('countallhide') > 0) { EventCountHideAll(clickedOn); } if (clickedOn.indexOf('countallreshow') > 0) { EventCountReshowAll(clickedOn); } if (clickedOn.indexOf('counthide') > 0) { EventCountHide(clickedOn); } if (clickedOn.indexOf('countpositionandshow') > 0) { EventCountPositionAndShow(clickedOn); } if (clickedOn.indexOf('countreshow') > 0) { EventCountReshow(clickedOn); } if (clickedOn.indexOf('countallshow') > 0) { EventCountAllShow(); } if (clickedOn.indexOf('clear') > 0) { EventClear(); } // we handled the event so stop propagation event.stopPropagation(); event.preventDefault(); } }, true); } // =================================================================== // Search Stuff function CallFlickrMethod(method, params, onLoadFunction) { params['format'] = 'json'; params['nojsoncallback'] = 1; params['method'] = method; var url = "https://api.flickr.com/services/rest?"; CallMethod(url,params,onLoadFunction); } function CallMethod(url, params, onLoadFunction) { // http GET XHR wrapper var key; for(key in params) { url += "&" + key + "=" + params[key]; } GM_xmlhttpRequest({ method: "GET", url: url, headers: { "User-Agent": "flickrAwardCounter", "Accept": "application/json", }, onload: onLoadFunction }); } function CallPostMethod(url, params, onLoadFunction) { // http POST XHR wrapper var key, data = ''; for (key in params) { data += key + "=" + params[key] + "&"; } GM_xmlhttpRequest({ method: 'POST', url: url, data: data, headers: { "User-Agent": "flickrAwardCounter", "Accept": "text/monkey,text/xml", "Content-Type": "application/x-www-form-urlencoded" }, onload: onLoadFunction }); } function GetCommentsForPhotoId(PhotoId) { // Have we already cached the comments? if (glblLastPhotoId != PhotoId || glblCommentsText == undefined) { var params = {}, onLoadFunction = function(details) { ProcessComments(details.responseText); }; glblPhotoId = PhotoId; params.photo_id = PhotoId; params.api_key = glblApiKey; CallFlickrMethod('flickr.photos.comments.getList', params, onLoadFunction); } else { ProcessComments(glblCommentsText); } } function GetFavouritesForPhotoId(PhotoId) { var params = new Array(); params['photo_id'] = PhotoId; params['per_page'] = 1; params['api_key'] = glblApiKey; var onLoadFunction = function(details) { ProcessFavourites(details.responseText); } CallFlickrMethod('flickr.photos.getFavorites', params, onLoadFunction); } function GetGalleriesForPhotoId(PhotoId) { var params = new Array(); params['photo_id'] = PhotoId; params['per_page'] = 1; params['api_key'] = glblApiKey; var onLoadFunction = function(details) { ProcessGalleries(details.responseText,PhotoId); } CallFlickrMethod('flickr.galleries.getListForPhoto', params, onLoadFunction); } function CountAwardsPresentInText(intext, awardtextarr) { var result = 0; for (var i = 0; i < awardtextarr.length;i++) { // Todo : Maybe make this 2.7 change optional in future // if (intext.toLowerCase().indexOf('src="' + awardtextarr[i].toLowerCase() + '"') > 0) if (intext.toLowerCase().indexOf(awardtextarr[i].toLowerCase()) > -1) { result++; } } return result; } function inArray(arr, str) { for (var i=0; iRetrieving comments, please wait...
' + AwardCounter + ConfigureLink + '