imgur_show_user_stats_light

Show user statistics on imgur

  1. // ==UserScript==
  2. // @name imgur_show_user_stats_light
  3. // @namespace someName
  4. // @include http://imgur.com/user/*
  5. // @include https://imgur.com/user/*
  6. // @version 0.3.7
  7. // @grant none
  8. // @description Show user statistics on imgur
  9. // ==/UserScript==
  10. // TODO: Catch errors and check result.success
  11. // TODO: Think about useable version numbers...
  12. // TODO: Add support for username.imgur.com style urls
  13. // TODO: Show errors and handle no credits remaining ?
  14.  
  15. $(window).ready(function () {
  16. var CLIENT_ID = 'cd0695f1226536b';
  17. var SHOW_ID = false;
  18. var MAX_SUB_PAGES = 15;
  19. var _submissions_left = -1;
  20. var _sub_site = 0;
  21. var _submissions = [];
  22. var _last_sub_id = -1;
  23. var _last_post = -1;
  24. function _update_limits_from_header(xhr) {
  25. xhr.getResponseHeader('Header')
  26. $('#stats_credits_user').html('User Credits: ' + xhr.getResponseHeader('X-RateLimit-UserRemaining') + ' / ' + xhr.getResponseHeader('X-RateLimit-UserLimit'));
  27. $('#stats_credits_script').html('Script Credits: : ' + xhr.getResponseHeader('X-RateLimit-ClientRemaining') + ' / ' + xhr.getResponseHeader('X-RateLimit-ClientLimit'));
  28. }
  29.  
  30. function request_user_info(endpoint, success_cb, error_cb) {
  31. $.ajax({
  32. url: 'https://api.imgur.com/3/account/' + username + '/' + endpoint,
  33. method: 'GET',
  34. headers: {
  35. Authorization: 'Client-ID ' + CLIENT_ID,
  36. Accept: 'application/json'
  37. },
  38. success: function (a, b, c) {
  39. _update_limits_from_header(c);
  40. success_cb(a, b, c);
  41. },
  42. error: error_cb
  43. });
  44. }
  45. if (window.location.pathname.indexOf('/user/') === 0 && $('.button').filter('.comments').length > 0) {
  46. // Set up UI
  47. var username = window.location.pathname.split('/', 3) [2]; // TODO: look for a more stable way (is there an imgur js var maybe ?)
  48. var newBox = $('<div id="statsBox" class="textbox"></div>');
  49. var tble = $('<table id="_stats_table" width="100%">' +
  50. //'<tr><td colspan="2" align="center" style="display:none; color:#cf3131; font-weight:bold;" id="stats_is_mod">Moderator</td></tr>' +
  51. '<tr><td colspan="2"><hr></td></tr>'+
  52. '<tr style="display:none"><td>Userid:</td><td align="right"><span id="stats_uid"> - </span></td></tr>' +
  53. '<tr><td>Account creation</td><td align="right"><span id="stats_created"> - </span></td></tr>' +
  54. '<tr><td>Comments</td><td align="right"><a href="http://imgur.com/user/' + username + '/" id="stats_comments"> - </a></td></tr>' +
  55. '<tr><td>Submissions</td><td align="right"><a href="http://imgur.com/user/' + username + '/submitted" id="stats_submissions"> - </a></td></tr>' +
  56. '<tr><td>Albums</td><td align="right"><a href="http://' + username + '.imgur.com" id="stats_albums"> - </a></td></tr>' +
  57. '<tr><td>Images</td><td align="right"><a href="http://' + username + '.imgur.com/all" id="stats_images"> - </a></td></tr>' +
  58. '<tr><td>Favorites</td><td align="right"><a href="http://imgur.com/user/' + username + '/favorites" id="stats_favorites"> - </a></td></tr>' +
  59. '<tr><td colspan="2"><hr></td></tr>'+
  60. '<tr><td colspan="2" align="center"><button id="_btn_extend">Extended statistics</button></td></tr>' +
  61. '<tr class="_extended"><td colspan="2"><hr></td></tr>'+
  62. '<tr class="_extended"><td>Last activity</td><td align="right" id="stats_last_active"></td></tr>' +
  63. '<tr class="_extended"><td>AVG post points</td><td align="right" id="stats_score"></td></tr>' +
  64. '<tr class="_extended"><td>AVG post views</td><td align="right" id="stats_views"></td></tr>' +
  65. '<tr class="_extended"><td>Most viral posts </td><td align="right" id="stats_most_viral"></td></tr>' +
  66. '<tr class="_extended"><td>NSFW posts </td><td align="right" id="stats_nsfw"></td></tr>' +
  67. '<tr class="_extended"><td>Top tags</td><td align="right" id="stats_toptags"></td></tr>' +
  68. '<tr><td colspan="2"><hr></td></tr>'+
  69. '<tr><td colspan="2" align="center"><a href="http://community.imgur.com/users/' + username + '">IC profile</a></td></tr>' +
  70. '<tr><td style="color: #2B2B2B; font-size: 0.7em;" colspan="2" align="center" id="stats_credits_user"> - </td></tr>' +
  71. '<tr><td style="color: #2B2B2B; font-size: 0.7em;" colspan="2" align="center" id="stats_credits_script"> - </td></tr>' +
  72. '</table>');
  73. newBox.append(tble);
  74. newBox.insertBefore($('.notoriety-container'));
  75. tble.find('._extended').hide();
  76. // Add loading icon to all rows
  77. var tmp = $('#_stats_table tr td:nth-child(2)'); tmp.children().hide();
  78. tmp.append('<img style="height:1em" src="https://i.imgur.com/LR2v0rh.gif" />');
  79. $('#_btn_extend').click(function(){
  80. if(_submissions_left == 0) return;
  81. tble.find('._extended').show();
  82. get_submissions();
  83. });
  84. // get coments / submission stats
  85. request_user_info('gallery_profile', function (result, status, request) {
  86. $('#stats_comments').text(result.data.total_gallery_comments.toLocaleString()).closest('td').children().show().filter('img').remove();
  87. $('#stats_submissions').text(result.data.total_gallery_submissions.toLocaleString()).closest('td').children().show().filter('img').remove();
  88. $('#stats_favorites').text(result.data.total_gallery_favorites.toLocaleString()).closest('td').children().show().filter('img').remove();
  89. _submissions_left = result.data.total_gallery_submissions;
  90. if(_submissions_left == 0) $('#_btn_extend, #_stats_table hr:nth(1)').hide()
  91. }, function (a, b, c) {
  92. console.log('Failed to load', a, b, c);
  93. $('#stats_comments, #stats_submissions, #stats_favorites').text('Failed to load').closest('td').children().show().filter('img').remove();
  94. }
  95. );
  96. // get the exact (*) join date. TODO: I bet i messed up the time(zones) here.
  97. request_user_info('', function (result, status, request) {
  98. var date = new Date(result.data.created * 1000);
  99. var cake = new Date(result.data.created * 1000);
  100. var now = new Date();
  101. cake.setFullYear(now.getFullYear());
  102. if(cake < now){
  103. cake.setFullYear(cake.getFullYear() + 1);
  104. }
  105. var dist = cake - now;
  106. var foo = [[1000*60*60*24, 'day'], [1000*60*60, 'hour'], [1000*60, 'minute'], [1000, 'second']];
  107. var till_str = "";
  108. for(var i=0; i< foo.length; ++i){
  109. var val = Math.floor(dist / foo[i][0]);
  110. dist -= val * foo[i][0];
  111. if(val == 0 && till_str.length == 0)
  112. continue;
  113. till_str += val + " " + foo[i][1];
  114. if(val > 1) till_str += "s";
  115. till_str += " ";
  116. }
  117. $('#stats_created').text(date.toLocaleDateString()).attr('title', date.toLocaleString() + "\n" + "In: " + till_str).closest('td').children().show().filter('img').remove();
  118. if(SHOW_ID){
  119. $('#stats_uid').text(result.data.id).parent().parent().show();
  120. $('#stats_uid').closest('td').children().show().filter('img').remove();
  121. }
  122. /*if(result.data.pro_expiration != false){
  123. $('#stats_is_mod').show();
  124. }*/
  125. }, function (a, b, c) {
  126. console.log('Failed to load', a, b, c);
  127. $('#stats_created').text('Failed to load').closest('td').children().show().filter('img').remove();
  128. }
  129. );
  130. // album count (inklusive not submitted to gallery), if album settings are set to public.
  131. request_user_info('albums/count', function (result, status, request) {
  132. $('#stats_albums').text(result.data.toLocaleString()).closest('td').children().show().filter('img').remove();
  133. }, function (a, b, c) {
  134. console.log('Failed to load', a, b, c);
  135. $('#stats_albums').text('private').closest('td').children().show().filter('img').remove();
  136. }
  137. );
  138. // image count (inklusive not submitted to gallery), if image settings are set to public.
  139. request_user_info('images/count', function (result, status, request) {
  140. $('#stats_images').text(result.data.toLocaleString()).closest('td').children().show().filter('img').remove();
  141. }, function (a, b, c) {
  142. console.log('Failed to load', a, b, c);
  143. $('#stats_images').text('private').closest('td').children().show().filter('img').remove();
  144. }
  145. );
  146. function get_submissions() {
  147. if(_submissions_left <= 0){
  148. return;
  149. }
  150. console.log("Requesting submission page #" + _sub_site);
  151. request_user_info('submissions/' + _sub_site, function (result, status, request) {
  152. _submissions.push.apply(_submissions, result.data);
  153. _submissions_left -= result.data.length;
  154. var done = true;
  155. if(result.data.length > 0 && _submissions_left > 0 && _last_sub_id != result.data[0].id){
  156. if(_sub_site+1 == MAX_SUB_PAGES){
  157. var a = $('<span style="color:yellow; font-weight: bold; padding: 0 5px 0 5px;">!</span>');
  158. a.attr('title', 'Only the last '+ _submissions.length +' submissions are considered.');
  159. $('#stats_score, #stats_views, #stats_toptags, #stats_nsfw, #stats_most_viral').parent().children('td:nth-child(1)').append(a);
  160. }else{
  161. _last_sub_id = result.data[0].id;
  162. _sub_site += 1;
  163. get_submissions();
  164. done = false;
  165. }
  166. }
  167. if(done){
  168. if(_submissions.length > 0){
  169. // TODO: are they always returned newest first ?
  170. _last_post = _submissions[0].datetime;
  171. }
  172. calc_views();
  173. calc_score();
  174. collect_tags();
  175. get_last_comment();
  176. calc_most_viral();
  177. calc_nsfw();
  178. }
  179. }, function (a, b, c) {
  180. console.log('Failed to load', a, b, c);
  181. }
  182. );
  183. }
  184. function _get_field(array, field){
  185. var ret = Array();
  186. for(var i=0; i < array.length; ++i){
  187. ret.push(array[i][field])
  188. }
  189. return ret;
  190. }
  191. // some array funcs for convinience
  192. Array.prototype.sum = function() {
  193. return this.reduce(function(a, b) { return a + b; }, 0);
  194. };
  195. Array.prototype.max = function() {
  196. return Math.max.apply(null, this);
  197. };
  198. Array.prototype.min = function() {
  199. return Math.min.apply(null, this);
  200. };
  201. var round = Math.round;
  202. function calc_views(){
  203. var views = _get_field(_submissions ,'views');
  204. var view_sum = views.sum();
  205. var a = $('<span></span>');
  206. a.text(round(view_sum / views.length).toLocaleString());
  207. a.attr('title', 'All: ' + round(view_sum).toLocaleString() + ". Max: " + views.max().toLocaleString() + ". Min: " + views.min().toLocaleString() + ".");
  208. $('#stats_views').append(a).closest('td').children().show().filter('img').remove();
  209. }
  210. function calc_score(){
  211. var points = _get_field(_submissions ,'points');
  212. var ups = _get_field(_submissions ,'ups').sum() / points.length;
  213. var downs = _get_field(_submissions ,'downs').sum() / points.length;
  214. var point_sum = points.sum();
  215. var a = $('<span></span>');
  216. a.text( round(point_sum / points.length).toLocaleString());
  217. a.attr('title', 'Upvotes avg: ' + round(ups).toLocaleString() + ". Downvotes avg: " + round(downs).toLocaleString() + ".");
  218. $('#stats_score').append(a).closest('td').children().show().filter('img').remove();
  219. }
  220. function calc_most_viral(){
  221. var virals = _get_field(_submissions ,'in_most_viral');
  222. var _sum = virals.sum();
  223. if(virals.length > 0){
  224. val = Math.round((100.0 / virals.length) * _sum);
  225. }
  226. var a = $('<span></span>');
  227. a.text( val + "%" );
  228. a.attr('title', _sum + " / " + virals.length + " posts");
  229. $('#stats_most_viral').append(a).closest('td').children().show().filter('img').remove();
  230. }
  231. function calc_nsfw(){
  232. var nsfws = _get_field(_submissions ,'nsfw');
  233. var _sum = nsfws.sum();
  234. var val = 0;
  235. if(nsfws.length > 0){
  236. val = Math.round((100.0 / nsfws.length) * _sum);
  237. }
  238. var a = $('<span></span>');
  239. a.text( val + "%" );
  240. a.attr('title', _sum + " / " + nsfws.length + " posts");
  241. $('#stats_nsfw').append(a).closest('td').children().show().filter('img').remove();
  242. }
  243. function collect_tags(){
  244. console.log('collect_tags');
  245. var counter = {};
  246. for(var i=0; i < _submissions.length; ++i){
  247. var tags = _submissions[i].tags;
  248. for(var j=0; j < tags.length; ++j){
  249. var count = 1; var k = tags[j].display_name;
  250. if( k in counter ){
  251. count += counter[k][0];
  252. }
  253. counter[k] = [count, tags[j]];
  254. }
  255. }
  256. var vals = Object.values(counter);
  257. vals.sort(function(a, b) {
  258. return b[0] - a[0];
  259. });
  260. $('#stats_toptags').children().show().filter('img').remove();
  261. for(var i=0; i < 5 && i < vals.length; ++i){
  262. var node = $('<a>-</a><br>');
  263. node.filter('a').text(vals[i][1].display_name).attr('title', "Used "+vals[i][0]+" times").attr('href', 'https://imgur.com/t/'+vals[i][1].name);
  264. $('#stats_toptags').append(node);
  265. }
  266. }
  267. }
  268. function get_last_comment(){
  269. request_user_info('comments/newest', function (result, status, request) {
  270. if(result.data.length == 0 && _last_post == -1){
  271. $('#stats_last_active').text('-');
  272. return;
  273. }
  274. if(result.data.length == 0) return;
  275. var d = result.data[0].datetime;
  276. var link = result.data[0].datetime;
  277. if(d > _last_post){
  278. link = 'https://imgur.com/gallery/' +result.data[0].image_id+ '/comment/' + result.data[0].id;
  279. }else{
  280. link = 'https://imgur.com/gallery/' + _submissions[0].id;
  281. d = _last_post;
  282. }
  283. var delta = (new Date().getTime()/1000) - d;
  284. function pluralize(val, word){
  285. val = Math.floor(val);
  286. return val + " " + Imgur.Util.pluralize(val, word);
  287. }
  288. // thats propably somewhere already
  289. if(delta >= 356*24*60*60) delta = pluralize(delta / (356*24*60*60), " year");
  290. else if(delta >= 24*60*60) delta = pluralize(delta / (24*60*60), " day");
  291. else if(delta >= 60*60) delta = pluralize(delta / (60*60), " hour");
  292. else if(delta >= 60) delta = pluralize(delta / 60, " minute");
  293. else delta = pluralize(delta, " second");
  294. d = new Date(d * 1000);
  295. var a = $('<a></a>').attr('href', link).text(delta + " ago").attr('title', d.toLocaleDateString() + " " + d.toLocaleTimeString());
  296. $('#stats_last_active').append(a).children().show().filter('img').remove();
  297. }, function (a, b, c) {
  298. console.log('Failed to load', a, b, c);
  299. $('#stats_last_active').text('Failed to load comment').closest('td').children().show().filter('img').remove();
  300. }
  301. );
  302. }
  303. });