Geocaching.com + Project-GC

Adds links and data to Geocaching.com to make it collaborate with PGC

2017-02-27 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

  1. /* global $: true */
  2. /* global waitForKeyElements: true */
  3. /* global GM_xmlhttpRequest: true */
  4. /* global GM_getValue: true */
  5. /* global GM_setValue: true */
  6. /* global unsafeWindow: true */
  7. // jshint newcap:false
  8. // jshint multistr:true
  9.  
  10. // ==UserScript==
  11. // @name Geocaching.com + Project-GC
  12. // @namespace PGC
  13. // @description Adds links and data to Geocaching.com to make it collaborate with PGC
  14. // @include http://www.geocaching.com/*
  15. // @include https://www.geocaching.com/*
  16. // @version 1.7.1
  17. // @require http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js
  18. // @require https://greatest.deepsurf.us/scripts/5392-waitforkeyelements/code/WaitForKeyElements.js?version=19641
  19. // @grant GM_xmlhttpRequest
  20. // @grant GM_setValue
  21. // @grant GM_getValue
  22. // @grant GM_addStyle
  23. // @license The MIT License (MIT)
  24. // ==/UserScript==
  25.  
  26.  
  27. (function() {
  28.  
  29. 'use strict';
  30.  
  31. var pgcUrl = 'http://project-gc.com/',
  32. pgcApiUrl = pgcUrl + 'api/gm/v1/',
  33. externalLinkIcon = 'http://maxcdn.project-gc.com/images/external_small.png',
  34. galleryLinkIcon = 'http://maxcdn.project-gc.com/images/pictures_16.png',
  35. mapLinkIcon = 'http://maxcdn.project-gc.com/images/map_app_16.png',
  36. loggedIn = null,
  37. subscription = null,
  38. pgcUsername = null,
  39. gccomUsername = null,
  40. latestLogs = [],
  41. latestLogsAlert = false,
  42. settings = {},
  43. path = window.location.pathname;
  44.  
  45. // Don't run the script for iframes
  46. if (window.top == window.self) {
  47. Main();
  48. }
  49.  
  50. function Main() {
  51. ReadSettings();
  52. CheckPGCLogin();
  53. }
  54.  
  55. function Router() {
  56. if (path.match(/^\/geocache\/.*/) !== null) {
  57. Page_CachePage();
  58. } else if (path.match(/^\/seek\/cache_details\.aspx.*/) !== null) {
  59. Page_CachePage();
  60. } else if (path.match(/^\/seek\/cache_logbook\.aspx.*/) !== null) {
  61. Page_Logbook();
  62. } else if (path.match(/^\/bookmarks\/.*/) !== null) {
  63. Page_Bookmarks();
  64. } else if (path.match(/^\/map\/.*/) !== null) {
  65. Page_Map();
  66. } else if(path.match(/^\/seek\/gallery\.aspx.*/) !== null) {
  67. Page_Gallery();
  68. } else if(path.match(/^\/profile\/.*/) !== null) {
  69. Page_Profile();
  70. }
  71.  
  72. }
  73.  
  74. function GetSettingsItems() {
  75. var items = {
  76. showVGPS: {
  77. title: 'Show Virtual GPS',
  78. default: true
  79. },
  80. addChallengeCheckers: {
  81. title: 'Add challenge checkers',
  82. default: true
  83. },
  84. makeCopyFriendly: {
  85. title: 'Make copy friendly GC-Code and link',
  86. default: true
  87. },
  88. addPgcMapLinks: {
  89. title: 'Add PGC map links',
  90. default: true
  91. },
  92. addLatestLogs: {
  93. title: 'Add latest logs',
  94. default: true
  95. },
  96. cloneLogsPerType: {
  97. title: 'Clone number of logs per type',
  98. default: true
  99. },
  100. addPGCLocation: {
  101. title: 'Add PGC Location',
  102. default: true
  103. },
  104. addAddress: {
  105. title: 'Add reverse geocoded address',
  106. default: true
  107. },
  108. removeUTM: {
  109. title: 'Remove UTM coordinates',
  110. default: true
  111. },
  112. addPgcFp: {
  113. title: 'Add FP from PGC',
  114. default: true
  115. },
  116. profileStatsLinks: {
  117. title: 'Add links to Profile stats',
  118. default: true
  119. },
  120. tidy: {
  121. title: 'Tidy the web a bit',
  122. default: true
  123. },
  124. collapseDownloads: {
  125. title: 'Collapse download links',
  126. default: false
  127. },
  128. addPgcGalleryLinks: {
  129. title: 'Add links to PGC gallery',
  130. default: true
  131. },
  132. addMapBookmarkListLinks: {
  133. title: 'Add links for bookmark lists',
  134. default: true
  135. },
  136. decryptHints: {
  137. title: 'Automatically decrypt hints',
  138. default: true
  139. },
  140. addElevation: {
  141. title: 'Add elevation',
  142. default: true
  143. },
  144. imperial: {
  145. title: 'Use imperial units',
  146. default: false
  147. },
  148. removeDisclaimer: {
  149. title: 'Remove disclaimer',
  150. default: false
  151. },
  152. parseExifLocation: {
  153. title: 'Parse Exif location',
  154. default: true
  155. },
  156. addGeocacheLogsPerProfileCountry: {
  157. title: 'Geocachelogs per profile country',
  158. default: true
  159. }
  160. };
  161. return items;
  162. }
  163.  
  164. function ReadSettings() {
  165. settings = GM_getValue('settings');
  166. if (typeof(settings) != 'undefined') {
  167. settings = JSON.parse(settings);
  168. if (settings === null) {
  169. settings = [];
  170. }
  171. } else {
  172. settings = [];
  173. }
  174.  
  175. var items = GetSettingsItems();
  176. for (var item in items) {
  177. if (typeof(settings[item]) == 'undefined') {
  178. settings[item] = items[item].default;
  179. }
  180. }
  181. }
  182.  
  183. function SaveSettings(e) {
  184. e.preventDefault();
  185. settings = {};
  186.  
  187. for (var item in GetSettingsItems()) {
  188. settings[item] = Boolean($('#pgcUserMenuForm input[name="' + item + '"]').is(':checked'));
  189. }
  190.  
  191. var json = JSON.stringify(settings);
  192. GM_setValue('settings', json);
  193.  
  194. $('#pgcUserMenuWarning').css('display', 'inherit');
  195. }
  196.  
  197. function IsSettingEnabled(setting) {
  198. return settings[setting];
  199. }
  200.  
  201. function MetersToFeet(meters) {
  202. return Math.round(meters * 3.28084);
  203. }
  204.  
  205. function FormatDistance(distance) {
  206. distance = parseInt(distance, 10);
  207. distance = IsSettingEnabled('imperial') ? MetersToFeet(distance) : distance;
  208. distance = distance.toLocaleString();
  209.  
  210. return distance;
  211. }
  212.  
  213. function GetCoordinatesFromExif(exif) {
  214. var GPSLatitudeRef = EXIF.getTag(exif, "GPSLatitudeRef"),
  215. GPSLatitude = EXIF.getTag(exif, "GPSLatitude"),
  216. GPSLongitudeRef = EXIF.getTag(exif, "GPSLongitudeRef"),
  217. GPSLongitude = EXIF.getTag(exif, "GPSLongitude");
  218.  
  219. if (typeof(GPSLatitude) === 'undefined' || isNaN(GPSLatitude[0]) || isNaN(GPSLatitude[1]) || isNaN(GPSLatitude[1]) ||
  220. isNaN(GPSLongitude[0]) || isNaN(GPSLongitude[1]) || isNaN(GPSLongitude[1])) {
  221. return false;
  222. }
  223.  
  224. // Create a latitude DD.DDD
  225. var tmp = Number(GPSLatitude[0]) + Number(GPSLatitude[1]) / 60 + Number(GPSLatitude[2]) / 60 / 60,
  226. coords = '';
  227.  
  228. coords += GPSLatitudeRef;
  229. var d = Math.floor(tmp);
  230. if (d < 10) {
  231. coords += '0' + d;
  232. } else {
  233. coords += d;
  234. }
  235. tmp = (tmp - d) * 60;
  236. coords += ' ';
  237. var m = Math.floor(tmp);
  238. if (m < 10) {
  239. coords += '0' + m;
  240. } else {
  241. coords += m;
  242. }
  243. tmp = (tmp - m) * 1000;
  244. coords += '.';
  245. var decimals = Math.round(tmp, 3);
  246. if (decimals < 10) {
  247. coords += '00' + decimals;
  248. } else if (decimals < 100) {
  249. coords += '0' + decimals;
  250. } else {
  251. coords += decimals;
  252. }
  253.  
  254. coords += ' ';
  255.  
  256. // Create a longitude DD.DDD
  257. var tmp = Number(GPSLongitude[0]) + Number(GPSLongitude[1]) / 60 + Number(GPSLongitude[2]) / 60 / 60;
  258.  
  259. coords += GPSLongitudeRef;
  260. var d = Math.floor(tmp);
  261. if (d < 10) {
  262. coords += '00' + d;
  263. } else if (GPSLongitude[0] < 100) {
  264. coords += '0' + d;
  265. } else {
  266. coords += d;
  267. }
  268. tmp = (tmp - d) * 60;
  269. coords += ' ';
  270. var m = Math.floor(tmp);
  271. if (m < 10) {
  272. coords += '0' + m;
  273. } else {
  274. coords += m;
  275. }
  276. tmp = (tmp - m) * 1000;
  277. coords += '.';
  278. var decimals = Math.round(tmp, 3);
  279. if (decimals < 10) {
  280. coords += '00' + decimals;
  281. } else if (decimals < 100) {
  282. coords += '0' + decimals;
  283. } else {
  284. coords += decimals;
  285. }
  286.  
  287. return coords;
  288. }
  289.  
  290. /**
  291. * Check that we are authenticated at Project-GC.com, and that it's with the same username
  292. */
  293. function CheckPGCLogin() {
  294. GM_xmlhttpRequest({
  295. method: "GET",
  296. url: pgcApiUrl + 'GetMyUsername',
  297. onload: function(response) {
  298. var result = JSON.parse(response.responseText);
  299.  
  300. if (result.status !== 'OK') {
  301. alert(response.responseText);
  302. return false;
  303. }
  304.  
  305. pgcUsername = result.data.username;
  306. loggedIn = Boolean(result.data.loggedIn);
  307. subscription = Boolean(result.data.subscription);
  308.  
  309. BuildPGCUserMenu();
  310. Router();
  311. },
  312. onerror: function(response) {
  313. alert(response);
  314. return false;
  315. }
  316. });
  317. }
  318.  
  319. function BuildPGCUserMenu() {
  320. var loggedInContent, html, subscriptionContent = '', profileStatsUrl;
  321.  
  322. gccomUsername = false;
  323. if ($('#ctl00_uxLoginStatus_divSignedIn ul.logged-in-user').length) {
  324. gccomUsername = $('#ctl00_uxLoginStatus_divSignedIn ul.logged-in-user .li-user-info span').html();
  325. } else if ($('ul.profile-panel-menu').length) {
  326. gccomUsername = $('ul.profile-panel-menu .li-user-info span:nth-child(2)').text();
  327. } else if ($('#uxLoginStatus_divSignedIn ul.logged-in-user li.li-user span.li-user-info span').first().text().length) {
  328. gccomUsername = $('#uxLoginStatus_divSignedIn ul.logged-in-user li.li-user span.li-user-info span').first().text();
  329. } else if ($('ul.profile-panel.detailed').length) {
  330. gccomUsername = $('ul.profile-panel.detailed > li.li-user > a > span:nth-child(2)').text();
  331. }
  332.  
  333. if (loggedIn === false) {
  334. loggedInContent = 'Not logged in';
  335. profileStatsUrl = pgcUrl + 'User/Login';
  336. } else {
  337. profileStatsUrl = pgcUrl + 'ProfileStats/' + pgcUsername;
  338.  
  339. if (pgcUsername == gccomUsername) {
  340. loggedInContent = '<strong>' + pgcUsername + '</strong>';
  341. } else {
  342. loggedInContent = '<strong style="color: red;">' + pgcUsername + '</strong>';
  343. }
  344.  
  345. if (subscription) {
  346. subscriptionContent = 'Paid membership';
  347. } else {
  348. subscriptionContent = 'Missing membership';
  349. }
  350. }
  351.  
  352. GM_addStyle('\
  353. #pgcUserMenuForm > li:hover { background-color: #e3dfc9; }\
  354. #pgcUserMenuForm > li { display: block; }\
  355. #pgcUserMenuForm input[type="checkbox"] { opacity: inherit; width: inherit; height:inherit; overflow:inherit; position:inherit; }\
  356. #pgcUserMenuForm button { display: inline-block; background: none; border-width: 0; }\
  357. ');
  358.  
  359. html = '\
  360. <div onclick="$(\'#pgcUserMenu, #pgcSettingsOverlay\').toggle();" style="position: fixed; top: 0; bottom: 0; left: 0; right: 0; z-index:1004; display: none;" id="pgcSettingsOverlay"></div>\
  361. <div>\
  362. <a class="SignedInProfileLink" href="' + pgcUrl + '" title="Project-GC">\
  363. <span class="avatar">\
  364. <img src="http://project-gc.com/favicon.ico" alt="Logo" width="30" height="30" style="border-radius:100%; border-width:0;">\
  365. </span>\
  366. </a>\
  367. <span class="li-user-info">\
  368. <a class="SignedInProfileLink" href="' + profileStatsUrl + '" title="Project-GC">\
  369. <span style="display: block;">' + loggedInContent + '</span>\
  370. </a>\
  371. <a class="SignedInProfileLink" href="' + pgcUrl + 'Home/Membership/" title="Project-GC">\
  372. <span class="cache-count">' + subscriptionContent + '</span>\
  373. </a>\
  374. </span>\
  375. <button id="pgcUserMenuButton" type="button" class="li-user-toggle" onclick="$(\'#pgcUserMenu, #pgcSettingsOverlay\').toggle();">\
  376. <svg width="12px" height="7px" viewBox="0 0 12 7" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><g class="arrow" transform="translate(-1277.000000, -25.000000)" stroke="#FFFFFF" fill="#FFFFFF"><path d="M1280.43401,23.3387013 C1280.20315,23.5702719 1280.20315,23.945803 1280.43401,24.1775793 L1284.82138,28.5825631 L1280.43401,32.9873411 C1280.20315,33.2191175 1280.20315,33.5944429 1280.43401,33.8262192 C1280.54934,33.9420045 1280.70072,34 1280.8519,34 C1281.00307,34 1281.15425,33.9422102 1281.26978,33.8262192 L1286.07462,29.0018993 C1286.30548,28.7701229 1286.30548,28.3947975 1286.07462,28.1630212 L1281.26958,23.3387013 C1281.03872,23.106925 1280.66487,23.106925 1280.43401,23.3387013 Z" id="Dropdown-arrow" sketch:type="MSShapeGroup" transform="translate(1283.254319, 28.582435) scale(1, -1) rotate(-90.000000) translate(-1283.254319, -28.582435) "></path></g></g></svg>\
  377. </button>\
  378. </div>\
  379. <ul id="pgcUserMenu" style="z-index: 1005; display: none; text-align: left;">\
  380. <form id="pgcUserMenuForm" style="color: #5f452a;">';
  381.  
  382. var items = GetSettingsItems(),
  383. isChecked = '';
  384. for (var item in items) {
  385. isChecked = IsSettingEnabled(item) ? ' checked="checked"' : '';
  386. // Explicitly set the styles as some pages (i.e. https://www.geocaching.com/account/settings/profile) are missing the required css.
  387. html += '<li style="margin: .2em 1em; white-space: nowrap;"><label style="font-weight: inherit; margin-bottom: 0"><input type="checkbox" name="' + item + '"' + isChecked + '>&nbsp;' + items[item].title + '</label></li>';
  388. }
  389.  
  390. html += '\
  391. <li style="margin: .2em 1em;">\
  392. <button onclick="document.getElementById(\'pgcUserMenuForm\').reset(); $(\'#pgcUserMenu\').hide(); return false;">Cancel</button>\
  393. &nbsp;<button onclick="document.getElementById(\'pgcUserMenuForm\').reset(); return false;">Reset</button>\
  394. &nbsp;<button id="pgcUserMenuSave">Save</button>\
  395. </li>\
  396. <li id="pgcUserMenuWarning" style="display: none; margin: .5em 1em;"><small class="OldWarning"><a href="#" onclick="location.reload();" style="padding: 0; text-decoration: underline;">Reload</a> the page to activate the new settings.</small></li>\
  397. </form>\
  398. </ul>';
  399.  
  400. if ($('#ctl00_uxLoginStatus_divSignedIn ul.logged-in-user').length) { // The default look of the header bar
  401. $('#ctl00_uxLoginStatus_divSignedIn ul.logged-in-user').prepend('<li class="li-user">' + html + '</li>');
  402. } else if ($('ul.profile-panel li.li-user').length) { // new style, e.g. https://www.geocaching.com/play/search
  403. $('ul.profile-panel').prepend('<li class="li-user">' + html + '</li>');
  404. } else if ($('ul.profile-panel-menu').length) { // Special case for https://www.geocaching.com/account/settings/preferences
  405. $('ul.profile-panel-menu').prepend('<li class="li-user">' + html + '</li>');
  406. } else if ($('#uxLoginStatus_divSignedIn ul.logged-in-user').length) { // Special case for https://www.geocaching.com/map/
  407. $('#uxLoginStatus_divSignedIn ul.logged-in-user').prepend('<li class="li-user">' + html + '</li>');
  408. }
  409.  
  410. $('#pgcUserMenuSave').click(function(e) {
  411. SaveSettings(e);
  412. });
  413. }
  414.  
  415. /**
  416. * getGcCodeFromPage
  417. * @return string
  418. */
  419. function getGcCodeFromPage() {
  420. return $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoCode').html();
  421. }
  422.  
  423. /**
  424. * addToVGPS
  425. */
  426. function addToVGPS(gccode) {
  427. var listId = $('#comboVGPS').val(),
  428. url = null;
  429.  
  430. if (typeof(gccode) === 'undefined') { // The map provides the gccode itself
  431. gccode = getGcCodeFromPage();
  432. }
  433.  
  434. url = pgcApiUrl + 'AddToVGPSList?listId=' + listId + '&gccode=' + gccode + '&sectionName=GM-script';
  435.  
  436.  
  437. GM_xmlhttpRequest({
  438. method: "GET",
  439. url: url,
  440. onload: function(response) {
  441. var result = JSON.parse(response.responseText),
  442. msg = (result.status === 'OK') ? 'Geocache added to Virtual-GPS!' : 'Geocache not added to Virtual-GPS :(';
  443.  
  444. $('#btnAddToVGPS').css('display', 'none');
  445. $('#btnRemoveFromVGPS').css('display', '');
  446.  
  447. alert(msg);
  448.  
  449. return true;
  450. },
  451. onerror: function(response) {
  452. console.log(response);
  453. return false;
  454. }
  455. });
  456. return true;
  457. }
  458.  
  459. /**
  460. * removeFromVGPS
  461. */
  462. function removeFromVGPS(gccode) {
  463. var listId = $('#comboVGPS').val(),
  464. url = null;
  465.  
  466. if (typeof(gccode) === 'undefined') { // The map provides the gccode itself
  467. gccode = getGcCodeFromPage();
  468. }
  469.  
  470. url = pgcApiUrl + 'RemoveFromVGPSList?listId=' + listId + '&gccode=' + gccode;
  471.  
  472.  
  473. GM_xmlhttpRequest({
  474. method: "GET",
  475. url: url,
  476. onload: function(response) {
  477. var result = JSON.parse(response.responseText),
  478. msg = (result.status === 'OK') ? 'Geocache removed from Virtual-GPS!' : 'Geocache not removed from Virtual-GPS :(';
  479.  
  480. $('#btnAddToVGPS').css('display', '');
  481. $('#btnRemoveFromVGPS').css('display', 'none');
  482.  
  483. alert(msg);
  484.  
  485. return true;
  486. },
  487. onerror: function(response) {
  488. console.log(response);
  489. return false;
  490. }
  491. });
  492. }
  493.  
  494. function Page_Profile() {
  495. // Override gc.com function on alerting for external links to not alert for Project-GC URLs
  496. var gcAlertOverride = document.createElement('script');
  497. gcAlertOverride.type = "text/javascript";
  498. gcAlertOverride.innerHTML = `(function() {
  499. var _old_isGeocachingDomain = isGeocachingDomain;
  500. isGeocachingDomain = function(url) {
  501. return (_old_isGeocachingDomain.apply(this, arguments)
  502. || url == "project-gc.com"
  503. || url == "www.project-gc.com");
  504. };
  505. })();`;
  506. document.getElementsByTagName('head')[0].appendChild(gcAlertOverride);
  507. }
  508.  
  509. /**
  510. * Page_CachePage
  511. */
  512. function Page_CachePage() {
  513. var gccode = getGcCodeFromPage(),
  514. placedBy = $('#ctl00_ContentBody_mcd1 a').html(),
  515. lastUpdated = $('#ctl00_ContentBody_bottomSection p small time').get(1),
  516. lastFound = $('#ctl00_ContentBody_bottomSection p small time').get(2),
  517. coordinates, latitude, longitude, url;
  518.  
  519. lastUpdated = (lastUpdated) ? lastUpdated.dateTime : false;
  520. lastFound = (lastFound) ? lastFound.dateTime : false;
  521.  
  522. // Since everything in the logbook is ajax, we need to wait for the elements
  523. waitForKeyElements('#cache_logs_table tr', Logbook);
  524.  
  525. if (subscription) {
  526.  
  527. // Get geocache data from Project-GC
  528. url = pgcApiUrl + 'GetCacheDataFromGccode&gccode=' + gccode;
  529. if (lastUpdated)
  530. url += '&lastUpdated=' + lastUpdated;
  531. if (lastFound)
  532. url += '&lastFound=' + lastFound;
  533.  
  534. GM_xmlhttpRequest({
  535. method: "GET",
  536. url: url,
  537. onload: function(response) {
  538. var result = JSON.parse(response.responseText),
  539. cacheData = result.data.cacheData,
  540. cacheOwner = result.data.owner,
  541. challengeCheckerTagIds = result.data.challengeCheckerTagIds,
  542. geocacheLogsPerCountry = result.data.geocacheLogsPerCountry,
  543. location = [],
  544. fp = 0,
  545. fpp = 0,
  546. fpw = 0,
  547. elevation = '',
  548. html = '';
  549.  
  550. if (result.status == 'OK' && typeof cacheData !== 'undefined') {
  551.  
  552. // If placed by != owner, show the real owner as well.
  553. if (placedBy !== cacheOwner) {
  554. $('#ctl00_ContentBody_mcd1 span.message__owner').before(' (' + cacheOwner + ')');
  555. }
  556.  
  557. // Append link to Profile Stats for the cache owner
  558. // Need to real cache owner name from PGC since the web only has placed by
  559. if (IsSettingEnabled('profileStatsLinks')) {
  560. $('#ctl00_ContentBody_mcd1 span.message__owner').before('<a href="' + pgcUrl + 'ProfileStats/' + encodeURIComponent(cacheOwner) + '"><img src="' + externalLinkIcon + '" title="PGC Profile Stats"></a>');
  561. }
  562.  
  563. // Add FP/FP%/FPW below the current FP
  564. if (IsSettingEnabled('addPgcFp')) {
  565. fp = parseInt(+cacheData.favorite_points, 10),
  566. fpp = parseInt(+cacheData.favorite_points_pct, 10),
  567. fpw = parseInt(+cacheData.favorite_points_wilson, 10);
  568. $('#uxFavContainerLink').append('<p style="text-align: center; background-color: #f0edeb;border-bottom-left-radius: 5px;border-bottom-right-radius:5px;">PGC: ' + fp + ' FP, ' + fpp + '%, ' + fpw + 'W</p>');
  569. $('.favorite-container').css({
  570. "border-bottom-left-radius": "0",
  571. "border-bottom-right-radius": "0"
  572. });
  573. }
  574.  
  575. // Add elevation (Metres above mean sea level = mamsl)
  576. if (IsSettingEnabled('addElevation')) {
  577. var formattedElevation = FormatDistance(cacheData.elevation),
  578. elevationUnit = IsSettingEnabled('imperial') ? 'ft' : 'm',
  579. elevationArrow = (cacheData.elevation >= 0) ? '&#x21a5;' : '&#x21a7;';
  580. elevation = formattedElevation + ' ' + elevationUnit + ' ' + elevationArrow;
  581.  
  582. if (cacheData.elevation >= 0) {
  583. html = '<span> (' + elevation + ')</span>';
  584. } else {
  585. html = '<span class="OldWarning"> (' + elevation + ')</span>';
  586. }
  587.  
  588. ($('#uxLatLonLink').length > 0 ? $('#uxLatLonLink') : $('#uxLatLon').parent()).after(html);
  589. }
  590.  
  591. // Add PGC location
  592. if (IsSettingEnabled('addPGCLocation')) {
  593. if (cacheData.country.length > 0) {
  594. location.push(cacheData.country);
  595. }
  596. if (cacheData.region !== null && cacheData.region.length > 0) {
  597. location.push(cacheData.region);
  598. }
  599. if (cacheData.county !== null && cacheData.county.length > 0) {
  600. location.push(cacheData.county);
  601. }
  602. location = location.join(' / ');
  603.  
  604. var gccomLocationData = $('#ctl00_ContentBody_Location').html();
  605. $('#ctl00_ContentBody_Location').html('<span style="text-decoration: line-through;">' + gccomLocationData + '</span><br><span>' + location + '</span>');
  606. }
  607.  
  608.  
  609. // Add challenge checkers
  610. if (IsSettingEnabled('addChallengeCheckers') && challengeCheckerTagIds.length > 0) {
  611.  
  612. html = '<div id="checkerWidget" class="CacheDetailNavigationWidget TopSpacing BottomSpacing"><h3 class="WidgetHeader">Challenge checker(s)</h3><div class="WidgetBody" id="PGC_ChallengeCheckers">';
  613. for (var i = 0; i < challengeCheckerTagIds.length; i++) {
  614. html += '<a href="http://project-gc.com/Challenges/' + gccode + '/' + challengeCheckerTagIds[i] + '" style="display: block; width: 200px; margin: 0 auto;"><img src="http://maxcdn.project-gc.com/Images/Checker/' + challengeCheckerTagIds[i] + '" title="Project-GC Challenge checker" alt="PGC Checker"></a>';
  615. }
  616. html += '</div></div>';
  617. $('#ctl00_ContentBody_detailWidget').before(html);
  618. }
  619.  
  620. // Display warning message if cache is logged and no longer be logged
  621. if (cacheData.locked) {
  622. $('ul.OldWarning').append('<li>This cache has been locked and can no longer be logged.</li>');
  623. }
  624.  
  625. // Add geocache logs per profile country table
  626. if (IsSettingEnabled('addGeocacheLogsPerProfileCountry') && geocacheLogsPerCountry.length > 0) {
  627. $('#ctl00_ContentBody_lblFindCounts').append('<div id="geocacheLogsPerCountry" style="border: dashed; border-color: #aaa; border-width: thin;"><p style="margin-left: 10px; margin-bottom: 0;"><strong>Found logs per country</strong> <small>according to Project-GC.com</small></p><ul style="list-style: none; margin-left: 0; margin-bottom: 0;"></ul></div>');
  628. for (var i = 0; i < geocacheLogsPerCountry.length; i++) {
  629. $('#geocacheLogsPerCountry ul').append('<li style="display: inline; padding-right: 20px;"><img src="//project-gc.com' + geocacheLogsPerCountry[i].flagIcon + '" alt="' + geocacheLogsPerCountry[i].country + '" title="' + geocacheLogsPerCountry[i].country + '">' + geocacheLogsPerCountry[i].cnt + '</li>');
  630. }
  631. }
  632. }
  633. }
  634. });
  635. }
  636.  
  637. // Tidy the web
  638. if (IsSettingEnabled('tidy')) {
  639. $('#ctl00_divContentMain p.Clear').css('margin', '0');
  640. $('div.Note.PersonalCacheNote').css('margin', '0');
  641. $('h3.CacheDescriptionHeader').remove();
  642. $('#ctl00_ContentBody_EncryptionKey').remove();
  643. }
  644.  
  645. // Make it easier to copy the gccode
  646. if (IsSettingEnabled('makeCopyFriendly')) {
  647. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').
  648. html('<div style="margin-right: 15px; margin-bottom: 10px;"><p id="ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoCode" style="font-size: 125%; margin-bottom: 0">' + gccode + '</p>' +
  649. '<input size="25" type="text" value="http://coord.info/' + encodeURIComponent(gccode) + '" onclick="this.setSelectionRange(0, this.value.length);"></div>');
  650. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').css('font-weight', 'inherit').css('margin-right', '39px');
  651. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel div').css('margin', '0 0 5px 0');
  652. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel div p').css('font-weight', 'bold');
  653. }
  654.  
  655. // Add PGC Map links
  656. if (IsSettingEnabled('addPgcMapLinks')) {
  657. coordinates = $('#ctl00_ContentBody_MapLinks_MapLinks li a').attr('href'),
  658. latitude = coordinates.replace(/.*lat=([^&]*)&lng=.*/, "$1"),
  659. longitude = coordinates.replace(/.*&lng=(.*)$/, "$1");
  660. // var mapUrl = pgcUrl + 'Maps/mapcompare/?profile_name=' + gccomUsername +
  661. // '&nonefound=on&ownfound=on&location=' + latitude + ',' + longitude +
  662. // '&max_distance=5&submit=Filter';
  663. var mapUrl = pgcUrl + 'LiveMap/#c=' + latitude + ',' + longitude + ';z=14';
  664.  
  665. // $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').append(
  666. // '<div style="margin-bottom: 8px;"><a target="_blank" href="' + mapUrl + '">Project-GC map</a> (<a target="_blank" href="' + mapUrl + '&onefound=on">incl found</a>)</div>'
  667. // );
  668. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').append(
  669. '<div style="margin-bottom: 8px;"><a target="_blank" href="' + mapUrl + '">Project-GC Live map</a></div>'
  670. );
  671. }
  672.  
  673. // Remove the UTM coordinates
  674. // $('#ctl00_ContentBody_CacheInformationTable div.LocationData div.span-9 p.NoBottomSpacing br').remove();
  675. if (IsSettingEnabled('removeUTM')) {
  676. $('#ctl00_ContentBody_LocationSubPanel').html('');
  677.  
  678. // And move the "N 248.3 km from your home location"
  679. $('#ctl00_ContentBody_LocationSubPanel').after($('#lblDistFromHome'));
  680. }
  681.  
  682. // Remove ads
  683. // PGC can't really do this officially
  684. // $('#ctl00_ContentBody_uxBanManWidget').remove();
  685.  
  686. // Remove disclaimer
  687. if (IsSettingEnabled('removeDisclaimer')) {
  688. $('#divContentMain div.span-17 div.Note.Disclaimer').remove();
  689. }
  690.  
  691. // If the first log is a DNF, display a blue warning on top of the page
  692. if($('#cache_logs_table tr:first td div.LogDisplayRight strong img').attr('src') === '/images/logtypes/3.png') {
  693. var htmlFirstLogDnf = '<p style="color: #006cff;" class=" NoBottomSpacing"><strong>Cache Issues:</strong></p>\
  694. <ul style="color: #006cff;" class="">\
  695. <li>The latest log for this cache is a DNF, <a href="#cache_logs_table">please read the log</a> before your own search.</li>\
  696. </ul>';
  697. $('div.span-6.right.last').next().after(htmlFirstLogDnf);
  698.  
  699. }
  700.  
  701. // Collapse download links
  702. // http://www.w3schools.com/charsets/ref_utf_geometric.asp (x25BA, x25BC)
  703. if (IsSettingEnabled('collapseDownloads')) {
  704. $('<p style="cursor: pointer; margin: 0;" id="DownloadLinksToggle" onclick="$(\'#divContentMain div.DownloadLinks, #DownloadLinksToggle .arrow\').toggle();"><span class="arrow">&#x25BA;</span><span class="arrow open">&#x25BC;</span>Print and Downloads</p>').insertBefore('#divContentMain div.DownloadLinks');
  705. $('#divContentMain div.DownloadLinks, #DownloadLinksToggle .arrow.open').hide();
  706. }
  707.  
  708. // Resolve the coordinates into an address
  709. if (IsSettingEnabled('addAddress')) {
  710. coordinates = $('#ctl00_ContentBody_MapLinks_MapLinks li a').attr('href'),
  711. latitude = coordinates.replace(/.*lat=([^&]*)&lng=.*/, "$1"),
  712. longitude = coordinates.replace(/.*&lng=(.*)$/, "$1"),
  713. url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=false';
  714.  
  715. GM_xmlhttpRequest({
  716. method: "GET",
  717. url: url,
  718. onload: function(response) {
  719. var result = JSON.parse(response.responseText);
  720. if (result.status !== 'OK') {
  721. return false;
  722. }
  723. var formattedAddress = result.results[0].formatted_address;
  724. $('#ctl00_ContentBody_LocationSubPanel').append(formattedAddress + '<br />');
  725. }
  726. });
  727. }
  728.  
  729. // Add number of finds per type to the top
  730. if (IsSettingEnabled('cloneLogsPerType') && typeof $('#ctl00_ContentBody_lblFindCounts').html() !== 'undefined') {
  731. $('#ctl00_ContentBody_CacheInformationTable').before('<div>' + $('#ctl00_ContentBody_lblFindCounts').html() + '</div>');
  732. }
  733.  
  734. // Add link to PGC gallery
  735. if (subscription && IsSettingEnabled('addPgcGalleryLinks')) {
  736. var html = '<a href="' + pgcUrl + 'Tools/Gallery?gccode=' + gccode + '&submit=Filter"><img src="' + galleryLinkIcon + '" title="Project-GC Gallery"></a> ';
  737. $('.CacheDetailNavigation ul li:first').append(html);
  738. }
  739.  
  740. // Add map links for each bookmarklist
  741. if (IsSettingEnabled('addMapBookmarkListLinks')) {
  742. $('ul.BookmarkList li').each(function() {
  743. var guid = $(this).children(':nth-child(1)').attr('href').replace(/.*\?guid=(.*)/, "$1");
  744. var owner = $(this).children(':nth-child(3)').text();
  745.  
  746. // Add the map link
  747. url = 'http://project-gc.com/Tools/MapBookmarklist?owner_name=' + encodeURIComponent(owner) + '&guid=' + encodeURIComponent(guid);
  748. $(this).children(':nth-child(1)').append('&nbsp;<a href="' + url + '"><img src="' + mapLinkIcon + '" title="Map with Project-GC"></a>');
  749.  
  750. // Add gallery link for the bookmark list
  751. url = 'http://project-gc.com/Tools/Gallery?bml_owner=' + encodeURIComponent(owner) + '&bml_guid=' + encodeURIComponent(guid) + '&submit=Filter';
  752. $(this).children(':nth-child(1)').append('&nbsp;<a href="' + url + '"><img src="' + galleryLinkIcon + '" title="Project-GC Gallery"></a>');
  753.  
  754. // Add profile stats link to the owner
  755. url = 'http://project-gc.com/ProfileStats/' + encodeURIComponent(owner);
  756. $(this).children(':nth-child(3)').append('&nbsp;<a href="' + url + '"><img src="' + externalLinkIcon + '" title="Project-GC Profile stats"></a>');
  757. });
  758. }
  759.  
  760. // Decrypt the hint
  761. if (IsSettingEnabled('decryptHints')) {
  762. unsafeWindow.dht();
  763. }
  764.  
  765. // VGPS form
  766. if (IsSettingEnabled('showVGPS')) {
  767. GM_xmlhttpRequest({
  768. method: "GET",
  769. url: pgcApiUrl + 'GetExistingVGPSLists?gccode=' + gccode,
  770. onload: function(response) {
  771. var result = JSON.parse(response.responseText),
  772. vgpsLists = result.data.lists,
  773. selected = result.data.selected,
  774. existsIn = result.data.existsIn,
  775. selectedContent,
  776. existsContent,
  777. html = '<li><img width="16" height="16" src="http://maxcdn.project-gc.com/images/mobile_telephone_32.png"> <strong>Add to VGPS</strong><br />',
  778. listId;
  779.  
  780. html += '<select id="comboVGPS" style="width: 138px;">';
  781. for (listId in vgpsLists) {
  782. selectedContent = '';
  783. if (+selected === +listId) {
  784. selectedContent = ' selected="selected"';
  785. }
  786.  
  787. existsContent = '';
  788. if (existsIn.indexOf(listId) > -1) {
  789. existsContent = ' data-exists="true"';
  790. }
  791. html += '<option value="' + listId + '"' + selectedContent + existsContent + '>' + vgpsLists[listId].name + '</option>';
  792. }
  793. html += '</select>';
  794. if (existsIn.indexOf(String(selected)) == -1) {
  795. html += '&nbsp;<button id="btnAddToVGPS">+</button>';
  796. html += '&nbsp;<button id="btnRemoveFromVGPS" style="display: none;">-</button>';
  797. } else {
  798. html += '&nbsp;<button id="btnAddToVGPS" style="display: none;">+</button>';
  799. html += '&nbsp;<button id="btnRemoveFromVGPS">-</button>';
  800. }
  801. html += '</li>';
  802.  
  803. $('div.CacheDetailNavigation ul:first').append(html);
  804.  
  805. $('#comboVGPS').change(function() {
  806. selected = $(this).find(':selected').val();
  807. if (existsIn.indexOf(String(selected)) == -1) {
  808. $('#btnAddToVGPS').css('display', '');
  809. $('#btnRemoveFromVGPS').css('display', 'none');
  810. } else {
  811. $('#btnAddToVGPS').css('display', 'none');
  812. $('#btnRemoveFromVGPS').css('display', '');
  813. }
  814. });
  815. $('#btnAddToVGPS').click(function(event) {
  816. event.preventDefault();
  817. addToVGPS();
  818. });
  819. $('#btnRemoveFromVGPS').click(function(event) {
  820. event.preventDefault();
  821. removeFromVGPS();
  822. });
  823. }
  824. });
  825. }
  826. }
  827.  
  828. function Page_Logbook() {
  829. // Since everything in the logbook is ajax, we need to wait for the elements
  830. waitForKeyElements('#AllLogs tr', Logbook);
  831. waitForKeyElements('#PersonalLogs tr', Logbook);
  832. waitForKeyElements('#FriendLogs tr', Logbook);
  833. }
  834.  
  835. function Logbook(jNode) {
  836. // Add Profile stats and gallery links after each user
  837. if (IsSettingEnabled('profileStatsLinks')) {
  838. var profileNameElm = $(jNode).find('p.logOwnerProfileName strong a');
  839. var profileName = profileNameElm.html();
  840.  
  841. if (typeof profileName !== 'undefined') {
  842. profileName = profileNameElm.append('<a href="' + pgcUrl + 'ProfileStats/' + encodeURIComponent(profileName) + '"><img src="' + externalLinkIcon + '" title="PGC Profile Stats"></a>')
  843. .append('<a href="' + pgcUrl + 'Tools/Gallery?profile_name=' + encodeURIComponent(profileName) + '&submit=Filter"><img src="' + galleryLinkIcon + '" title="PGC Gallery"></a>');
  844. }
  845. }
  846.  
  847. if(IsSettingEnabled('parseExifLocation')) {
  848. $(jNode).find('table.LogImagesTable tr>td').each(function() {
  849. var url = $(this).find('a.tb_images').attr('href');
  850. var thumbnailUrl = url.replace('/img.geocaching.com/cache/log/large/', '/img.geocaching.com/cache/log/thumb/');
  851.  
  852. var imgElm = $(this).find('img');
  853. $(imgElm).attr('src', thumbnailUrl);
  854. $(imgElm).next().css('vertical-align', 'top');
  855.  
  856. $(imgElm).load(function() {
  857. EXIF.getData($(imgElm)[0], function() {
  858. // console.log(EXIF.pretty(this));
  859. var coords = GetCoordinatesFromExif(this);
  860. if(coords != false) {
  861. $('<span style="color: #8c0b0b; font-weight: bold;">EXIF Location: <a href="http://maps.google.com/?q=' + coords + '" target="_blank">' + coords + '</a></span>').insertAfter($(imgElm).parent());
  862. }
  863. });
  864. });
  865.  
  866. });
  867. }
  868.  
  869.  
  870. // Save to latest logs
  871. if (latestLogs.length < 5) {
  872. var node = $(jNode).find('div.HalfLeft.LogType strong img[src]'),
  873. logType = {};
  874.  
  875. if (node.length === 0)
  876. return false;
  877.  
  878. logType = {
  879. 'src': node.attr('src'),
  880. 'alt': node.attr('alt'),
  881. 'title': node.attr('title')
  882. };
  883.  
  884. logType.id = +logType.src.replace(/.*logtypes\/(\d+)\.png/, "$1");
  885.  
  886. // First entry is undefined, due to ajax
  887. if (logType.src) {
  888. latestLogs.push('<img src="' + logType.src + '" alt="' + logType.alt + '" title="' + logType.title + '" style="margin-bottom: -4px; margin-right: 1px;">');
  889. // 2 = found, 3 = dnf, 4 = note, 5 = archive, 22 = disable, 24 = publish, 45 = nm, 46 = owner maintenance, 68 = reviewer note
  890. if ($.inArray(logType.id, [3, 5, 22, 45, 68]) !== -1) {
  891. latestLogsAlert = true;
  892. }
  893. }
  894.  
  895. // Show latest logs
  896. // Enhanced Nov 2016 to show icons for up to 5 of the latest logs
  897. if (IsSettingEnabled('addLatestLogs') && latestLogs.length <= 5) {
  898. var images = latestLogs.join('');
  899.  
  900. $('#latestLogIcons').remove();
  901. $('#ctl00_ContentBody_size p').removeClass('AlignCenter').addClass('NoBottomSpacing');
  902.  
  903. if (latestLogsAlert) {
  904. $('#ctl00_ContentBody_size').append('<p class="NoBottomSpacing OldWarning" id="latestLogIcons"><strong>Latest logs:</strong> <span>' + images + '</span></p>');
  905. } else {
  906. $('#ctl00_ContentBody_size').append('<p class="NoBottomSpacing" id="latestLogIcons">Latest logs: <span>' + images + '</span></p>');
  907. }
  908. }
  909. }
  910. }
  911.  
  912. function Page_Map() {
  913. if (IsSettingEnabled('showVGPS')) {
  914.  
  915. setTimeout(function() {
  916. $('#map_canvas div.leaflet-popup-pane').bind('DOMSubtreeModified', function() {
  917. if ($('#pgc_vgps').length === 0) {
  918. var gccode = $('#gmCacheInfo div.code').text();
  919.  
  920. $('#gmCacheInfo div.links').after('<div id="pgc_vgps"></div>');
  921.  
  922. GM_xmlhttpRequest({
  923. method: "GET",
  924. url: pgcApiUrl + 'GetExistingVGPSLists?gccode=' + gccode,
  925. onload: function(response) {
  926.  
  927. var result = JSON.parse(response.responseText),
  928. vgpsLists = result.data.lists,
  929. selected = result.data.selected,
  930. existsIn = result.data.existsIn,
  931. selectedContent,
  932. existsContent,
  933. html,
  934. listId;
  935.  
  936.  
  937. html = '<img src="http://maxcdn.project-gc.com/images/mobile_telephone_32.png" style="width: 24px; height: 24px; margin-bottom: -6px;">';
  938.  
  939. html += '<select id="comboVGPS" style="margin-bottom: 4px;">';
  940. for (listId in vgpsLists) {
  941. selectedContent = '';
  942. if (+selected === +listId) {
  943. selectedContent = ' selected="selected"';
  944. }
  945.  
  946. html += '<option value="' + listId + '"' + selectedContent + existsContent + '>' + vgpsLists[listId].name + '</option>';
  947. }
  948. html += '</select>';
  949.  
  950. if (existsIn.indexOf(String(selected)) == -1) {
  951. html += '&nbsp;<button id="btnAddToVGPS">+</button>';
  952. html += '&nbsp;<button id="btnRemoveFromVGPS" style="display: none;">-</button>';
  953. } else {
  954. html += '&nbsp;<button id="btnAddToVGPS" style="display: none;">+</button>';
  955. html += '&nbsp;<button id="btnRemoveFromVGPS">-</button>';
  956. }
  957.  
  958. $('#pgc_vgps').html(html);
  959.  
  960.  
  961. $('#btnAddToVGPS').click(function(event) {
  962. event.preventDefault();
  963. addToVGPS(gccode);
  964. });
  965. $('#btnRemoveFromVGPS').click(function(event) {
  966. event.preventDefault();
  967. removeFromVGPS(gccode);
  968. });
  969. }
  970. });
  971. }
  972. });
  973. }, 500);
  974. }
  975.  
  976. }
  977.  
  978. function Page_Gallery() {
  979. // Find location data in exif tags
  980. if(IsSettingEnabled('parseExifLocation')) {
  981. $(window).load(function() { // Wait until page is loaded. If the images aren't loaded before this starts it will fail.
  982. $('#ctl00_ContentBody_GalleryItems_DataListGallery img').each(function() {
  983. EXIF.getData($(this)[0], function() {
  984. // console.log(EXIF.pretty(this));
  985. var coords = GetCoordinatesFromExif(this);
  986. if(coords != false) {
  987. $('<span class="OldWarning">EXIF Location<br><a href="http://maps.google.com/?q=' + coords + '" target="_blank">' + coords + '</a></span>').insertAfter(this.parentNode);
  988. }
  989. });
  990. });
  991. });
  992. }
  993. }
  994.  
  995. function Page_Bookmarks() {
  996. var owner_name = $("#ctl00_ContentBody_ListInfo_uxListOwner").text();
  997.  
  998. var search = window.location.search;
  999. var guid_start = search.indexOf("guid=");
  1000. if (guid_start == -1) {
  1001. /* the guid= not found in URL
  1002. * something is wrong so we will not generate bad URL
  1003. */
  1004. return;
  1005. }
  1006. var guid = search.substr(guid_start + 5/*, eof */);
  1007.  
  1008. var url = "http://project-gc.com/Tools/MapBookmarklist?owner_name=" + owner_name + "&guid=" + guid;
  1009. var icon = "http://maxcdn.project-gc.com/images/map_app_16.png";
  1010.  
  1011. /* Heading link */
  1012. var html = ' <a href="' + url + '" title="Map this Bookmark list using Project-GC" style="padding-left:20px;"><img src="' + icon + '" /> Map this!</a>';
  1013.  
  1014. $("#ctl00_ContentBody_lbHeading").after(html);
  1015.  
  1016. /* Footer button */
  1017. var html2 = '<p><input type="button" onclick="window.location.href= \'' + url + '\'" value="Map this Bookmark list on Project-GC" /></p>';
  1018.  
  1019. $("#ctl00_ContentBody_ListInfo_btnDownload").parent().before(html2);
  1020. }
  1021.  
  1022. }());
  1023.  
  1024.  
  1025.  
  1026. // https://github.com/exif-js/exif-js adjusted to use GM_xmlhttpRequest
  1027. (function() {
  1028. var debug = false;
  1029.  
  1030. var root = this;
  1031.  
  1032. var EXIF = function(obj) {
  1033. console.log('B');
  1034. if (obj instanceof EXIF) return obj;
  1035. if (!(this instanceof EXIF)) return new EXIF(obj);
  1036. this.EXIFwrapped = obj;
  1037. };
  1038.  
  1039. if (typeof exports !== 'undefined') {
  1040. if (typeof module !== 'undefined' && module.exports) {
  1041. exports = module.exports = EXIF;
  1042. }
  1043. exports.EXIF = EXIF;
  1044. } else {
  1045. root.EXIF = EXIF;
  1046. }
  1047.  
  1048. var ExifTags = EXIF.Tags = {
  1049.  
  1050. // version tags
  1051. 0x9000 : "ExifVersion", // EXIF version
  1052. 0xA000 : "FlashpixVersion", // Flashpix format version
  1053.  
  1054. // colorspace tags
  1055. 0xA001 : "ColorSpace", // Color space information tag
  1056.  
  1057. // image configuration
  1058. 0xA002 : "PixelXDimension", // Valid width of meaningful image
  1059. 0xA003 : "PixelYDimension", // Valid height of meaningful image
  1060. 0x9101 : "ComponentsConfiguration", // Information about channels
  1061. 0x9102 : "CompressedBitsPerPixel", // Compressed bits per pixel
  1062.  
  1063. // user information
  1064. 0x927C : "MakerNote", // Any desired information written by the manufacturer
  1065. 0x9286 : "UserComment", // Comments by user
  1066.  
  1067. // related file
  1068. 0xA004 : "RelatedSoundFile", // Name of related sound file
  1069.  
  1070. // date and time
  1071. 0x9003 : "DateTimeOriginal", // Date and time when the original image was generated
  1072. 0x9004 : "DateTimeDigitized", // Date and time when the image was stored digitally
  1073. 0x9290 : "SubsecTime", // Fractions of seconds for DateTime
  1074. 0x9291 : "SubsecTimeOriginal", // Fractions of seconds for DateTimeOriginal
  1075. 0x9292 : "SubsecTimeDigitized", // Fractions of seconds for DateTimeDigitized
  1076.  
  1077. // picture-taking conditions
  1078. 0x829A : "ExposureTime", // Exposure time (in seconds)
  1079. 0x829D : "FNumber", // F number
  1080. 0x8822 : "ExposureProgram", // Exposure program
  1081. 0x8824 : "SpectralSensitivity", // Spectral sensitivity
  1082. 0x8827 : "ISOSpeedRatings", // ISO speed rating
  1083. 0x8828 : "OECF", // Optoelectric conversion factor
  1084. 0x9201 : "ShutterSpeedValue", // Shutter speed
  1085. 0x9202 : "ApertureValue", // Lens aperture
  1086. 0x9203 : "BrightnessValue", // Value of brightness
  1087. 0x9204 : "ExposureBias", // Exposure bias
  1088. 0x9205 : "MaxApertureValue", // Smallest F number of lens
  1089. 0x9206 : "SubjectDistance", // Distance to subject in meters
  1090. 0x9207 : "MeteringMode", // Metering mode
  1091. 0x9208 : "LightSource", // Kind of light source
  1092. 0x9209 : "Flash", // Flash status
  1093. 0x9214 : "SubjectArea", // Location and area of main subject
  1094. 0x920A : "FocalLength", // Focal length of the lens in mm
  1095. 0xA20B : "FlashEnergy", // Strobe energy in BCPS
  1096. 0xA20C : "SpatialFrequencyResponse", //
  1097. 0xA20E : "FocalPlaneXResolution", // Number of pixels in width direction per FocalPlaneResolutionUnit
  1098. 0xA20F : "FocalPlaneYResolution", // Number of pixels in height direction per FocalPlaneResolutionUnit
  1099. 0xA210 : "FocalPlaneResolutionUnit", // Unit for measuring FocalPlaneXResolution and FocalPlaneYResolution
  1100. 0xA214 : "SubjectLocation", // Location of subject in image
  1101. 0xA215 : "ExposureIndex", // Exposure index selected on camera
  1102. 0xA217 : "SensingMethod", // Image sensor type
  1103. 0xA300 : "FileSource", // Image source (3 == DSC)
  1104. 0xA301 : "SceneType", // Scene type (1 == directly photographed)
  1105. 0xA302 : "CFAPattern", // Color filter array geometric pattern
  1106. 0xA401 : "CustomRendered", // Special processing
  1107. 0xA402 : "ExposureMode", // Exposure mode
  1108. 0xA403 : "WhiteBalance", // 1 = auto white balance, 2 = manual
  1109. 0xA404 : "DigitalZoomRation", // Digital zoom ratio
  1110. 0xA405 : "FocalLengthIn35mmFilm", // Equivalent foacl length assuming 35mm film camera (in mm)
  1111. 0xA406 : "SceneCaptureType", // Type of scene
  1112. 0xA407 : "GainControl", // Degree of overall image gain adjustment
  1113. 0xA408 : "Contrast", // Direction of contrast processing applied by camera
  1114. 0xA409 : "Saturation", // Direction of saturation processing applied by camera
  1115. 0xA40A : "Sharpness", // Direction of sharpness processing applied by camera
  1116. 0xA40B : "DeviceSettingDescription", //
  1117. 0xA40C : "SubjectDistanceRange", // Distance to subject
  1118.  
  1119. // other tags
  1120. 0xA005 : "InteroperabilityIFDPointer",
  1121. 0xA420 : "ImageUniqueID" // Identifier assigned uniquely to each image
  1122. };
  1123.  
  1124. var TiffTags = EXIF.TiffTags = {
  1125. 0x0100 : "ImageWidth",
  1126. 0x0101 : "ImageHeight",
  1127. 0x8769 : "ExifIFDPointer",
  1128. 0x8825 : "GPSInfoIFDPointer",
  1129. 0xA005 : "InteroperabilityIFDPointer",
  1130. 0x0102 : "BitsPerSample",
  1131. 0x0103 : "Compression",
  1132. 0x0106 : "PhotometricInterpretation",
  1133. 0x0112 : "Orientation",
  1134. 0x0115 : "SamplesPerPixel",
  1135. 0x011C : "PlanarConfiguration",
  1136. 0x0212 : "YCbCrSubSampling",
  1137. 0x0213 : "YCbCrPositioning",
  1138. 0x011A : "XResolution",
  1139. 0x011B : "YResolution",
  1140. 0x0128 : "ResolutionUnit",
  1141. 0x0111 : "StripOffsets",
  1142. 0x0116 : "RowsPerStrip",
  1143. 0x0117 : "StripByteCounts",
  1144. 0x0201 : "JPEGInterchangeFormat",
  1145. 0x0202 : "JPEGInterchangeFormatLength",
  1146. 0x012D : "TransferFunction",
  1147. 0x013E : "WhitePoint",
  1148. 0x013F : "PrimaryChromaticities",
  1149. 0x0211 : "YCbCrCoefficients",
  1150. 0x0214 : "ReferenceBlackWhite",
  1151. 0x0132 : "DateTime",
  1152. 0x010E : "ImageDescription",
  1153. 0x010F : "Make",
  1154. 0x0110 : "Model",
  1155. 0x0131 : "Software",
  1156. 0x013B : "Artist",
  1157. 0x8298 : "Copyright"
  1158. };
  1159.  
  1160. var GPSTags = EXIF.GPSTags = {
  1161. 0x0000 : "GPSVersionID",
  1162. 0x0001 : "GPSLatitudeRef",
  1163. 0x0002 : "GPSLatitude",
  1164. 0x0003 : "GPSLongitudeRef",
  1165. 0x0004 : "GPSLongitude",
  1166. 0x0005 : "GPSAltitudeRef",
  1167. 0x0006 : "GPSAltitude",
  1168. 0x0007 : "GPSTimeStamp",
  1169. 0x0008 : "GPSSatellites",
  1170. 0x0009 : "GPSStatus",
  1171. 0x000A : "GPSMeasureMode",
  1172. 0x000B : "GPSDOP",
  1173. 0x000C : "GPSSpeedRef",
  1174. 0x000D : "GPSSpeed",
  1175. 0x000E : "GPSTrackRef",
  1176. 0x000F : "GPSTrack",
  1177. 0x0010 : "GPSImgDirectionRef",
  1178. 0x0011 : "GPSImgDirection",
  1179. 0x0012 : "GPSMapDatum",
  1180. 0x0013 : "GPSDestLatitudeRef",
  1181. 0x0014 : "GPSDestLatitude",
  1182. 0x0015 : "GPSDestLongitudeRef",
  1183. 0x0016 : "GPSDestLongitude",
  1184. 0x0017 : "GPSDestBearingRef",
  1185. 0x0018 : "GPSDestBearing",
  1186. 0x0019 : "GPSDestDistanceRef",
  1187. 0x001A : "GPSDestDistance",
  1188. 0x001B : "GPSProcessingMethod",
  1189. 0x001C : "GPSAreaInformation",
  1190. 0x001D : "GPSDateStamp",
  1191. 0x001E : "GPSDifferential"
  1192. };
  1193.  
  1194. var StringValues = EXIF.StringValues = {
  1195. ExposureProgram : {
  1196. 0 : "Not defined",
  1197. 1 : "Manual",
  1198. 2 : "Normal program",
  1199. 3 : "Aperture priority",
  1200. 4 : "Shutter priority",
  1201. 5 : "Creative program",
  1202. 6 : "Action program",
  1203. 7 : "Portrait mode",
  1204. 8 : "Landscape mode"
  1205. },
  1206. MeteringMode : {
  1207. 0 : "Unknown",
  1208. 1 : "Average",
  1209. 2 : "CenterWeightedAverage",
  1210. 3 : "Spot",
  1211. 4 : "MultiSpot",
  1212. 5 : "Pattern",
  1213. 6 : "Partial",
  1214. 255 : "Other"
  1215. },
  1216. LightSource : {
  1217. 0 : "Unknown",
  1218. 1 : "Daylight",
  1219. 2 : "Fluorescent",
  1220. 3 : "Tungsten (incandescent light)",
  1221. 4 : "Flash",
  1222. 9 : "Fine weather",
  1223. 10 : "Cloudy weather",
  1224. 11 : "Shade",
  1225. 12 : "Daylight fluorescent (D 5700 - 7100K)",
  1226. 13 : "Day white fluorescent (N 4600 - 5400K)",
  1227. 14 : "Cool white fluorescent (W 3900 - 4500K)",
  1228. 15 : "White fluorescent (WW 3200 - 3700K)",
  1229. 17 : "Standard light A",
  1230. 18 : "Standard light B",
  1231. 19 : "Standard light C",
  1232. 20 : "D55",
  1233. 21 : "D65",
  1234. 22 : "D75",
  1235. 23 : "D50",
  1236. 24 : "ISO studio tungsten",
  1237. 255 : "Other"
  1238. },
  1239. Flash : {
  1240. 0x0000 : "Flash did not fire",
  1241. 0x0001 : "Flash fired",
  1242. 0x0005 : "Strobe return light not detected",
  1243. 0x0007 : "Strobe return light detected",
  1244. 0x0009 : "Flash fired, compulsory flash mode",
  1245. 0x000D : "Flash fired, compulsory flash mode, return light not detected",
  1246. 0x000F : "Flash fired, compulsory flash mode, return light detected",
  1247. 0x0010 : "Flash did not fire, compulsory flash mode",
  1248. 0x0018 : "Flash did not fire, auto mode",
  1249. 0x0019 : "Flash fired, auto mode",
  1250. 0x001D : "Flash fired, auto mode, return light not detected",
  1251. 0x001F : "Flash fired, auto mode, return light detected",
  1252. 0x0020 : "No flash function",
  1253. 0x0041 : "Flash fired, red-eye reduction mode",
  1254. 0x0045 : "Flash fired, red-eye reduction mode, return light not detected",
  1255. 0x0047 : "Flash fired, red-eye reduction mode, return light detected",
  1256. 0x0049 : "Flash fired, compulsory flash mode, red-eye reduction mode",
  1257. 0x004D : "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",
  1258. 0x004F : "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",
  1259. 0x0059 : "Flash fired, auto mode, red-eye reduction mode",
  1260. 0x005D : "Flash fired, auto mode, return light not detected, red-eye reduction mode",
  1261. 0x005F : "Flash fired, auto mode, return light detected, red-eye reduction mode"
  1262. },
  1263. SensingMethod : {
  1264. 1 : "Not defined",
  1265. 2 : "One-chip color area sensor",
  1266. 3 : "Two-chip color area sensor",
  1267. 4 : "Three-chip color area sensor",
  1268. 5 : "Color sequential area sensor",
  1269. 7 : "Trilinear sensor",
  1270. 8 : "Color sequential linear sensor"
  1271. },
  1272. SceneCaptureType : {
  1273. 0 : "Standard",
  1274. 1 : "Landscape",
  1275. 2 : "Portrait",
  1276. 3 : "Night scene"
  1277. },
  1278. SceneType : {
  1279. 1 : "Directly photographed"
  1280. },
  1281. CustomRendered : {
  1282. 0 : "Normal process",
  1283. 1 : "Custom process"
  1284. },
  1285. WhiteBalance : {
  1286. 0 : "Auto white balance",
  1287. 1 : "Manual white balance"
  1288. },
  1289. GainControl : {
  1290. 0 : "None",
  1291. 1 : "Low gain up",
  1292. 2 : "High gain up",
  1293. 3 : "Low gain down",
  1294. 4 : "High gain down"
  1295. },
  1296. Contrast : {
  1297. 0 : "Normal",
  1298. 1 : "Soft",
  1299. 2 : "Hard"
  1300. },
  1301. Saturation : {
  1302. 0 : "Normal",
  1303. 1 : "Low saturation",
  1304. 2 : "High saturation"
  1305. },
  1306. Sharpness : {
  1307. 0 : "Normal",
  1308. 1 : "Soft",
  1309. 2 : "Hard"
  1310. },
  1311. SubjectDistanceRange : {
  1312. 0 : "Unknown",
  1313. 1 : "Macro",
  1314. 2 : "Close view",
  1315. 3 : "Distant view"
  1316. },
  1317. FileSource : {
  1318. 3 : "DSC"
  1319. },
  1320.  
  1321. Components : {
  1322. 0 : "",
  1323. 1 : "Y",
  1324. 2 : "Cb",
  1325. 3 : "Cr",
  1326. 4 : "R",
  1327. 5 : "G",
  1328. 6 : "B"
  1329. }
  1330. };
  1331.  
  1332. function addEvent(element, event, handler) {
  1333. if (element.addEventListener) {
  1334. element.addEventListener(event, handler, false);
  1335. } else if (element.attachEvent) {
  1336. element.attachEvent("on" + event, handler);
  1337. }
  1338. }
  1339.  
  1340. function imageHasData(img) {
  1341. return !!(img.exifdata);
  1342. }
  1343.  
  1344.  
  1345. function base64ToArrayBuffer(base64, contentType) {
  1346. contentType = contentType || base64.match(/^data\:([^\;]+)\;base64,/mi)[1] || ''; // e.g. 'data:image/jpeg;base64,...' => 'image/jpeg'
  1347. base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
  1348. var binary = atob(base64);
  1349. var len = binary.length;
  1350. var buffer = new ArrayBuffer(len);
  1351. var view = new Uint8Array(buffer);
  1352. for (var i = 0; i < len; i++) {
  1353. view[i] = binary.charCodeAt(i);
  1354. }
  1355. return buffer;
  1356. }
  1357.  
  1358. function objectURLToBlob(url, callback) {
  1359. // var http = new XMLHttpRequest();
  1360. // http.open("GET", url, true);
  1361. // http.responseType = "blob";
  1362. // http.onload = function(e) {
  1363. // if (this.status == 200 || this.status === 0) {
  1364. // callback(this.response);
  1365. // }
  1366. // };
  1367. // http.send();
  1368.  
  1369. // GM_xmlhttpRequest({
  1370. // method: "GET",
  1371. // url: url,
  1372. // onload: function(e) {
  1373. // if (this.status == 200 || this.status === 0) {
  1374. // callback(this.response);
  1375. // }
  1376. // }
  1377. // });
  1378. }
  1379.  
  1380. function getImageData(img, callback) {
  1381. function handleBinaryFile(binFile) {
  1382. var data = findEXIFinJPEG(binFile);
  1383. var iptcdata = findIPTCinJPEG(binFile);
  1384. img.exifdata = data || {};
  1385. img.iptcdata = iptcdata || {};
  1386. if (callback) {
  1387. callback.call(img);
  1388. }
  1389. }
  1390.  
  1391. if (img.src) {
  1392. if (/^data\:/i.test(img.src)) { // Data URI
  1393. var arrayBuffer = base64ToArrayBuffer(img.src);
  1394. handleBinaryFile(arrayBuffer);
  1395.  
  1396. } else if (/^blob\:/i.test(img.src)) { // Object URL
  1397. var fileReader = new FileReader();
  1398. fileReader.onload = function(e) {
  1399. handleBinaryFile(e.target.result);
  1400. };
  1401. objectURLToBlob(img.src, function (blob) {
  1402. fileReader.readAsArrayBuffer(blob);
  1403. });
  1404. } else {
  1405. // var http = new XMLHttpRequest();
  1406. // http.onload = function() {
  1407. // if (this.status == 200 || this.status === 0) {
  1408. // handleBinaryFile(http.response);
  1409. // } else {
  1410. // throw "Could not load image";
  1411. // }
  1412. // http = null;
  1413. // };
  1414. // http.open("GET", img.src, true);
  1415. // http.responseType = "arraybuffer";
  1416. // http.send(null);
  1417.  
  1418. GM_xmlhttpRequest({
  1419. method: "GET",
  1420. url: img.src,
  1421. responseType: 'arraybuffer',
  1422. onload: function(response) {
  1423. if (response.status == 200 || response.status === 0) {
  1424. handleBinaryFile(response.response);
  1425. }
  1426. }
  1427. });
  1428. }
  1429. } else if (window.FileReader && (img instanceof window.Blob || img instanceof window.File)) {
  1430. var fileReader = new FileReader();
  1431. fileReader.onload = function(e) {
  1432. if (debug) console.log("Got file of length " + e.target.result.byteLength);
  1433. handleBinaryFile(e.target.result);
  1434. };
  1435.  
  1436. fileReader.readAsArrayBuffer(img);
  1437. }
  1438. }
  1439.  
  1440. function findEXIFinJPEG(file) {
  1441. var dataView = new DataView(file);
  1442.  
  1443. if (debug) console.log("Got file of length " + file.byteLength);
  1444. if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
  1445. if (debug) console.log("Not a valid JPEG");
  1446. return false; // not a valid jpeg
  1447. }
  1448.  
  1449. var offset = 2,
  1450. length = file.byteLength,
  1451. marker;
  1452.  
  1453. while (offset < length) {
  1454. if (dataView.getUint8(offset) != 0xFF) {
  1455. if (debug) console.log("Not a valid marker at offset " + offset + ", found: " + dataView.getUint8(offset));
  1456. return false; // not a valid marker, something is wrong
  1457. }
  1458.  
  1459. marker = dataView.getUint8(offset + 1);
  1460. if (debug) console.log(marker);
  1461.  
  1462. // we could implement handling for other markers here,
  1463. // but we're only looking for 0xFFE1 for EXIF data
  1464.  
  1465. if (marker == 225) {
  1466. if (debug) console.log("Found 0xFFE1 marker");
  1467.  
  1468. return readEXIFData(dataView, offset + 4, dataView.getUint16(offset + 2) - 2);
  1469.  
  1470. // offset += 2 + file.getShortAt(offset+2, true);
  1471.  
  1472. } else {
  1473. offset += 2 + dataView.getUint16(offset+2);
  1474. }
  1475.  
  1476. }
  1477.  
  1478. }
  1479.  
  1480. function findIPTCinJPEG(file) {
  1481. var dataView = new DataView(file);
  1482.  
  1483. if (debug) console.log("Got file of length " + file.byteLength);
  1484. if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
  1485. if (debug) console.log("Not a valid JPEG");
  1486. return false; // not a valid jpeg
  1487. }
  1488.  
  1489. var offset = 2,
  1490. length = file.byteLength;
  1491.  
  1492.  
  1493. var isFieldSegmentStart = function(dataView, offset){
  1494. return (
  1495. dataView.getUint8(offset) === 0x38 &&
  1496. dataView.getUint8(offset+1) === 0x42 &&
  1497. dataView.getUint8(offset+2) === 0x49 &&
  1498. dataView.getUint8(offset+3) === 0x4D &&
  1499. dataView.getUint8(offset+4) === 0x04 &&
  1500. dataView.getUint8(offset+5) === 0x04
  1501. );
  1502. };
  1503.  
  1504. while (offset < length) {
  1505.  
  1506. if ( isFieldSegmentStart(dataView, offset )){
  1507.  
  1508. // Get the length of the name header (which is padded to an even number of bytes)
  1509. var nameHeaderLength = dataView.getUint8(offset+7);
  1510. if(nameHeaderLength % 2 !== 0) nameHeaderLength += 1;
  1511. // Check for pre photoshop 6 format
  1512. if(nameHeaderLength === 0) {
  1513. // Always 4
  1514. nameHeaderLength = 4;
  1515. }
  1516.  
  1517. var startOffset = offset + 8 + nameHeaderLength;
  1518. var sectionLength = dataView.getUint16(offset + 6 + nameHeaderLength);
  1519.  
  1520. return readIPTCData(file, startOffset, sectionLength);
  1521.  
  1522. break;
  1523.  
  1524. }
  1525.  
  1526.  
  1527. // Not the marker, continue searching
  1528. offset++;
  1529.  
  1530. }
  1531.  
  1532. }
  1533. var IptcFieldMap = {
  1534. 0x78 : 'caption',
  1535. 0x6E : 'credit',
  1536. 0x19 : 'keywords',
  1537. 0x37 : 'dateCreated',
  1538. 0x50 : 'byline',
  1539. 0x55 : 'bylineTitle',
  1540. 0x7A : 'captionWriter',
  1541. 0x69 : 'headline',
  1542. 0x74 : 'copyright',
  1543. 0x0F : 'category'
  1544. };
  1545. function readIPTCData(file, startOffset, sectionLength){
  1546. var dataView = new DataView(file);
  1547. var data = {};
  1548. var fieldValue, fieldName, dataSize, segmentType, segmentSize;
  1549. var segmentStartPos = startOffset;
  1550. while(segmentStartPos < startOffset+sectionLength) {
  1551. if(dataView.getUint8(segmentStartPos) === 0x1C && dataView.getUint8(segmentStartPos+1) === 0x02){
  1552. segmentType = dataView.getUint8(segmentStartPos+2);
  1553. if(segmentType in IptcFieldMap) {
  1554. dataSize = dataView.getInt16(segmentStartPos+3);
  1555. segmentSize = dataSize + 5;
  1556. fieldName = IptcFieldMap[segmentType];
  1557. fieldValue = getStringFromDB(dataView, segmentStartPos+5, dataSize);
  1558. // Check if we already stored a value with this name
  1559. if(data.hasOwnProperty(fieldName)) {
  1560. // Value already stored with this name, create multivalue field
  1561. if(data[fieldName] instanceof Array) {
  1562. data[fieldName].push(fieldValue);
  1563. }
  1564. else {
  1565. data[fieldName] = [data[fieldName], fieldValue];
  1566. }
  1567. }
  1568. else {
  1569. data[fieldName] = fieldValue;
  1570. }
  1571. }
  1572.  
  1573. }
  1574. segmentStartPos++;
  1575. }
  1576. return data;
  1577. }
  1578.  
  1579.  
  1580.  
  1581. function readTags(file, tiffStart, dirStart, strings, bigEnd) {
  1582. var entries = file.getUint16(dirStart, !bigEnd),
  1583. tags = {},
  1584. entryOffset, tag,
  1585. i;
  1586.  
  1587. for (i=0;i<entries;i++) {
  1588. entryOffset = dirStart + i*12 + 2;
  1589. tag = strings[file.getUint16(entryOffset, !bigEnd)];
  1590. if (!tag && debug) console.log("Unknown tag: " + file.getUint16(entryOffset, !bigEnd));
  1591. tags[tag] = readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd);
  1592. }
  1593. return tags;
  1594. }
  1595.  
  1596.  
  1597. function readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd) {
  1598. var type = file.getUint16(entryOffset+2, !bigEnd),
  1599. numValues = file.getUint32(entryOffset+4, !bigEnd),
  1600. valueOffset = file.getUint32(entryOffset+8, !bigEnd) + tiffStart,
  1601. offset,
  1602. vals, val, n,
  1603. numerator, denominator;
  1604.  
  1605. switch (type) {
  1606. case 1: // byte, 8-bit unsigned int
  1607. case 7: // undefined, 8-bit byte, value depending on field
  1608. if (numValues == 1) {
  1609. return file.getUint8(entryOffset + 8, !bigEnd);
  1610. } else {
  1611. offset = numValues > 4 ? valueOffset : (entryOffset + 8);
  1612. vals = [];
  1613. for (n=0;n<numValues;n++) {
  1614. vals[n] = file.getUint8(offset + n);
  1615. }
  1616. return vals;
  1617. }
  1618.  
  1619. case 2: // ascii, 8-bit byte
  1620. offset = numValues > 4 ? valueOffset : (entryOffset + 8);
  1621. return getStringFromDB(file, offset, numValues-1);
  1622.  
  1623. case 3: // short, 16 bit int
  1624. if (numValues == 1) {
  1625. return file.getUint16(entryOffset + 8, !bigEnd);
  1626. } else {
  1627. offset = numValues > 2 ? valueOffset : (entryOffset + 8);
  1628. vals = [];
  1629. for (n=0;n<numValues;n++) {
  1630. vals[n] = file.getUint16(offset + 2*n, !bigEnd);
  1631. }
  1632. return vals;
  1633. }
  1634.  
  1635. case 4: // long, 32 bit int
  1636. if (numValues == 1) {
  1637. return file.getUint32(entryOffset + 8, !bigEnd);
  1638. } else {
  1639. vals = [];
  1640. for (n=0;n<numValues;n++) {
  1641. vals[n] = file.getUint32(valueOffset + 4*n, !bigEnd);
  1642. }
  1643. return vals;
  1644. }
  1645.  
  1646. case 5: // rational = two long values, first is numerator, second is denominator
  1647. if (numValues == 1) {
  1648. numerator = file.getUint32(valueOffset, !bigEnd);
  1649. denominator = file.getUint32(valueOffset+4, !bigEnd);
  1650. val = new Number(numerator / denominator);
  1651. val.numerator = numerator;
  1652. val.denominator = denominator;
  1653. return val;
  1654. } else {
  1655. vals = [];
  1656. for (n=0;n<numValues;n++) {
  1657. numerator = file.getUint32(valueOffset + 8*n, !bigEnd);
  1658. denominator = file.getUint32(valueOffset+4 + 8*n, !bigEnd);
  1659. vals[n] = new Number(numerator / denominator);
  1660. vals[n].numerator = numerator;
  1661. vals[n].denominator = denominator;
  1662. }
  1663. return vals;
  1664. }
  1665.  
  1666. case 9: // slong, 32 bit signed int
  1667. if (numValues == 1) {
  1668. return file.getInt32(entryOffset + 8, !bigEnd);
  1669. } else {
  1670. vals = [];
  1671. for (n=0;n<numValues;n++) {
  1672. vals[n] = file.getInt32(valueOffset + 4*n, !bigEnd);
  1673. }
  1674. return vals;
  1675. }
  1676.  
  1677. case 10: // signed rational, two slongs, first is numerator, second is denominator
  1678. if (numValues == 1) {
  1679. return file.getInt32(valueOffset, !bigEnd) / file.getInt32(valueOffset+4, !bigEnd);
  1680. } else {
  1681. vals = [];
  1682. for (n=0;n<numValues;n++) {
  1683. vals[n] = file.getInt32(valueOffset + 8*n, !bigEnd) / file.getInt32(valueOffset+4 + 8*n, !bigEnd);
  1684. }
  1685. return vals;
  1686. }
  1687. }
  1688. }
  1689.  
  1690. function getStringFromDB(buffer, start, length) {
  1691. var outstr = "";
  1692. for (n = start; n < start+length; n++) {
  1693. outstr += String.fromCharCode(buffer.getUint8(n));
  1694. }
  1695. return outstr;
  1696. }
  1697.  
  1698. function readEXIFData(file, start) {
  1699. if (getStringFromDB(file, start, 4) != "Exif") {
  1700. if (debug) console.log("Not valid EXIF data! " + getStringFromDB(file, start, 4));
  1701. return false;
  1702. }
  1703.  
  1704. var bigEnd,
  1705. tags, tag,
  1706. exifData, gpsData,
  1707. tiffOffset = start + 6;
  1708.  
  1709. // test for TIFF validity and endianness
  1710. if (file.getUint16(tiffOffset) == 0x4949) {
  1711. bigEnd = false;
  1712. } else if (file.getUint16(tiffOffset) == 0x4D4D) {
  1713. bigEnd = true;
  1714. } else {
  1715. if (debug) console.log("Not valid TIFF data! (no 0x4949 or 0x4D4D)");
  1716. return false;
  1717. }
  1718.  
  1719. if (file.getUint16(tiffOffset+2, !bigEnd) != 0x002A) {
  1720. if (debug) console.log("Not valid TIFF data! (no 0x002A)");
  1721. return false;
  1722. }
  1723.  
  1724. var firstIFDOffset = file.getUint32(tiffOffset+4, !bigEnd);
  1725.  
  1726. if (firstIFDOffset < 0x00000008) {
  1727. if (debug) console.log("Not valid TIFF data! (First offset less than 8)", file.getUint32(tiffOffset+4, !bigEnd));
  1728. return false;
  1729. }
  1730.  
  1731. tags = readTags(file, tiffOffset, tiffOffset + firstIFDOffset, TiffTags, bigEnd);
  1732.  
  1733. if (tags.ExifIFDPointer) {
  1734. exifData = readTags(file, tiffOffset, tiffOffset + tags.ExifIFDPointer, ExifTags, bigEnd);
  1735. for (tag in exifData) {
  1736. switch (tag) {
  1737. case "LightSource" :
  1738. case "Flash" :
  1739. case "MeteringMode" :
  1740. case "ExposureProgram" :
  1741. case "SensingMethod" :
  1742. case "SceneCaptureType" :
  1743. case "SceneType" :
  1744. case "CustomRendered" :
  1745. case "WhiteBalance" :
  1746. case "GainControl" :
  1747. case "Contrast" :
  1748. case "Saturation" :
  1749. case "Sharpness" :
  1750. case "SubjectDistanceRange" :
  1751. case "FileSource" :
  1752. exifData[tag] = StringValues[tag][exifData[tag]];
  1753. break;
  1754.  
  1755. case "ExifVersion" :
  1756. case "FlashpixVersion" :
  1757. exifData[tag] = String.fromCharCode(exifData[tag][0], exifData[tag][1], exifData[tag][2], exifData[tag][3]);
  1758. break;
  1759.  
  1760. case "ComponentsConfiguration" :
  1761. exifData[tag] =
  1762. StringValues.Components[exifData[tag][0]] +
  1763. StringValues.Components[exifData[tag][1]] +
  1764. StringValues.Components[exifData[tag][2]] +
  1765. StringValues.Components[exifData[tag][3]];
  1766. break;
  1767. }
  1768. tags[tag] = exifData[tag];
  1769. }
  1770. }
  1771.  
  1772. if (tags.GPSInfoIFDPointer) {
  1773. gpsData = readTags(file, tiffOffset, tiffOffset + tags.GPSInfoIFDPointer, GPSTags, bigEnd);
  1774. for (tag in gpsData) {
  1775. switch (tag) {
  1776. case "GPSVersionID" :
  1777. gpsData[tag] = gpsData[tag][0] +
  1778. "." + gpsData[tag][1] +
  1779. "." + gpsData[tag][2] +
  1780. "." + gpsData[tag][3];
  1781. break;
  1782. }
  1783. tags[tag] = gpsData[tag];
  1784. }
  1785. }
  1786.  
  1787. return tags;
  1788. }
  1789.  
  1790. EXIF.getData = function(img, callback) {
  1791. if ((img instanceof Image || img instanceof HTMLImageElement) && !img.complete) return false;
  1792.  
  1793. if (!imageHasData(img)) {
  1794. getImageData(img, callback);
  1795. } else {
  1796. if (callback) {
  1797. callback.call(img);
  1798. }
  1799. }
  1800. return true;
  1801. }
  1802.  
  1803. EXIF.getTag = function(img, tag) {
  1804. if (!imageHasData(img)) return;
  1805. return img.exifdata[tag];
  1806. }
  1807.  
  1808. EXIF.getAllTags = function(img) {
  1809. if (!imageHasData(img)) return {};
  1810. var a,
  1811. data = img.exifdata,
  1812. tags = {};
  1813. for (a in data) {
  1814. if (data.hasOwnProperty(a)) {
  1815. tags[a] = data[a];
  1816. }
  1817. }
  1818. return tags;
  1819. }
  1820.  
  1821. EXIF.pretty = function(img) {
  1822. if (!imageHasData(img)) return "";
  1823. var a,
  1824. data = img.exifdata,
  1825. strPretty = "";
  1826. for (a in data) {
  1827. if (data.hasOwnProperty(a)) {
  1828. if (typeof data[a] == "object") {
  1829. if (data[a] instanceof Number) {
  1830. strPretty += a + " : " + data[a] + " [" + data[a].numerator + "/" + data[a].denominator + "]\r\n";
  1831. } else {
  1832. strPretty += a + " : [" + data[a].length + " values]\r\n";
  1833. }
  1834. } else {
  1835. strPretty += a + " : " + data[a] + "\r\n";
  1836. }
  1837. }
  1838. }
  1839. return strPretty;
  1840. }
  1841.  
  1842. EXIF.readFromBinaryFile = function(file) {
  1843. return findEXIFinJPEG(file);
  1844. }
  1845.  
  1846. if (typeof define === 'function' && define.amd) {
  1847. define('exif-js', [], function() {
  1848. return EXIF;
  1849. });
  1850. }
  1851. }.call(this));
  1852. // -- https://github.com/exif-js/exif-js