ImageFAQs

Converts image and webm/mp4 URLs into their embedded form

目前為 2023-11-26 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name ImageFAQs
  3. // @namespace FightingGames@gfaqs
  4. // @include http://www.gamefaqs.gamespot.com
  5. // @include http://www.gamefaqs.gamespot.com*
  6. // @include https://www.gamefaqs.gamespot.com
  7. // @include https://www.gamefaqs.gamespot.com*
  8. // @include http://gamefaqs.gamespot.com
  9. // @include http://gamefaqs.gamespot.com*
  10. // @include https://gamefaqs.gamespot.com
  11. // @include https://gamefaqs.gamespot.com*
  12. // @icon http://fightinggames.bitbucket.io/imagefaqs/icon.png
  13. // @description Converts image and webm/mp4 URLs into their embedded form
  14. // @license MIT
  15. // @supportURL https://gamefaqs.gamespot.com/boards/1063-customfaqs-scripts-and-styles
  16. // @homepageURL https://fightinggames.bitbucket.io/imagefaqs/
  17. // @version 1.22.44
  18. // @grant GM_addStyle
  19. // @grant GM_getResourceText
  20. // @grant GM_log
  21. // @grant GM_xmlhttpRequest
  22. // @grant GM.xmlHttpRequest
  23. // @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
  24. // @require https://code.jquery.com/jquery-2.2.4.min.js
  25. // @require https://code.jquery.com/ui/1.11.4/jquery-ui.min.js
  26. // @require https://cdnjs.cloudflare.com/ajax/libs/async/2.0.0/async.min.js
  27. // @resource jqueryuibaseCSS https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery.ui.base.css
  28. // @resource jqueryuithemeCSS https://code.jquery.com/ui/1.11.4/themes/cupertino/jquery-ui.css
  29. // ==/UserScript==
  30. /*
  31. The MIT License (MIT)
  32. This greasemonkey script for GameFAQs converts image and webm/mp4
  33. links into their embedded form. It can be considered as a spiritual successor
  34. to text-to-image (TTI) for GameFAQs.
  35. Copyright (c) 2018 FightingGames@gamefaqs <adrenalinebionicarm@gmail.com>
  36. Copyright (c) 2018 FeaturingDante@gamefaqs <featuringDante@gmail.com>
  37. Permission is hereby granted, free of charge, to any person obtaining a copy
  38. of this software and associated documentation files (the "Software"), to deal
  39. in the Software without restriction, including without limitation the rights
  40. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  41. copies of the Software, and to permit persons to whom the Software is
  42. furnished to do so, subject to the following conditions:
  43. The above copyright notice and this permission notice shall be included in
  44. all copies or substantial portions of the Software.
  45. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  46. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  47. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  48. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  49. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  50. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  51. THE SOFTWARE.
  52. */
  53. /*
  54. Debug tips:
  55. - Use `return;` incrementally to see if intermediate output is correct.
  56. - Use external IDE when editing script:
  57. - https://stackoverflow.com/questions/49509874/how-can-i-develop-my-userscript-in-my-favourite-ide-and-avoid-copy-pasting-it-to
  58. - Remember to still include @require and @grant in the tampermonkey script, not just the local script.
  59. */
  60. /*
  61. Reminder:
  62. GM_addStyle_from_file and GM_addStyle_from_string are currently being used to
  63. replace GM_addStyle.
  64. Currently checks if imagefaqs has already been loaded after clicking back button
  65. See code immediately after print function.
  66. Relying on hacks:
  67. // @grant GM.xmlHttpRequest
  68. // @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
  69. .embeddedImgAnchor > .embeddedImg (#video) behave differently between firefox and chrome
  70. - In firefox, anchor's href is disabled while video is expanded.
  71. - Left-click does not shrink video, needed [Close Video]
  72. - In chrome:
  73. - Left-click will shrink video except when using video controls.
  74. May have to delay execution of entire script via setTimeout() to catch
  75. particular end-user reported problems.
  76. */
  77. SUPPORT_URL = "https://gamefaqs.gamespot.com/boards/1063-customfaqs-scripts-and-styles";
  78. HOMEPAGE_URL = "http://fightinggames.bitbucket.io/imagefaqs/";
  79. USER_URL = "https://gamefaqs.gamespot.com/user";
  80. const isDebug = true;
  81. var print = function(msg) {};
  82. if (unsafeWindow.console && isDebug) {
  83. print = (...args) => unsafeWindow.console.log("ImageFAQs_Debug", ...args)
  84. }
  85. if ($("body").find('#imagefaqsLoaded').length !== 0) {
  86. print('Imagefaqs already loaded. Returning.')
  87. return;
  88. }
  89. else
  90. {
  91. $("body").append("<div id='imagefaqsLoaded'></div>");
  92. }
  93. const isSkipImgurAlbum = true;
  94. /*
  95. Get number of keys in a primitive java object
  96. */
  97. Object.size = function(obj) {
  98. const size = 0;
  99. let key;
  100. for (key in obj) {
  101. if (obj.hasOwnProperty(key))
  102. size++;
  103. }
  104. return size;
  105. };
  106. /*
  107. Below is a collection of functions to iterate through HTML objects (e.g. step from <b></b> to <img/>)
  108. https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Whitespace_in_the_DOM
  109. */
  110. /*
  111. * Determine whether a node's text content is entirely whitespace.
  112. *
  113. * @param nod A node implementing the |CharacterData| interface (i.e.,
  114. * a |Text|, |Comment|, or |CDATASection| node
  115. * @return True if all of the text content of |nod| is whitespace,
  116. * otherwise false.
  117. */
  118. function is_all_ws( nod )
  119. {
  120. // Use ECMA-262 Edition 3 String and RegExp features
  121. return !(/[^\t\n\r ]/.test(nod.textContent));
  122. }
  123. /*
  124. * Determine if a node should be ignored by the iterator functions.
  125. *
  126. * @param nod An object implementing the DOM1 |Node| interface.
  127. * @return true if the node is:
  128. * 1) A |Text| node that is all whitespace
  129. * 2) A |Comment| node
  130. * and otherwise false.
  131. */
  132. function is_ignorable( nod )
  133. {
  134. return ( nod.nodeType == 8) || // A comment node
  135. ( (nod.nodeType == 3) && is_all_ws(nod) ); // a text node, all ws
  136. }
  137. /*
  138. * Version of |previousSibling| that skips nodes that are entirely
  139. * whitespace or comments. (Normally |previousSibling| is a property
  140. * of all DOM nodes that gives the sibling node, the node that is
  141. * a child of the same parent, that occurs immediately before the
  142. * reference node.)
  143. *
  144. * @param sib The reference node.
  145. * @return Either:
  146. * 1) The closest previous sibling to |sib| that is not
  147. * ignorable according to |is_ignorable|, or
  148. * 2) null if no such node exists.
  149. */
  150. function node_before( sib )
  151. {
  152. while ((sib = sib.previousSibling)) {
  153. if (!is_ignorable(sib)) return sib;
  154. }
  155. return null;
  156. }
  157. /*
  158. * Version of |nextSibling| that skips nodes that are entirely
  159. * whitespace or comments.
  160. *
  161. * @param sib The reference node.
  162. * @return Either:
  163. * 1) The closest next sibling to |sib| that is not
  164. * ignorable according to |is_ignorable|, or
  165. * 2) null if no such node exists.
  166. */
  167. function node_after( sib )
  168. {
  169. while ((sib = sib.nextSibling)) {
  170. if (!is_ignorable(sib)) return sib;
  171. }
  172. return null;
  173. }
  174. /*
  175. * Version of |lastChild| that skips nodes that are entirely
  176. * whitespace or comments. (Normally |lastChild| is a property
  177. * of all DOM nodes that gives the last of the nodes contained
  178. * directly in the reference node.)
  179. *
  180. * @param sib The reference node.
  181. * @return Either:
  182. * 1) The last child of |sib| that is not
  183. * ignorable according to |is_ignorable|, or
  184. * 2) null if no such node exists.
  185. */
  186. function last_child( par )
  187. {
  188. var res=par.lastChild;
  189. while (res) {
  190. if (!is_ignorable(res)) return res;
  191. res = res.previousSibling;
  192. }
  193. return null;
  194. }
  195. /*
  196. * Version of |firstChild| that skips nodes that are entirely
  197. * whitespace and comments.
  198. *
  199. * @param sib The reference node.
  200. * @return Either:
  201. * 1) The first child of |sib| that is not
  202. * ignorable according to |is_ignorable|, or
  203. * 2) null if no such node exists.
  204. */
  205. function first_child( par )
  206. {
  207. var res=par.firstChild;
  208. while (res) {
  209. if (!is_ignorable(res)) return res;
  210. res = res.nextSibling;
  211. }
  212. return null;
  213. }
  214. /*
  215. * Version of |data| that doesn't include whitespace at the beginning
  216. * and end and normalizes all whitespace to a single space. (Normally
  217. * |data| is a property of text nodes that gives the text of the node.)
  218. *
  219. * @param txt The text node whose data should be returned
  220. * @return A string giving the contents of the text node with
  221. * whitespace collapsed.
  222. */
  223. function data_of( txt )
  224. {
  225. var data = txt.textContent;
  226. // Use ECMA-262 Edition 3 String and RegExp features
  227. data = data.replace(/[\t\n\r ]+/g, " ");
  228. if (data.charAt(0) == " ")
  229. data = data.substring(1, data.length);
  230. if (data.charAt(data.length - 1) == " ")
  231. data = data.substring(0, data.length - 1);
  232. return data;
  233. }
  234. /*End of HTML object iterator functions*/
  235. /*Get our own unique jQuery library instance*/
  236. this.$ = this.jQuery = jQuery.noConflict(true);
  237. /*
  238. Display a notification on the bottom-right of the browser.
  239. @param msg :: string to put between <span></span>
  240. @param duration :: number of milliseconds to display message before it disappears. Default 1000
  241. */
  242. function showNotification(msg, duration)
  243. {
  244. var notificationBox = $("#imagefaqs_notificationBox");
  245. notificationBox.remove();
  246. $("body").append(
  247. "<div id='imagefaqs_notificationBox'>" +
  248. "<span style='color: black'>" +
  249. msg +
  250. "</span>" +
  251. "</div>"
  252. );
  253. notificationBox = $("#imagefaqs_notificationBox");
  254. notificationBox.css({
  255. "position": "absolute",
  256. "background": "white",
  257. "top": ($(window).scrollTop() + $(window).height() - notificationBox.height())+"px",
  258. "left": ($(window).scrollLeft() + $(window).width() - notificationBox.find("span").width() - 1)+"px",
  259. });
  260. // Note: Also look at $(window).scroll(function() { ... which controls scrolling of notification box.
  261. if (duration === undefined)
  262. duration = 1000;
  263. notificationBox.effect("highlight").delay(duration).fadeOut(500);
  264. }
  265. /*This top portion of the script handles the settings box and local storage*/
  266. var thumbnailImgWidth = 0;
  267. var thumbnailImgHeight = 150;
  268. var thumbnailImgWidthSig = 0;
  269. var thumbnailImgHeightSig = 75;
  270. var settingsJSON = localStorage.getItem("imagefaqs");
  271. var settings; /*key-value array of JSON*/
  272. var sessionResizeHotkey;
  273. var sessionHideToggleHotkey;
  274. const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1; /*osdep*/
  275. const isTampermonkey = GM_info.scriptHandler === "Tampermonkey";
  276. function getDefaultSettings() {
  277. return {
  278. enable_sigs: true,
  279. enable_floatingImg: true,
  280. enable_floatingImg_url: false,
  281. includeSigWhenExpanding: false,
  282. hideSigsWhenHideMode: false,
  283. legacySigDetection: true,
  284. show_imgURLspan: true,
  285. show_imgResolutionSpan: true,
  286. show_imgFilesizeSpan: false,
  287. show_imgGoogle: true,
  288. show_imgIqdb: true,
  289. show_blacklistToggle: true,
  290. show_imgAllResizeToggles: true,
  291. show_hideToggle: true,
  292. show_hideAllToggle: true,
  293. imgContainerStyle: "sideBySideSig",
  294. auto_scroll_when_thumbnail_clicked: false,
  295. thumbnailWidth: thumbnailImgWidth,
  296. thumbnailHeight: thumbnailImgHeight,
  297. thumbnailWidthSig: thumbnailImgWidthSig,
  298. thumbnailHeightSig: thumbnailImgHeightSig,
  299. expandedWidth: 0,
  300. expandedHeight: 0,
  301. imgContainerBackgroundColor: "#DFE6F7",
  302. isHideMode: false,
  303. hideToggleHotkey: {115: 115}, /*F4*/
  304. resizeHotkey: {113: 113}, /*F2*/
  305. blacklistStr: "",
  306. loopThumbnailVideo: true,
  307. loopExpandedVideo: false,
  308. };
  309. }
  310. function setSettingsToDefault() {
  311. settings = getDefaultSettings();
  312. }
  313. /*if imageFAQs was freshly installed*/
  314. if (settingsJSON === null)
  315. {
  316. setSettingsToDefault();
  317. localStorage.setItem("imagefaqs", JSON.stringify(settings)); /*save default settings*/
  318. /*gfaqsdep for URL*/
  319. showNotification(`ImageFAQs ${GM_info.script.version} has successfully been installed.`+
  320. `<br/><br/>Settings can be accessed under 'Message Board Information' `+
  321. `at<br/><a target='_blank' href='${USER_URL}'>${USER_URL}</a>`, 10000);
  322. }
  323. else
  324. {
  325. settings = $.parseJSON(settingsJSON);
  326. //For each default setting, apply it to current settings if current setting isn't set
  327. var defaultSettings = getDefaultSettings();
  328. var defaultKeys = Object.keys(defaultSettings);
  329. defaultKeys.forEach(function (defaultKey) {
  330. if (settings[defaultKey] === undefined) {
  331. settings[defaultKey] = defaultSettings[defaultKey];
  332. localStorage.setItem("imagefaqs", JSON.stringify(settings));
  333. }
  334. });
  335. }
  336. print("ImageFAQs settings from local storage: " + JSON.stringify(settings));
  337. /*
  338. Convert an ASCII numeric representation of a keyboard character to its full string name
  339. e.g. keyCodeToString(16) === "shift"
  340. */
  341. function keyCodeToString(keyCode)
  342. {
  343. keyCode = parseInt(keyCode);
  344. if (keyCode === 16)
  345. {
  346. return "shift";
  347. }
  348. else if (keyCode === 17)
  349. {
  350. return "ctrl";
  351. }
  352. else if (keyCode === 18)
  353. {
  354. return "alt";
  355. }
  356. else if (keyCode >= 112 && keyCode <= 123) /*F keys*/
  357. {
  358. return "F" + (keyCode - 111);
  359. }
  360. else
  361. {
  362. return String.fromCharCode(keyCode);
  363. }
  364. }
  365. /*
  366. Convert an array of KV ASCII numeric representation of keyboard characters to its
  367. full string representation
  368. e,g, keyCodeKVArrayToString([{68:68},{77:77}]) === "DM"
  369. */
  370. function keyCodeKVArrayToString(array)
  371. {
  372. var string = "";
  373. for (var key in array)
  374. {
  375. string += keyCodeToString(key) + " ";
  376. }
  377. return string;
  378. }
  379. /*
  380. Get a copy of an array of KV's using 1-level deep cloning.
  381. */
  382. function cloneKVArray(KVArray)
  383. {
  384. var newKVArray = {};
  385. for (var key in KVArray)
  386. {
  387. newKVArray[key] = KVArray[key];
  388. }
  389. return newKVArray;
  390. }
  391. sessionHideToggleHotkey = cloneKVArray(settings.hideToggleHotkey);
  392. sessionResizeHotkey = cloneKVArray(settings.resizeHotkey);
  393. function applySettingsToPopup(settings, settingsPopup)
  394. {
  395. settingsPopup.find("#enable_sigs_checkbox").prop("checked", settings.enable_sigs);
  396. settingsPopup.find("#enable_floatingImg").prop("checked", settings.enable_floatingImg);
  397. settingsPopup.find("#enable_floatingImg_url").prop("checked", settings.enable_floatingImg_url);
  398. settingsPopup.find("#includeSigWhenExpanding_checkbox").prop("checked", settings.includeSigWhenExpanding);
  399. settingsPopup.find("#hideSigsWhenHideMode_checkbox").prop("checked", settings.hideSigsWhenHideMode);
  400. settingsPopup.find("#legacySigDetection_checkbox").prop("checked", settings.legacySigDetection);
  401. settingsPopup.find("#loopThumbnailVideo_checkbox").prop("checked", settings.loopThumbnailVideo);
  402. settingsPopup.find("#loopExpandedVideo_checkbox").prop("checked", settings.loopExpandedVideo);
  403. settingsPopup.find("#show_ImgURLspan_checkbox").prop("checked", settings.show_imgURLspan);
  404. settingsPopup.find("#show_ImgResolutionSpan_checkbox").prop("checked", settings.show_imgResolutionSpan);
  405. settingsPopup.find("#show_imgFilesizeSpan_checkbox").prop("checked", settings.show_imgFilesizeSpan);
  406. settingsPopup.find("#show_imgGoogle_checkbox").prop("checked", settings.show_imgGoogle);
  407. settingsPopup.find("#show_blacklistToggle_checkbox").prop("checked", settings.show_blacklistToggle);
  408. settingsPopup.find("#show_imgIqdb_checkbox").prop("checked", settings.show_imgIqdb);
  409. settingsPopup.find("#show_imgAllResizeToggles_checkbox").prop("checked", settings.show_imgAllResizeToggles);
  410. settingsPopup.find("#show_hideToggle_checkbox").prop("checked", settings.show_hideToggle);
  411. settingsPopup.find("#show_hideAllToggle_checkbox").prop("checked", settings.show_hideAllToggle);
  412. settingsPopup.find("input[value="+settings.imgContainerStyle+"]").prop("checked", true);
  413. settingsPopup.find("#auto_scroll_when_thumbnail_clicked_checkbox").prop("checked", settings.auto_scroll_when_thumbnail_clicked);
  414. settingsPopup.find("#thumbnailImgWidth_text").val(settings.thumbnailWidth);
  415. settingsPopup.find("#thumbnailImgHeight_text").val(settings.thumbnailHeight);
  416. settingsPopup.find("#thumbnailImgWidthSig_text").val(settings.thumbnailWidthSig);
  417. settingsPopup.find("#thumbnailImgHeightSig_text").val(settings.thumbnailHeightSig);
  418. settingsPopup.find("#expandedWidth_text").val(settings.expandedWidth);
  419. settingsPopup.find("#expandedHeight_text").val(settings.expandedHeight);
  420. settingsPopup.find("#imgContainerBackgroundColor_color").val(settings.imgContainerBackgroundColor);
  421. settingsPopup.find("#resizeHotkey_text").val( keyCodeKVArrayToString(settings.resizeHotkey) );
  422. settingsPopup.find("#hideToggleHotkey_text").val( keyCodeKVArrayToString(settings.hideToggleHotkey) );
  423. settingsPopup.find("#blacklist_text").val( settings.blacklistStr );
  424. settingsPopup.children("#responseSpan").html("&nbsp;");
  425. }
  426. /*Event where user opens up settings menu*/
  427. $("body").on("click", "#imagefaqs_settings_but", function(event) {
  428. var settingsPopup = $("#imagefaqs_settings_popup");
  429. event.preventDefault();
  430. if (settingsPopup.length === 0)
  431. {
  432. $("body").append(
  433. "<div id='imagefaqs_settings_popup' title='ImageFAQs Settings. Version "+GM_info.script.version+"'>" +
  434. "Update history: <a target='_blank' href='"+HOMEPAGE_URL+"' style='outline: 0'>"+HOMEPAGE_URL+"</a>" +
  435. "<br/>" +
  436. "<span id='feedback_bugreport_info'>" +
  437. "Feedback and bug reporting: <a target='_blank' href='"+SUPPORT_URL+"'>"+SUPPORT_URL+"</a>" +
  438. "<br/>" +
  439. "</span>" +
  440. "<fieldset>" +
  441. "<legend>Main</legend>" +
  442. "<label><input id='enable_floatingImg' type='checkbox'>Enable floating expanded image upon cursor hover over thumbnail</label>" +
  443. "<br/>" +
  444. "<label><input id='enable_floatingImg_url' type='checkbox'>Enable floating expanded image upon cursor hover over URL</label>" +
  445. "<br/>" +
  446. "<label><input id='auto_scroll_when_thumbnail_clicked_checkbox' type='checkbox'>Auto-scroll to top of image after toggling visibility or size</label>" +
  447. "</fieldset>" +
  448. "<fieldset>" +
  449. "<legend>Signature-specific</legend>" +
  450. "<label><input id='enable_sigs_checkbox' type='checkbox'>Embed signature images</label>" +
  451. "<br/>" +
  452. "<label><input id='legacySigDetection_checkbox' type='checkbox'>Add legacy signature image detection on older posts</label>" +
  453. "<br/>" +
  454. "<label><input id='includeSigWhenExpanding_checkbox' type='checkbox'>Affect signature images when expanding and contracting all images</label>" +
  455. "<br/>" +
  456. "<label><input id='hideSigsWhenHideMode_checkbox' type='checkbox'>Affect signature images when toggling hide mode</label>" +
  457. "</fieldset>" +
  458. "<fieldset>" +
  459. "<legend>Video-specific</legend>" +
  460. "<label><input id='loopThumbnailVideo_checkbox' type='checkbox'>Auto-play and loop thumbnail videos (muted)</label>" +
  461. "<br/>" +
  462. "<label><input id='loopExpandedVideo_checkbox' type='checkbox'>Loop expanded videos</label>" +
  463. "<br/>" +
  464. "</fieldset>" +
  465. "<fieldset>" +
  466. "<legend>Image Container Toggles and Information Visibility</legend>" +
  467. "<label><input id='show_ImgURLspan_checkbox' type='checkbox'>Show image URL</label>" +
  468. "<br/>" +
  469. "<label><input id='show_ImgResolutionSpan_checkbox' type='checkbox'>Show image resolution</label>" +
  470. "<br/>" +
  471. "<label><input id='show_imgFilesizeSpan_checkbox' type='checkbox'>Show image filesize (Warning: Doubles load time)</label>" +
  472. "<br/>" +
  473. "<label><input id='show_imgGoogle_checkbox' type='checkbox'>Show google reverse image search button</label>" +
  474. "<br/>" +
  475. "<label><input id='show_imgIqdb_checkbox' type='checkbox'>Show iqdb reverse image search button</label>" +
  476. "<br/>" +
  477. "<label><input id='show_blacklistToggle_checkbox' type='checkbox'>Show blacklist toggle button</label>" +
  478. "<br/>" +
  479. "<label><input id='show_imgAllResizeToggles_checkbox' type='checkbox'>Show all-resize toggle buttons</label>" +
  480. "<br/>" +
  481. "<label><input id='show_hideAllToggle_checkbox' type='checkbox'>Show all-hide/expose toggle buttons</label>" +
  482. "<br/>" +
  483. "<label><input id='show_hideToggle_checkbox' type='checkbox'>Show individual hide/expose toggle button</label>" +
  484. "</fieldset>" +
  485. "<fieldset>" +
  486. "<legend>Image Container Style</legend>" +
  487. "<label><input type='radio' name='imgContainerStyle' value='stacked' checked='checked'>Stacked and Verbose</label>" +
  488. "<br>" +
  489. "<label><input type='radio' name='imgContainerStyle' value='sideBySide'>Side-By-Side and Succinct</label>" +
  490. "<br>" +
  491. "<label><input type='radio' name='imgContainerStyle' value='sideBySideSig'>Side-By-Side and Succinct (Signatures Only)</label>" +
  492. "</fieldset>" +
  493. "<label><input id='thumbnailImgWidth_text' type='text'>Thumbnail Max-Width (0 default)</label>" +
  494. "<br/>" +
  495. "<label><input id='thumbnailImgHeight_text' type='text'>Thumbnail Max-Height (150 default)</label>" +
  496. "<br/>" +
  497. "<label><input id='thumbnailImgWidthSig_text' type='text'>Signature Thumbnail Max-Width (0 default)</label>" +
  498. "<br/>" +
  499. "<label><input id='thumbnailImgHeightSig_text' type='text'>Signature Thumbnail Max-Height (75 default)</label>" +
  500. "<br/>" +
  501. "<label><input id='expandedWidth_text' type='text'>Expanded max-width (0 default)</label>" +
  502. "<br/>" +
  503. "<label><input id='expandedHeight_text' type='text'>Expanded max-height (0 default)</label>" +
  504. "<br/ style='margin-bottom: 5px'>" +
  505. "<span>Tip: Use 0 to specify no length restriction.</span>" +
  506. "<br/><br/>" +
  507. "<input id='imgContainerBackgroundColor_color' type='color' value='#DFE6F7' size=4 ><label>Image container background color (RGB={223,230,247} default)</label>" +
  508. "<br/ style='margin-bottom: 5px'>" +
  509. "<span>Tip: Use RGB={0,0,0} for no background color.</span>" +
  510. "<br/><br/>" +
  511. "<label>Newline separated list of blacklisted image URLs</label>" +
  512. "<br/>" +
  513. "<textarea id='blacklist_text'></textarea>" +
  514. "<br/ style='margin-bottom: 5px'>" +
  515. "<span>Tip: You can blacklist an entire domain (e.g. pbsrc.com).</span>" +
  516. "<br/><br/>" +
  517. "<label><input id='resizeHotkey_text' class='hotkeyInput' type='text'>Toggle image size hotkey (F2 default)</label>" +
  518. "<br/>" +
  519. "<label><input id='hideToggleHotkey_text' class='hotkeyInput' type='text'>Toggle hide mode hotkey (F4 default)</label>" +
  520. "<br/ style='margin-bottom: 5px'>" +
  521. "<span>Tip: You can disable a hotkey with the backspace.</span>" +
  522. "<br/><br/>" +
  523. "<button id='saveImagefaqsSettingsBut' type='button'>Save</button> " +
  524. "<button id='cancelImagefaqsSettingsBut' type='button'>Cancel</button> " +
  525. "<span id='responseSpan'>&nbsp;&nbsp;</span>" + /*for reporting success or failure*/
  526. "<button id='defaultSettingsBut' type='button' style='float: right'>Reset Settings</button> " +
  527. "</div>"
  528. );
  529. settingsPopup = $("#imagefaqs_settings_popup");
  530. }
  531. /*Show user's custom settings*/
  532. applySettingsToPopup(settings, settingsPopup);
  533. settingsPopup.dialog({
  534. width: 550,
  535. height: 800 /*adds a scrollbar*/
  536. });
  537. settingsPopup.find("#blacklist_text").width(settingsPopup.width());
  538. });
  539. $("body").on("click", "#defaultSettingsBut", function(event) {
  540. event.preventDefault();
  541. var settingsPopup = $("#imagefaqs_settings_popup");
  542. setSettingsToDefault();
  543. applySettingsToPopup(settings, settingsPopup);
  544. localStorage.setItem("imagefaqs", JSON.stringify(settings));
  545. reportResponseMsgInImagefaqsSettingsPopupBox("Default settings saved.", settingsPopup);
  546. });
  547. /*Event where users clicks on the "Save Settings" button*/
  548. $("body").on("click", "#saveImagefaqsSettingsBut", function(event) {
  549. event.preventDefault();
  550. var settingsPopup = $("#imagefaqs_settings_popup");
  551. /*if valid thumbnail dimensions*/
  552. if (
  553. !isNaN($("#thumbnailImgWidth_text").val()) && $("#thumbnailImgWidth_text").val() >= 0 &&
  554. !isNaN($("#thumbnailImgHeight_text").val()) && $("#thumbnailImgHeight_text").val() >= 0 &&
  555. !isNaN($("#thumbnailImgWidthSig_text").val()) && $("#thumbnailImgWidthSig_text").val() >= 0 &&
  556. !isNaN($("#thumbnailImgHeightSig_text").val()) && $("#thumbnailImgHeightSig_text").val() >= 0)
  557. {
  558. settings.thumbnailWidth = $("#thumbnailImgWidth_text").val();
  559. settings.thumbnailHeight = $("#thumbnailImgHeight_text").val();
  560. settings.thumbnailWidthSig = $("#thumbnailImgWidthSig_text").val();
  561. settings.thumbnailHeightSig = $("#thumbnailImgHeightSig_text").val();
  562. }
  563. else
  564. {
  565. reportResponseMsgInImagefaqsSettingsPopupBox("Error: Invalid thumbnail dimensions. Use non-negative integers only.", settingsPopup);
  566. return;
  567. }
  568. /*if valid expanded dimensions*/
  569. if (
  570. !isNaN($("#expandedWidth_text").val()) && $("#expandedWidth_text").val() >= 0 &&
  571. !isNaN($("#expandedHeight_text").val()) && $("#expandedHeight_text").val() >= 0)
  572. {
  573. settings.expandedWidth = $("#expandedWidth_text").val();
  574. settings.expandedHeight = $("#expandedHeight_text").val();
  575. }
  576. else
  577. {
  578. reportResponseMsgInImagefaqsSettingsPopupBox("Error: Invalid expanded dimensions. Use non-negative integers only.", settingsPopup);
  579. return;
  580. }
  581. /*if valid image container background color*/
  582. if (settingsPopup.find("#imgContainerBackgroundColor_color").val().match(/^(#[a-zA-Z0-9]{6})|0$/i))
  583. {
  584. settings.imgContainerBackgroundColor = settingsPopup.find("#imgContainerBackgroundColor_color").val();
  585. }
  586. else
  587. {
  588. reportResponseMsgInImagefaqsSettingsPopupBox("Error: Invalid image container background color.", settingsPopup);
  589. return;
  590. }
  591. settings.enable_sigs = settingsPopup.find("#enable_sigs_checkbox").is(":checked");
  592. settings.enable_floatingImg = settingsPopup.find("#enable_floatingImg").is(":checked");
  593. settings.enable_floatingImg_url = settingsPopup.find("#enable_floatingImg_url").is(":checked");
  594. settings.loopThumbnailVideo = settingsPopup.find("#loopThumbnailVideo_checkbox").is(":checked");
  595. settings.loopExpandedVideo = settingsPopup.find("#loopExpandedVideo_checkbox").is(":checked");
  596. settings.includeSigWhenExpanding = settingsPopup.find("#includeSigWhenExpanding_checkbox").is(":checked");
  597. settings.hideSigsWhenHideMode = settingsPopup.find("#hideSigsWhenHideMode_checkbox").is(":checked");
  598. settings.legacySigDetection = settingsPopup.find("#legacySigDetection_checkbox").is(":checked");
  599. settings.show_imgURLspan = settingsPopup.find("#show_ImgURLspan_checkbox").is(":checked");
  600. settings.show_imgResolutionSpan = settingsPopup.find("#show_ImgResolutionSpan_checkbox").is(":checked");
  601. settings.show_imgFilesizeSpan = settingsPopup.find("#show_imgFilesizeSpan_checkbox").is(":checked");
  602. settings.show_imgGoogle = settingsPopup.find("#show_imgGoogle_checkbox").is(":checked");
  603. settings.show_imgIqdb = settingsPopup.find("#show_imgIqdb_checkbox").is(":checked");
  604. settings.show_blacklistToggle = settingsPopup.find("#show_blacklistToggle_checkbox").is(":checked");
  605. settings.show_imgAllResizeToggles = settingsPopup.find("#show_imgAllResizeToggles_checkbox").is(":checked");
  606. settings.show_hideToggle = settingsPopup.find("#show_hideToggle_checkbox").is(":checked");
  607. settings.show_hideAllToggle = settingsPopup.find("#show_hideAllToggle_checkbox").is(":checked");
  608. settings.imgContainerStyle = settingsPopup.find("input[name=imgContainerStyle]:checked").val();
  609. settings.auto_scroll_when_thumbnail_clicked = settingsPopup.find("#auto_scroll_when_thumbnail_clicked_checkbox").is(":checked");
  610. settings.resizeHotkey = cloneKVArray(sessionResizeHotkey);
  611. settings.hideToggleHotkey = cloneKVArray(sessionHideToggleHotkey);
  612. settings.blacklistStr = settingsPopup.find("#blacklist_text").val();
  613. localStorage.setItem("imagefaqs", JSON.stringify(settings));
  614. reportResponseMsgInImagefaqsSettingsPopupBox("Settings saved.", settingsPopup);
  615. });
  616. /*
  617. Display a notification in the settings window
  618. @param msg :: message string to show to the user
  619. @param box :: $("#imagefaqs_settings_popup")
  620. */
  621. function reportResponseMsgInImagefaqsSettingsPopupBox(msg, box)
  622. {
  623. var msgBox = box.children("#responseSpan");
  624. msgBox.html(msg);
  625. msgBox.effect("highlight");
  626. }
  627. /*Event when users clicks on the "Cancel" button the settings window.*/
  628. $("body").on("click", "#cancelImagefaqsSettingsBut", function(event) {
  629. event.preventDefault();
  630. $("#imagefaqs_settings_popup").dialog("close");
  631. });
  632. /*Begin main scripting*/
  633. setTimeout(function(){
  634. print("Entered main()");
  635. var isHideMode = settings.isHideMode;
  636. var enable_floatingImg = settings.enable_floatingImg;
  637. var enable_floatingImg_url = settings.enable_floatingImg_url;
  638. var includeSigWhenExpanding = settings.includeSigWhenExpanding;
  639. var hideSigsWhenHideMode = settings.hideSigsWhenHideMode;
  640. var legacySigDetection = settings.legacySigDetection;
  641. var loopThumbnailVideo = settings.loopThumbnailVideo;
  642. var loopExpandedVideo = settings.loopExpandedVideo;
  643. var isShow = {
  644. URLSpan: settings.show_imgURLspan,
  645. resolutionSpan: settings.show_imgResolutionSpan,
  646. filesizeSpan: settings.show_imgFilesizeSpan,
  647. googleReverse: settings.show_imgGoogle,
  648. IQDBreverse: settings.show_imgIqdb,
  649. blacklistToggle: settings.show_blacklistToggle,
  650. resizeToggles: settings.show_imgAllResizeToggles,
  651. hideToggles: settings.show_hideAllToggle,
  652. hideToggle: settings.show_hideToggle,
  653. };
  654. var imgContainerStyle = settings.imgContainerStyle;
  655. var autoScrollWhenThumbnailClicked = settings.auto_scroll_when_thumbnail_clicked;
  656. var thumbnailImgWidth = Number(settings.thumbnailWidth);
  657. var thumbnailImgHeight = Number(settings.thumbnailHeight);
  658. var thumbnailImgWidthSig = Number(settings.thumbnailWidthSig);
  659. var thumbnailImgHeightSig = Number(settings.thumbnailHeightSig);
  660. var expandedImgWidth = Number(settings.expandedWidth);
  661. var expandedImgHeight = Number(settings.expandedHeight);
  662. var imgContainerBackgroundColor = settings.imgContainerBackgroundColor;
  663. if (imgContainerBackgroundColor === "#000000") {
  664. imgContainerBackgroundColor = 0;
  665. }
  666. var blacklist = settings.blacklistStr.split("\n"); /*array of URLs to block*/
  667. var currentURL;
  668. var pageType; /* "topic" or "postPreview" or "other" */
  669. var allowImgInSig = settings.enable_sigs;
  670. var floatingImgWidth;
  671. var floatingImgRightOffset = 50;
  672. var floatingImgBorder = 10;
  673. var currentHoveredThumbnail = null;
  674. var imgAnchorTags = [];
  675. var expandedImgWidth_css = expandedImgWidth === 0 ? "" : expandedImgWidth+"px";
  676. var expandedImgHeight_css = expandedImgHeight === 0 ? "" : expandedImgHeight+"px";
  677. print("Global settings applied");
  678. var heldDownKeys = {};
  679. $("body").on("keydown", "#imagefaqs_settings_popup #hideToggleHotkey_text", function(event){
  680. heldDownKeys[event.which] = event.which;
  681. sessionHideToggleHotkey = cloneKVArray(heldDownKeys);
  682. $(this).val(
  683. keyCodeKVArrayToString(sessionHideToggleHotkey)
  684. );
  685. return false;
  686. });
  687. $("body").on("keydown", "#imagefaqs_settings_popup #resizeHotkey_text", function(event){
  688. heldDownKeys[event.which] = event.which;
  689. sessionResizeHotkey = cloneKVArray(heldDownKeys);
  690. $(this).val(
  691. keyCodeKVArrayToString(sessionResizeHotkey)
  692. );
  693. return false;
  694. });
  695. $("body").on("keyup", "#imagefaqs_settings_popup .hotkeyInput", function(event){
  696. delete heldDownKeys[event.which];
  697. return false;
  698. });
  699. $("body").on("keypress", "#imagefaqs_settings_popup .hotkeyInput", function(event){
  700. event.preventDefault();
  701. });
  702. /*
  703. Toggle between "display" and "hide" images.
  704. */
  705. function toggleImageVisiblity(embeddedImgContainers, via)
  706. {
  707. if (via === "hotkey")
  708. isHideMode = !isHideMode;
  709. /*If set images to be hidden...*/
  710. if ((via === "hotkey" && isHideMode) ||
  711. via === "closeAnchor")
  712. {
  713. if (pageType !== "other")
  714. {
  715. embeddedImgContainers.each(function(index, element) {
  716. if ($(this).hasClass("isHidable") && !$(this).hasClass("hiddenx")) {
  717. hideMedia($(this), false);
  718. }
  719. });
  720. if (via === "hotkey")
  721. showNotification("ImageFAQs: All images hidden.");
  722. }
  723. else
  724. {
  725. if (via === "hotkey")
  726. showNotification("ImageFAQs: Images will be hidden.");
  727. }
  728. }
  729. else
  730. {
  731. if (pageType !== "other")
  732. {
  733. embeddedImgContainers.each(function(index, element) {
  734. if ($(this).hasClass("hiddenx")) {
  735. showMedia($(this), false);
  736. }
  737. });
  738. if (via === "hotkey")
  739. showNotification("ImageFAQs: All images exposed.");
  740. }
  741. else
  742. {
  743. if (via === "hotkey")
  744. showNotification("ImageFAQs: Images will be exposed.");
  745. }
  746. }
  747. settings.isHideMode = isHideMode;
  748. localStorage.setItem("imagefaqs", JSON.stringify(settings));
  749. }
  750. var nextImageSize = "expanded";
  751. $("body").keydown(function(event){
  752. var key;
  753. var numMatchingPressedHotkeys;
  754. var desiredAction = "";
  755. heldDownKeys[event.which] = event.which;
  756. /*if backspace, ignore*/
  757. if (heldDownKeys[8] === 8)
  758. {
  759. return;
  760. }
  761. /*are every hide mode hotkey pressed?*/
  762. numMatchingPressedHotkeys = 0;
  763. for (key in settings.hideToggleHotkey)
  764. {
  765. if (settings.hideToggleHotkey[key] !== heldDownKeys[key])
  766. {
  767. break;
  768. }
  769. numMatchingPressedHotkeys++;
  770. }
  771. if (numMatchingPressedHotkeys === Object.size(settings.hideToggleHotkey) && numMatchingPressedHotkeys > 0)
  772. {
  773. desiredAction = "toggleHideMode";
  774. }
  775. /*is every resize hotkey pressed?*/
  776. if (desiredAction === "")
  777. {
  778. numMatchingPressedHotkeys = 0;
  779. for (key in settings.resizeHotkey)
  780. {
  781. if (settings.resizeHotkey[key] !== heldDownKeys[key])
  782. {
  783. break;
  784. }
  785. numMatchingPressedHotkeys++;
  786. }
  787. if (numMatchingPressedHotkeys === Object.size(settings.resizeHotkey) && numMatchingPressedHotkeys > 0)
  788. {
  789. desiredAction = "toggleImageResize";
  790. }
  791. }
  792. if (desiredAction === "toggleHideMode")
  793. {
  794. toggleImageVisiblity($(".embeddedImgContainer"), "hotkey");
  795. }
  796. else if (desiredAction === "toggleImageResize")
  797. {
  798. if (nextImageSize === "expanded")
  799. {
  800. toggleSizesOfImages($(".embeddedImg"), true);
  801. nextImageSize = "thumbnail";
  802. showNotification("ImageFAQs: Expanded all images.");
  803. }
  804. else
  805. {
  806. toggleSizesOfImages($(".embeddedImg.expandedImg"), false);
  807. nextImageSize = "expanded";
  808. showNotification("ImageFAQs: Shrunk all images.");
  809. }
  810. }
  811. });
  812. $("body").keyup(function(event){
  813. delete heldDownKeys[event.which];
  814. });
  815. if (blacklist.length === 1 && blacklist[0] === "")
  816. {
  817. blacklist = [];
  818. }
  819. else
  820. {
  821. /*trim white space*/
  822. for (var i = 0; i < blacklist.length; i++)
  823. {
  824. blacklist[i].trim();
  825. }
  826. }
  827. function isURLmatchBlacklistedURL(url, blacklistedURL)
  828. {
  829. blacklistedURL = blacklistedURL.trim();
  830. /*escape everything*/
  831. var blacklistedURLregex =
  832. new RegExp( blacklistedURL.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") );
  833. if (blacklistedURLregex.exec(url) !== null)
  834. {
  835. return true;
  836. }
  837. else
  838. {
  839. return false;
  840. }
  841. }
  842. /*
  843. Is the url string in the blacklist?
  844. @url :: string of the url to check
  845. @blacklist :: array of blacklisted urls
  846. Returns true or false
  847. */
  848. function isURLinBlacklist(url, blacklist)
  849. {
  850. for (var i = 0; i < blacklist.length; i++)
  851. {
  852. if (isURLmatchBlacklistedURL(url, blacklist[i]))
  853. {
  854. return true;
  855. }
  856. }
  857. return false;
  858. }
  859. $(window).scroll(function() {
  860. var notificationBoxes = $("body").children("#imagefaqs_notificationBox");
  861. notificationBoxes.each(function(index, element) {
  862. $(this).css({
  863. "top": ($(window).scrollTop() + $(window).height() - $(this).height())+"px",
  864. "left": ($(window).scrollLeft() + $(window).width() - $(this).find("span").width() - 1)+"px"
  865. });
  866. });
  867. });
  868. print("Parsing URL")
  869. currentURL = window.location.href;
  870. if (currentURL.match(/.*gamefaqs\.gamespot\.com\/boards\/.*\/.*\/.*/i)) /*gfaqsdep*/
  871. {
  872. pageType = "messageDetails";
  873. }
  874. else if (currentURL.match(/.*gamefaqs\.gamespot\.com\/boards\/.*\/.*/i)) /*gfaqsdep*/
  875. {
  876. pageType = "topic";
  877. }
  878. else if (currentURL.match(/.*gamefaqs\.gamespot\.com\/boards\/post/i)) /*gfaqsdep*/
  879. {
  880. pageType = "postPreview";
  881. }
  882. else if (currentURL.match(/.*gamefaqs\.gamespot\.com\/user[^\/]*$/i)) /*gfaqsdep*/
  883. {
  884. /*add settings link*/ /*gfaqsdep*/
  885. $("div.body tbody:eq(1)").append("<tr><td colspan='2'><a id='imagefaqs_settings_but' href='#'>ImageFAQs Options</a> - Change thumbnail size, enable signature embedding, and more.</td></tr>");
  886. }
  887. else
  888. {
  889. pageType = "other";
  890. return;
  891. }
  892. function GM_addStyle_from_file(fileName) {
  893. var head = document.head
  894. , link = document.createElement("link")
  895. link.type = "text/css"
  896. link.rel = "stylesheet"
  897. link.href = fileName
  898. head.appendChild(link)
  899. }
  900. function GM_addStyle_from_string(str) {
  901. var node = document.createElement('style');
  902. node.innerHTML = str;
  903. document.body.appendChild(node);
  904. }
  905. var jqueryuibaseCSS = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery.ui.base.css"
  906. var jqueryuithemeCSS = "https://code.jquery.com/ui/1.11.4/themes/cupertino/jquery-ui.css"
  907. print("GM_addStyle_from_file(jqueryuibaseCSS)")
  908. GM_addStyle_from_file (jqueryuibaseCSS);
  909. print("GM_addStyle_from_file(jqueryuithemeCSS)")
  910. GM_addStyle_from_file (jqueryuithemeCSS);
  911. print("GM_addStyle_from_string(all)")
  912. GM_addStyle_from_string (
  913. ".embeddedImgContainer {" +
  914. "background: "+imgContainerBackgroundColor+";" +
  915. "}" +
  916. ".embeddedImgAnchor {"+
  917. "display: inline-block;"+
  918. "}" +
  919. ".thumbnailImg {"+
  920. "display: inline-block;"+ /*prevents parent anchor from stretching horizontally*/
  921. "vertical-align: bottom;"+ /*eliminates small gap between bottom of image and parent div*/
  922. "}" +
  923. ".expandedImg {" +
  924. "display: inline-block;" +
  925. "vertical-align: bottom;" +
  926. "}" +
  927. ".imgMenuButton {" +
  928. "overflow: hidden;" +
  929. "position: absolute;" +
  930. "text-align: center;" +
  931. "z-index: 90;" +
  932. "background-color: #99FFCC;" +
  933. "opacity: 0.5;" +
  934. "pointer-events: none;" +
  935. "}" +
  936. ".imgMenuButton_symbol {" +
  937. "display: table-cell;" +
  938. "vertical-align: middle;" +
  939. "}" +
  940. ".imgMenuItem {" +
  941. "display: block;" +
  942. "}" +
  943. ".imgMenuItemAnchor {" +
  944. "display: block;" +
  945. "}" +
  946. ".imgMenu {" +
  947. "background-color: #CCFFFF;" +
  948. "opacity: 0.9;" +
  949. "border-style: solid;" +
  950. "border-width: 1px;" +
  951. "}" +
  952. ".ui-widget { " + /*shrink font size in the settings menu*/
  953. "font-size:96%;" +
  954. "}" +
  955. "#imagefaqs_settings_popup input { " +
  956. "margin-right: 5px;" +
  957. "}" +
  958. "#imagefaqs_settings_popup a { " +
  959. "color: blue;" +
  960. "}" +
  961. ".widget { " +
  962. "display: inline-block;"+ /*Allows wrapping of widget elements without expanding parent div (i.e. float left),*/
  963. "}", + /*and clears next element to newline (i.e. next element is not floating.*/
  964. ".imgResolution { " +
  965. "color: black;" +
  966. "}"
  967. );
  968. print("CSS applied");
  969. $("body").css("position", "relative");
  970. var posts = null;
  971. posts = $("div.msg_body"); /*gfaqsdep*/
  972. /* gfaqsdep. Remove the direct link icon that accompany each clickable URL */
  973. const embedLinkJDoms = posts.find('.embed_link');
  974. for (let embedLink of embedLinkJDoms) {
  975. const embedLinkJDom = $(embedLink);
  976. const url = embedLinkJDom.attr('href');
  977. if (url.match(/(user_image)|(imgur)/)) {
  978. $(embedLink).remove();
  979. }
  980. }
  981.  
  982. /* gfaqsdep. Replace gamefaqs anchors into our anchors. If anchor is accompanied by frame, delete the frame. */
  983. const imgToggleJDoms = posts.find(".click_embed")
  984. for (const imgToggleDom of imgToggleJDoms) {
  985. const imgToggleJDom = $(imgToggleDom)
  986. const imgSrc = imgToggleJDom.attr("data-src")
  987.  
  988. const isUserSrc = imgSrc.match(/user_image/);
  989. const isImgurSrc = imgSrc.match(/imgur/);
  990. const isAlbumSrc = imgSrc.match(/\/a\//);
  991.  
  992. if (isUserSrc || (isImgurSrc && !isAlbumSrc)) {
  993. const embedFrameJDom = imgToggleJDom.next('.embed_frame');
  994. if (embedFrameJDom.length > 0) {
  995. embedFrameJDom.remove();
  996. }
  997.  
  998. // next() doesn't work properly after replaceWith(), so call replaceWith() as last step.
  999. imgToggleJDom.replaceWith(`<a href="${imgSrc}">EmbedPlaceholder for ${imgSrc}</a>`)
  1000. }
  1001. }
  1002.  
  1003. /* gfaqsdep */
  1004. // We have removed the frames that accompanied the anchors, but there may
  1005. // be standalone frames with no accompanying anchors.
  1006. // iframe will be converted into anchor instead. This is required for
  1007. // "Always show images and media" mode.
  1008. const embedFrameJDoms = posts.find('.embed_frame'); // Get <div> that contain the iframe
  1009. for (let embedFrameDom of embedFrameJDoms) {
  1010. const embedFrameJDom = $(embedFrameDom)
  1011.  
  1012. const iframeJDom = embedFrameJDom.children().first(); // Get nested iframe
  1013. let isReplaceable = false;
  1014. let imgSrc = iframeJDom.attr('src') || '';
  1015. const iframeClass = iframeJDom.attr('class');
  1016.  
  1017. // Need first condition b/c iframe might match <blockquote>
  1018. if (imgSrc.match(/(gfycat)|(gamefaqs\.gamespot\.com)|(i\.imgur)/))
  1019. {
  1020. isReplaceable = true;
  1021. } else if (iframeClass.match(/imgur-embed-pub/)) {
  1022. isReplaceable = true;
  1023. const dataID = iframeJDom.attr('data-id');
  1024. imgSrc = `https://imgur.com/${dataID}`;
  1025. if (imgSrc.includes('/a/')) {
  1026. // Album.
  1027. if (isSkipImgurAlbum) {
  1028. // Chrome will always send http referrer which prevents
  1029. // imgur hotlink bypass.
  1030. isReplaceable = false;
  1031. }
  1032. }
  1033. } else if (iframeClass.match(/imgur-embed-iframe-pub-a-/)) { // Imgur album
  1034. // Example: id="imgur-embed-iframe-pub-a-eFrCukn" // a- indicates album.
  1035. isReplaceable = true;
  1036. const dataID = iframeJDom.attr('id');
  1037. const imgurID = dataID.replace('imgur-embed-iframe-pub-a-', '');
  1038. imgSrc = `https://imgur.com/a/${imgurID}`;
  1039. if (isSkipImgurAlbum) {
  1040. // Chrome will always send http referrer which prevents
  1041. // imgur hotlink bypass.
  1042. isReplaceable = false;
  1043. }
  1044. } else if (iframeClass.match(/imgur-embed-iframe-pub/)) {
  1045. isReplaceable = true;
  1046. // Example: id="imgur-embed-iframe-pub-PE8W5qk"
  1047. const dataID = iframeJDom.attr('id');
  1048. const imgurID = dataID.replace('imgur-embed-iframe-pub-', '');
  1049. imgSrc = `https://imgur.com/${imgurID}`;
  1050. } else {
  1051. // Don't remove (e.g. twitter embed).
  1052. }
  1053.  
  1054. if (isReplaceable) {
  1055. // If there's no .embedPlaceholder above, should convert this iframe into an anchor instead.
  1056. embedFrameJDom.replaceWith(`<a href="${imgSrc}">EmbedPlaceholderForFrame ${imgSrc}<a/>`)
  1057. print('replaced')
  1058. }
  1059. }
  1060. /* gfaqsdep = replace <img> user images with anchors (Always show images, but click-to-show media) */
  1061. let imgJDoms = posts.find("img")
  1062. for (let imgDom of imgJDoms) {
  1063. let imgJDom = $(imgDom)
  1064. let imgSrc = imgJDom.attr("src");
  1065. if (imgSrc.match(/user_image/)) {
  1066. imgJDom.replaceWith(`<a class='embedPlaceholder' href="${imgSrc}"><a/>`)
  1067. }
  1068. }
  1069. /* gfaqsdep. Special case for <a> that aren't embedded by gamefaqs for some reason.
  1070. Block must be positioned here after the rest for some reason */
  1071. const loneAnchorJDoms = posts.find("a");
  1072. for (const aEle of loneAnchorJDoms) {
  1073. const href = $(aEle).attr("href");
  1074. // Match like https://imgur.com/8ROZfAl/embed?ref=https%3A%2F%2Fgamefaqs.
  1075. // gamespot.com%2Fboards%2F2000121-anime-and-manga-other-titles%2F80628412
  1076. // &w=540
  1077. const m = /(https:\/\/imgur\.com\/\w+)\/embed/.exec(href);
  1078. if (m) {
  1079. // Capture like https://imgur.com/8ROZfAl
  1080. const imgurURL = m[1];
  1081. $(aEle).replaceWith(
  1082. `<a href="${imgurURL}">EmbedPlaceholderForFrame ${imgurURL}</a>`
  1083. );
  1084. }
  1085. }
  1086. print("Retrieved posts");
  1087. function getMediaTyping(obj)
  1088. {
  1089. var url = "";
  1090. if (typeof obj == "string")
  1091. {
  1092. url = obj;
  1093. }
  1094. else
  1095. {
  1096. url = getMediaURL(obj);
  1097. }
  1098. var mediaTyping = {
  1099. type: undefined,
  1100. subtype: undefined,
  1101. };
  1102. if (url.match(/i\.imgtc\.com\/\w+\.gifm$/))
  1103. {
  1104. mediaTyping.type = "iframe";
  1105. mediaTyping.subtype = "imgtc";
  1106. }
  1107. else if (url.match(/https?:\/\/[^<>\s]*?\.(?:png|jpg|gif|jpeg|webm|gifv|mp4)/i))
  1108. {
  1109. var mediaExt = url.split(".").pop();
  1110. mediaTyping.subtype = mediaExt.match(/png|jpg|gifv|gif|jpeg|webm|mp4/i)[0];
  1111. mediaTyping.type = mediaTyping.subtype.match(/webm|mp4|gifv/i) ? "video" : "image" ;
  1112. }
  1113. else if (url.match(/https?:\/\/gfycat\.com\/\w+$/i))
  1114. {
  1115. /*will be converted to webm later*/
  1116. mediaTyping.type = "iframe";
  1117. mediaTyping.subtype = "gfycat";
  1118. }
  1119. else if (url.match(/https?:\/\/(.\.)?imgur\.com\/(a\/)?\w+$/i))
  1120. {
  1121. /*will be converted to webm later*/
  1122. mediaTyping.type = "iframe";
  1123. mediaTyping.subtype = "imgur";
  1124. }
  1125. else
  1126. {
  1127. mediaTyping = undefined;
  1128. }
  1129. return mediaTyping;
  1130. }
  1131. function getMediaURL(obj)
  1132. {
  1133. if (obj.hasClass("embeddedImg"))
  1134. {
  1135. /*original 'href' may be modified to stop anchor events*/
  1136. return obj.closest(".embeddedImgAnchor").attr("data-backup-href");
  1137. }
  1138. else if (obj.hasClass("floatingImg"))
  1139. {
  1140. return obj.embeddedImgRef.closest(".embeddedImgAnchor").attr("data-backup-href");
  1141. }
  1142. else if (obj.hasClass(".embeddedImgContainer"))
  1143. {
  1144. return obj.find(".embeddedImgAnchor").attr("data-backup-href");
  1145. }
  1146. else
  1147. {
  1148. var container = getEmbeddedImgContainer(obj);
  1149. return container.find(".embeddedImgAnchor").attr("data-backup-href");
  1150. }
  1151. }
  1152. var jsPosts = $.makeArray(posts);
  1153. /*For each user post, get anchor tags that refer to media*/
  1154. async.each(jsPosts, function(jsPost, cb) {
  1155. var jqPost = $(jsPost);
  1156. /*if in post preview mode, need to manually parse through the preview message body and
  1157. replace every plain-text image URL in its anchor form
  1158. Bug fix: messageDetails already embeds clickable links.*/
  1159. if (pageType === "postPreview")
  1160. {
  1161. var postHtml = jqPost.html();
  1162. postHtml = postHtml.replace(/https?:\/\/[^<>\s]*?\.(?:png|jpg|gif|jpeg|webm|gifv|mp4)[^<>\s]*/ig, "<a href=\"$&\">$&</a>");
  1163. jqPost.html(postHtml);
  1164. }
  1165. /*get all anchor tags*/
  1166. const jsAnchorTags = $.makeArray(jqPost.find("a"));
  1167. jsPost.jsMediaAnchorTags = filterIn_mediaAnchorTags(jsAnchorTags);
  1168. markSigAnchorTags(jsPost.jsMediaAnchorTags, jqPost);
  1169. if (!allowImgInSig)
  1170. jsPost.jsMediaAnchorTags = removeSigAnchorTags(jsPost.jsMediaAnchorTags);
  1171. // Give each anchor tag the post number
  1172. let postID = jqPost.attr("data-msgnum"); /* gfaqsdep */
  1173. let i =0 ;
  1174. for (let jsAnchorTag of jsPost.jsMediaAnchorTags) {
  1175. jsAnchorTag.postID = postID
  1176. }
  1177. cb();
  1178. });
  1179. function filterIn_mediaAnchorTags(jsAnchorTags) {
  1180. const jsMediaAnchorTags = [];
  1181. for (let jsAnchorTag of jsAnchorTags) {
  1182. const jqAnchorTag = $(jsAnchorTag);
  1183. let anchorURL = jqAnchorTag.attr("href");
  1184. /* Bug fix: Hidden quote link */
  1185. if (anchorURL == null) {
  1186. continue;
  1187. }
  1188. /*Bug fix: Ignore @Username links*/
  1189. if (anchorURL.match(/^\/community\//)) {
  1190. continue;
  1191. }
  1192. /*Bug fix: Ignore 'FightingGames posted...' links*/
  1193. if (anchorURL.match(/^\/boards\//)) {
  1194. continue;
  1195. }
  1196. if (isTampermonkey) {
  1197. const embedType = jqAnchorTag.attr("data-embed-type");
  1198. if (embedType && embedType.match(/(imgur)|(gfycat)/)) {
  1199. if (jqAnchorTag[0] !== undefined) {
  1200. if (jqAnchorTag[0].nextSibling !== null && jqAnchorTag[0].nextSibling.nodeType === 3 /*isText?*/)
  1201. jqAnchorTag[0].nextSibling.nodeValue = ""; // remove "&nbsp;" text
  1202. if (jqAnchorTag.prev().is('br'))
  1203. jqAnchorTag.prev().remove(); // remove <br>
  1204. if (jqAnchorTag.next().next().is('br'))
  1205. jqAnchorTag.next().next().remove(); // remove <br> that's after the subsequent embedded anchor.
  1206. }
  1207. jqAnchorTag.remove();
  1208. continue;
  1209. }
  1210. else if (jqAnchorTag.hasClass("embed")) { // e.g. Twitter URL
  1211. continue;
  1212. }
  1213. else if (jqAnchorTag.prev().hasClass("embed")) { // e.g. small button
  1214. continue;
  1215. }
  1216. }
  1217. /*Bug fix: Occurs when opening image on same tab and returning. It will reparse URLs that
  1218. have already been rendered */
  1219. /*
  1220. if (jqAnchorTag.parent().hasClass("widget")) {
  1221. print("Filtered out URL header")
  1222. cb();
  1223. return;
  1224. }
  1225. if (jqAnchorTag.hasClass("embeddedImgAnchor")) {
  1226. print("Filtered out embeddedImgAnchor")
  1227. cb();
  1228. return;
  1229. }
  1230. if (jqAnchorTag.attr('href') == '#') {
  1231. print("Filtered out toggles")
  1232. cb();
  1233. return;
  1234. }
  1235. if (anchorURL.match(/(google\.com\/searchbyimage)|(iqdb\.org\/\?url)/)) {
  1236. print("Filtered out reverse image search links")
  1237. cb();
  1238. return;
  1239. }
  1240. */
  1241. /*In addition, convert URL if needed*/
  1242. anchorURL = standardizeURL(anchorURL);
  1243. jqAnchorTag.attr("href", anchorURL);
  1244. jqAnchorTag.html(anchorURL); /*bug fix: needed as well with href*/
  1245. if (getMediaTyping(anchorURL))
  1246. {
  1247. print("Filtered in " + anchorURL);
  1248. jqAnchorTag.addClass("imgAnchor");
  1249. jsMediaAnchorTags.push(jsAnchorTag);
  1250. }
  1251. }
  1252. return jsMediaAnchorTags;
  1253. }
  1254. function standardizeURL(url) {
  1255. var standardizeURL = ""
  1256. var mediaTyping = getMediaTyping(url);
  1257. if (mediaTyping != undefined && mediaTyping.subtype === "gifv")
  1258. {
  1259. standardizeURL = url.replace(/gifv$/i, "gif");
  1260. }
  1261. else
  1262. {
  1263. standardizeURL = url;
  1264. }
  1265. return standardizeURL;
  1266. }
  1267. function markSigAnchorTags(jsAnchorTags, jqPost) {
  1268. var postHtml;
  1269. var sigStrIdx;
  1270. /*get index of sig separator*/
  1271. if (legacySigDetection)
  1272. {
  1273. postHtml = jqPost.html();
  1274. sigStrIdx = postHtml.indexOf("<br>---<br>");
  1275. }
  1276. /*For each anchor tag, addClass('withinSig') if below signature mark*/
  1277. async.each(jsAnchorTags, function(jsAnchorTag, cb) {
  1278. var jqAnchorTag = $(jsAnchorTag);
  1279. var anchorURL = jqAnchorTag.attr('href');
  1280. var anchorTagStrIdx;
  1281. if (legacySigDetection)
  1282. anchorTagStrIdx = postHtml.indexOf(anchorURL + "</a>", 0);
  1283. /*if anchor is within of sig*/
  1284. if (jqAnchorTag.closest(".sig_text").length || /*gfaqsdep*/
  1285. legacySigDetection && sigStrIdx !== -1 && anchorTagStrIdx > sigStrIdx)
  1286. {
  1287. jqAnchorTag.addClass("withinSig");
  1288. }
  1289. cb();
  1290. });
  1291. }
  1292. function removeSigAnchorTags(jsAnchorTags) {
  1293. var nonSigAnchorTags = [];
  1294. async.eachSeries(jsAnchorTags, function(jsAnchorTag, cb) {
  1295. if (!$(jsAnchorTag).hasClass("withinSig"))
  1296. nonSigAnchorTags.push(jsAnchorTag);
  1297. cb();
  1298. });
  1299. return nonSigAnchorTags;
  1300. }
  1301. /*Merge all media anchor tags from all posts into a single array*/
  1302. //async.eachSeries(jsPosts, function(jsPost, cb) {
  1303. // imgAnchorTags = $.merge(imgAnchorTags, jsPost.jsMediaAnchorTags);
  1304. // cb();
  1305. //});
  1306. imgAnchorTags = []
  1307. for (const jsPost of jsPosts) {
  1308. for (const jsTag of jsPost.jsMediaAnchorTags)
  1309. imgAnchorTags.push(jsTag)
  1310. }
  1311. /*For each valid image URL anchor tag, replace with template div for embedded image template*/
  1312. var embeddedImgContainers = [];
  1313. for (let [imgAnchorIdx, imgAnchor] of imgAnchorTags.entries())
  1314. {
  1315. imgAnchor = $(imgAnchor);
  1316. const imgURL = imgAnchor.html();
  1317. const mediaTyping = getMediaTyping(imgURL);
  1318. const imgWithinSig_class = imgAnchor.hasClass("withinSig") ? "withinSig" : "";
  1319. const imgIsHidable_class = allowImgInSig && imgAnchor.hasClass("withinSig") && !hideSigsWhenHideMode ? "" : "isHidable";
  1320. const imgInitiallyBlacklisted_class = "";
  1321. const imgSpoilersTagged_class = imgAnchor.closest("s").length > 0 ? "spoilersTagged" : "";
  1322. var postID;
  1323. var isBlacklisted;
  1324. var imgContainerStyle_attr;
  1325.  
  1326. print("Creating container for " + imgURL);
  1327. isBlacklisted = isURLinBlacklist(imgURL, blacklist);
  1328. if (isBlacklisted)
  1329. imgInitiallyBlacklisted_class = "initiallyBlacklisted";
  1330. imgContainerStyle_attr = imgContainerStyle;
  1331. if (imgContainerStyle_attr === "sideBySideSig")
  1332. {
  1333. if (imgWithinSig_class === "withinSig")
  1334. imgContainerStyle_attr = "sideBySide";
  1335. else
  1336. imgContainerStyle_attr = "stacked";
  1337. }
  1338. if (pageType === "topic")
  1339. {
  1340. postID = imgAnchor[0].postID;
  1341. }
  1342. else /*if in post preview mode, need to provide missing message ID*/
  1343. {
  1344. imgAnchor.closest("td").addClass("msg_body"); /*gfaqsdep*/
  1345. imgAnchor.closest(".msg_body").attr("name", 0); /*gfaqsdep*/
  1346. postID = 0;
  1347. }
  1348. imgAnchor.replaceWith(
  1349. "<div class='embeddedImgContainer "+imgWithinSig_class+" "+imgIsHidable_class+" "+imgInitiallyBlacklisted_class+
  1350. " "+imgSpoilersTagged_class+"' data-postID='"+postID+"' data-style='"+imgContainerStyle_attr+"' data-idx='"+imgAnchorIdx+"'>" +
  1351. "<a class='embeddedImgAnchor' href='" + imgURL + "' data-backup-href='" + imgURL + "'>" +
  1352. "</a>" +
  1353. "</div>"
  1354. );
  1355. let embeddedImgContainer = $(".embeddedImgContainer[data-idx='"+imgAnchorIdx+"']");
  1356. embeddedImgContainers.push( embeddedImgContainer );
  1357. if (imgContainerStyle_attr == "stacked")
  1358. addDefaultWidgets(embeddedImgContainer);
  1359. print("Finished creating container for " + imgURL);
  1360. }
  1361. function getPredefinedWidgetStr(widgetClassStr, postID /*only for hideButtons*/)
  1362. {
  1363. if (widgetClassStr == "closeMediaButton")
  1364. {
  1365. return "<a class='closeMediaButton widget' target='_blank' href='#' title=''>"+
  1366. "[Close Media]"+
  1367. "</a>";
  1368. }
  1369. else if (widgetClassStr == "showButton")
  1370. {
  1371. return "<a class='imgHideToggle widget' href='#' title='Show image'>show</a>";
  1372. }
  1373. else if (widgetClassStr == "hideButtons")
  1374. {
  1375. return "<a class='imgHideAll widget' href='#' style='margin-right: 5px' title='Hide all images in page'>--</a>" +
  1376. "<a class='imgHidePost widget' href='#' style='margin-right: 5px' data-postID='"+postID+"' title='Hide all images in post'>-</a>" +
  1377. "<a class='imgShowPost widget' href='#' style='margin-right: 5px' data-postID='"+postID+"' title='Show all images in post'>+</a>" +
  1378. "<a class='imgShowAll widget' href='#' title='Show all images in page'>++</a>";
  1379. }
  1380. else if (widgetClassStr == "whitelistButton")
  1381. {
  1382. return "<a class='imgBlacklistToggle widget' href='#' title='Whitelist image'>whitelist</a>";
  1383. }
  1384. }
  1385. function addDefaultWidgets(container)
  1386. {
  1387. let embeddedImgContainer;
  1388. let imgURL = "";
  1389. let postID;
  1390. let isBlacklisted;
  1391. let isSpoilersTagged;
  1392. let isHidable;
  1393. let imgWidgets = {
  1394. URLSpan: "",
  1395. resolutionSpan: "",
  1396. filesizeSpan: "",
  1397. googleReverse: "",
  1398. IQDBreverse: "",
  1399. blacklistToggle: "",
  1400. resizeToggles: "",
  1401. hideToggles: "",
  1402. hideToggle: "",
  1403. };
  1404. if (container.hasClass("imgMenu"))
  1405. embeddedImgContainer = getEmbeddedImgContainer(container);
  1406. else
  1407. embeddedImgContainer = container;
  1408. imgURL = embeddedImgContainer.children(".embeddedImgAnchor").attr("href");
  1409. postID = embeddedImgContainer.attr("data-postID");
  1410. isBlacklisted = embeddedImgContainer.hasClass("blacklisted");
  1411. isSpoilersTagged = embeddedImgContainer.hasClass("spoilersTagged");
  1412. isHidable = embeddedImgContainer.hasClass("isHidable");
  1413. isImgMenu = container.hasClass("imgMenu");
  1414. print("Started addDefaultWidgets() for " + imgURL);
  1415. imgWidgets.URLSpan =
  1416. "<span class='imgURL widget'>" +
  1417. "<a target='_blank' href="+imgURL+">"+imgURL+"</a>" +
  1418. "</span>";
  1419. imgWidgets.resolutionSpan =
  1420. "<span class='imgResolution widget'>" +
  1421. "" +
  1422. "</span>";
  1423. imgWidgets.filesizeSpan =
  1424. "<span class='imgFilesize widget'>" +
  1425. "" +
  1426. "</span>";
  1427. imgWidgets.googleReverse =
  1428. "<a class='widget' target='_blank' title='Reverse image search on general images' href='https://www.google.com/searchbyimage?image_url="+imgURL+"'>" +
  1429. "google" +
  1430. "</a>";
  1431. imgWidgets.IQDBreverse =
  1432. "<a class='widget' target='_blank' title='Reverse image search on weeb images' href='http://iqdb.org/?url="+imgURL+"'>" +
  1433. "iqdb" +
  1434. "</a>";
  1435. if (isBlacklisted)
  1436. {
  1437. alert('here');
  1438. imgWidgets.blacklistToggle =
  1439. getPredefinedWidgetStr("whitelistButton");
  1440. }
  1441. else
  1442. {
  1443. imgWidgets.blacklistToggle =
  1444. "<a class='imgBlacklistToggle widget' href='#' title='Blacklist image'>blacklist</a>";
  1445. }
  1446. imgWidgets.resizeToggles =
  1447. "<a class='imgCloseAll widget' href='#' style='margin-right: 5px' title='Close all images in page'>&lt;&lt;</a>" +
  1448. "<a class='imgClosePost widget' href='#' style='margin-right: 5px' data-postID='"+postID+"' title='Close all images in post'>&lt;</a>" +
  1449. "<a class='imgExpandPost widget' href='#' style='margin-right: 5px' data-postID='"+postID+"' title='Expand all images in post'>&gt;</a>" +
  1450. "<a class='imgExpandAll widget' href='#' title='Expand all images in page'>&gt;&gt;</a>";
  1451. imgWidgets.hideToggles =
  1452. getPredefinedWidgetStr("hideButtons", postID);
  1453. /*
  1454. Bug fix: Added !isImgMenu in condition. Otherwise, when revealing a hidden
  1455. spoilered side-by-side image for the first time, its hideToggle widget will
  1456. mistakenly be set to "Show" instead of "Hide"
  1457. */
  1458. if (!isImgMenu && (isBlacklisted || isSpoilersTagged || (isHideMode && isHidable)))
  1459. {
  1460. imgWidgets.hideToggle =
  1461. getPredefinedWidgetStr("showButton");
  1462. }
  1463. else
  1464. {
  1465. imgWidgets.hideToggle =
  1466. "<a class='imgHideToggle widget' href='#' title='Hide image'>hide</a>";
  1467. }
  1468. print("Built widget strings in addDefaultWidgets() for " + imgURL);
  1469. async.eachOfSeries(imgWidgets, function(widget, widgetName, cb){
  1470. /*Bug fix: If 'hide toggle' widget disabled, then there's no way to reveal
  1471. a spoilered image. So, always add 'hide toggle' for spoilered images.*/
  1472. if (isShow[widgetName] || (widgetName == "hideToggle" && isSpoilersTagged))
  1473. {
  1474. //console.log("Adding widget (\""+widgetName+"\") string (\""+widget+"\") in addDefaultWidgets() for " + imgURL);
  1475. setWidget(widget, container);
  1476. }
  1477. cb();
  1478. });
  1479. }
  1480. function setWidget(widgetStr, container, removeClassStr)
  1481. {
  1482. let widget;
  1483. let widgets;
  1484. /*If adding first widget*/
  1485. if (!removeClassStr && container.children(".widgets").length == 0)
  1486. {
  1487. container.prepend("<div class='widgets'></div>");
  1488. }
  1489. widgets = container.children(".widgets");
  1490. if (container.hasClass("embeddedImgContainer"))
  1491. {
  1492. if (removeClassStr)
  1493. {
  1494. widgets.find("." + removeClassStr).remove();
  1495. }
  1496. else
  1497. {
  1498. widgets.append(widgetStr);
  1499. /*add leading whitespace to new widget*/
  1500. widget = widgets.children(':last');
  1501. widget.css('margin-right', '5px');
  1502. }
  1503. }
  1504. else if (container.hasClass("imgMenu"))
  1505. {
  1506. if (removeClassStr)
  1507. {
  1508. widgets.find("." + removeClassStr).closest(".imgMenuItem").remove();
  1509. }
  1510. else
  1511. {
  1512. widgetStr = "<div class='imgMenuItem'>" +
  1513. widgetStr +
  1514. "</div>";
  1515. widgets.append(widgetStr);
  1516. }
  1517. }
  1518. else
  1519. {
  1520. }
  1521. /*If removed last widget*/
  1522. if (removeClassStr && widgets.children().length == 0)
  1523. {
  1524. widgets.remove();
  1525. }
  1526. }
  1527. function getWidget(classStr, container)
  1528. {
  1529. var widgets = container.children(".widgets");
  1530. return widgets.find("." + classStr);
  1531. }
  1532. function hasWidget(classStr, container)
  1533. {
  1534. return container.find(".widgets").find("."+classStr).length > 0;
  1535. }
  1536. function getEmbeddedImgContainer(obj)
  1537. {
  1538. var embeddedImgContainer = obj.closest(".embeddedImgContainer");
  1539. if (embeddedImgContainer.length == 0)
  1540. {
  1541. var imgAnchor = getImageAnchorOfImgMenu();
  1542. embeddedImgContainer = imgAnchor.closest(".embeddedImgContainer");
  1543. }
  1544. return embeddedImgContainer;
  1545. }
  1546. /*Optimize positioning of media*/
  1547. async.eachSeries(embeddedImgContainers, function(embeddedImgContainer, cb) {
  1548. print("Started optimizing media position for " + getMediaURL(embeddedImgContainer));
  1549. var imgContainerStyle_attr = embeddedImgContainer.attr('data-style');
  1550. /*keep iterating through the next sibling elements until find an element that's
  1551. not whitespace*/
  1552. var curNextEleJS = embeddedImgContainer[0].nextSibling;
  1553. while (curNextEleJS !== null &&
  1554. ($(curNextEleJS).is("br") || is_ignorable(curNextEleJS)))
  1555. {
  1556. curNextEleJS = curNextEleJS.nextSibling;
  1557. }
  1558. /*now do the same thing, but iterating through the previous siblings*/
  1559. var curPrevEleJS = embeddedImgContainer[0].previousSibling;
  1560. while (curPrevEleJS !== null &&
  1561. is_ignorable(curPrevEleJS))
  1562. {
  1563. curPrevEleJS = curPrevEleJS.previousSibling;
  1564. }
  1565. /*at this point, we have two non-whitespace elements surrounding the embeddedImgContainer*/
  1566. /*remove the next br elements if next non-whitespace sibling is a going-to-be image*/
  1567. var curNextEle;
  1568. if (curNextEleJS !== null && $(curNextEleJS).hasClass("embeddedImgContainer"))
  1569. {
  1570. curNextEle = embeddedImgContainer.next();
  1571. while (curNextEle.length !== 0 && curNextEle.is("br"))
  1572. {
  1573. if (curNextEle.next().length === 0)
  1574. {
  1575. curNextEle.remove();
  1576. break;
  1577. }
  1578. else
  1579. {
  1580. curNextEle = curNextEle.next();
  1581. curNextEle.prev().remove();
  1582. }
  1583. }
  1584. }
  1585. /*if sig separator after image, remove <br> in between*/ /*gfaqsdeplegacy - no br anymore*/
  1586. else if (curNextEleJS !== null && curNextEleJS.nodeType === 3 && curNextEleJS.nodeValue === "---")
  1587. {
  1588. curNextEle = embeddedImgContainer.next();
  1589. if (curNextEle.is("br"))
  1590. curNextEle.remove();
  1591. }
  1592. /*if text after image*/ /*gfaqsdeplegacy - no br anymore*/
  1593. else if (curNextEleJS !== null && curNextEleJS.nodeType === 3 && curNextEleJS.nodeValue !== "---")
  1594. {
  1595. curNextEle = embeddedImgContainer.next();
  1596. if (curNextEle.is("br"))
  1597. curNextEle.remove();
  1598. }
  1599. if (imgContainerStyle_attr === "sideBySide")
  1600. {
  1601. /*if the next non-whitespace sibling not going to be an image, create a newline to
  1602. set the cursor below this image*/
  1603. if (curNextEleJS !== null && !$(curNextEleJS).hasClass("embeddedImgContainer"))
  1604. {
  1605. $(curNextEleJS).before(
  1606. "<div style='display: block;'></div>"
  1607. );
  1608. }
  1609. /*do same with previous non-whitespace sibling*/
  1610. if (curPrevEleJS !== null && !$(curPrevEleJS).hasClass("embeddedImgContainer"))
  1611. {
  1612. $(curPrevEleJS).after(
  1613. "<div style='display: block;'></div>"
  1614. );
  1615. }
  1616. /*set container to float*/
  1617. embeddedImgContainer.css("display", "inline-block");
  1618. embeddedImgContainer.css("vertical-align", "top");
  1619. embeddedImgContainer.css("margin-right", "5px");
  1620. embeddedImgContainer.css("margin-bottom", "5px");
  1621. }
  1622. else
  1623. {
  1624. embeddedImgContainer.css("margin-bottom", "10px");
  1625. }
  1626. print("Finished optimizing media position for " + getMediaURL(embeddedImgContainer));
  1627. cb();
  1628. });
  1629. /*for each template div, insert an embedded image*/
  1630. async.each(embeddedImgContainers, function(embeddedImgContainer, cb) {
  1631. if (isHideMode)
  1632. {
  1633. if (embeddedImgContainer.hasClass("isHidable"))
  1634. hideMedia(embeddedImgContainer, false);
  1635. else
  1636. loadMedia(embeddedImgContainer, false);
  1637. }
  1638. else
  1639. {
  1640. var isBlacklisted = embeddedImgContainer.hasClass("initiallyBlacklisted");
  1641. var isSpoilersTagged = embeddedImgContainer.hasClass("spoilersTagged");
  1642. if (isBlacklisted)
  1643. hideMedia(embeddedImgContainer, true);
  1644. else if (isSpoilersTagged)
  1645. hideMedia(embeddedImgContainer, false);
  1646. else
  1647. loadMedia(embeddedImgContainer, false);
  1648. }
  1649. cb();
  1650. });
  1651. function getMediaSize(media, span)
  1652. {
  1653. var url = getEmbeddedImgContainer(media).find(".embeddedImgAnchor").attr('href');
  1654. GM_xmlhttpRequest({
  1655. method: "GET",
  1656. url: url,
  1657. onload: function(response) {
  1658. var contentLengthStr = response.responseHeaders.match(/Content-Length: \d+/)[0];
  1659. var fileSizeBytes = parseInt(contentLengthStr.substring(16));
  1660. var fileSizeDisplayStr;
  1661. if (fileSizeBytes < 1000000) /*if less than 1.0MB*/
  1662. {
  1663. fileSizeDisplayStr = Math.round(fileSizeBytes / 1000) + "KB";
  1664. }
  1665. else
  1666. {
  1667. fileSizeDisplayStr = (fileSizeBytes / 1000000).toFixed(2) + "MB";
  1668. }
  1669. span.html("("+fileSizeDisplayStr+")");
  1670. }
  1671. });
  1672. }
  1673. function getMediaResolution(media, span)
  1674. {
  1675. if (span.length == 0)
  1676. return;
  1677. var mediaTyping = getMediaTyping(media);
  1678. if (mediaTyping.type == "video")
  1679. {
  1680. /*when video's metadata has been loaded, record its natural width and resolution*/
  1681. media[0].onloadedmetadata = function() {
  1682. var video = this;
  1683. span.html("(" + video.videoWidth + "x" + video.videoHeight + ")");
  1684. };
  1685. /*If video already loaded*/
  1686. if (media[0].videoWidth !== 0)
  1687. span.html("(" + media[0].videoWidth + "x" + media[0].videoHeight + ")");
  1688. }
  1689. else if (mediaTyping.type == "image")
  1690. {
  1691. media.load(function() {
  1692. span.html("(" + media[0].naturalWidth + "x" + media[0].naturalHeight + ")");
  1693. });
  1694. /*if image already loaded*/
  1695. if (media[0].naturalWidth !== 0)
  1696. {
  1697. span.html("(" + media[0].naturalWidth + "x" + media[0].naturalHeight + ")");
  1698. }
  1699. }
  1700. }
  1701. function showMedia(mediaContainer, isToWhitelist)
  1702. {
  1703. var mediaAnchor = mediaContainer.children(".embeddedImgAnchor");
  1704. var mediaURL = mediaAnchor.attr("data-backup-href");
  1705. var mediaContainerStyle = mediaContainer.attr("data-style");
  1706. var isSpoilersTagged = mediaContainer.hasClass("spoilersTagged");
  1707. if (!mediaContainer.hasClass("loaded"))
  1708. loadMedia(mediaContainer);
  1709. mediaContainer.removeClass("hiddenx");
  1710. if (isToWhitelist)
  1711. {
  1712. /*remove url from blacklist*/
  1713. var urlIdx = blacklist.indexOf(mediaURL);
  1714. if (urlIdx > -1)
  1715. {
  1716. blacklist.splice(urlIdx, 1);
  1717. }
  1718. mediaAnchor.removeClass("blacklisted");
  1719. if (mediaContainerStyle === "stacked" && isShow.blacklistToggle)
  1720. {
  1721. var imgBlacklistToggle = getWidget("imgBlacklistToggle", mediaContainer);
  1722. imgBlacklistToggle.html("blacklist");
  1723. imgBlacklistToggle.attr("title", "Blacklist image");
  1724. }
  1725. settings.blacklistStr = blacklist.join("\n");
  1726. localStorage.setItem("imagefaqs", JSON.stringify(settings));
  1727. }
  1728. mediaAnchor.show();
  1729. if (mediaContainerStyle === "sideBySide")
  1730. {
  1731. mediaAnchor.siblings("a.imgMenuItem").remove();
  1732. mediaAnchor.siblings("div.imgMenuItem").remove();
  1733. mediaAnchor.attr("style", "");
  1734. mediaAnchor.parent().css("max-width", "");
  1735. }
  1736. else
  1737. {
  1738. /*Bug fix: Spoilered images must have hideToggle regardless.*/
  1739. if (isShow.hideToggle || isSpoilersTagged)
  1740. {
  1741. var imgHideToggle = getWidget("imgHideToggle", mediaContainer);
  1742. imgHideToggle.html("hide");
  1743. imgHideToggle.attr("title", "Hide image");
  1744. }
  1745. }
  1746. }
  1747. function hideMedia(mediaContainer, isToBlacklist)
  1748. {
  1749. var mediaAnchor = mediaContainer.children(".embeddedImgAnchor");
  1750. var media = mediaAnchor.children(".embeddedImg");
  1751. var mediaURL = mediaAnchor.attr("data-backup-href");
  1752. var postID = mediaContainer.attr("data-postID");
  1753. var mediaContainerStyle = mediaContainer.attr("data-style");
  1754. var isSig = mediaContainer.hasClass("withinSig");
  1755. var isSpoilersTagged = mediaContainer.hasClass("spoilersTagged");
  1756. var mediaThumbnailImgWidth = isSig ? thumbnailImgWidthSig : thumbnailImgWidth;
  1757. var mediaThumbnailImgHeight = isSig ? thumbnailImgHeightSig : thumbnailImgHeight;
  1758. var mediaThumbnailImgWidth_css = mediaThumbnailImgWidth === 0 ? "" : mediaThumbnailImgWidth+"px";
  1759. var mediaThumbnailImgHeight_css = mediaThumbnailImgHeight === 0 ? "" : mediaThumbnailImgHeight+"px";
  1760. print("Started hideMedia() for " + mediaURL);
  1761. /*shrink image*/
  1762. if (media.hasClass("expandedImg"))
  1763. toggleSizesOfImages(media, false);
  1764. mediaContainer.addClass("hiddenx");
  1765. mediaAnchor.hide();
  1766. print("Hidden mediaAnchor in hideMedia() for " + mediaURL);
  1767. if (isToBlacklist)
  1768. {
  1769. mediaAnchor.addClass("blacklisted");
  1770. if (blacklist.indexOf(mediaURL) === -1)
  1771. blacklist.push(mediaURL);
  1772. var imgBlacklistToggle = getWidget("imgBlacklistToggle", mediaContainer);
  1773. imgBlacklistToggle.html("blacklist");
  1774. imgBlacklistToggle.attr("title", "Blacklist image");
  1775. settings.blacklistStr = blacklist.join("\n");
  1776. localStorage.setItem("imagefaqs", JSON.stringify(settings));
  1777. }
  1778. if (mediaContainerStyle === "sideBySide")
  1779. {
  1780. mediaContainer.css("max-width", mediaThumbnailImgWidth_css);
  1781. if (isShow.URLSpan)
  1782. {
  1783. mediaContainer.append("<a target='_blank' class='imgMenuItem' href="+mediaURL+">"+mediaURL+"</a>");
  1784. widget = mediaContainer.children(':last');
  1785. widget.css('margin-right', '5px');
  1786. widget.css('display', 'inline');
  1787. }
  1788. if (mediaAnchor.hasClass("blacklisted"))
  1789. {
  1790. if (isShow.blacklistToggle)
  1791. {
  1792. mediaContainer.append(
  1793. "<div class='imgMenuItem'>" +
  1794. getPredefinedWidgetStr("whitelistButton") +
  1795. "</div>"
  1796. );
  1797. /*add leading whitespace to new widget*/
  1798. widget = mediaContainer.children(':last');
  1799. widget.css('margin-right', '5px');
  1800. widget.css('display', 'inline');
  1801. }
  1802. }
  1803. if (isShow.hideAllToggle)
  1804. {
  1805. mediaContainer.append(
  1806. "<div class='imgMenuItem'>" +
  1807. getPredefinedWidgetStr("hideButtons", postID) +
  1808. "</div>"
  1809. );
  1810. /*add leading whitespace to new widget*/
  1811. widget = mediaContainer.children(':last');
  1812. widget.css('margin-right', '5px');
  1813. widget.css('display', 'inline');
  1814. }
  1815. /*Bug fix: Hidden images must always have show button.*/
  1816. mediaContainer.append(
  1817. "<div class='imgMenuItem'>" +
  1818. getPredefinedWidgetStr("showButton") +
  1819. "</div>"
  1820. );
  1821. /*add leading whitespace to new widget*/
  1822. widget = mediaContainer.children(':last');
  1823. widget.css('margin-right', '5px');
  1824. widget.css('display', 'inline');
  1825. /*remove leading whitespace to last widget*/
  1826. widget = mediaContainer.children(':last');
  1827. widget.css('margin-right', '');
  1828. hideImgMenu();
  1829. }
  1830. else /* stacked */
  1831. {
  1832. if (isShow.blacklistToggle && isToBlacklist)
  1833. {
  1834. var imgBlacklistToggle = getWidget("imgBlacklistToggle", mediaContainer);
  1835. imgBlacklistToggle.html("whitelist");
  1836. imgBlacklistToggle.attr("title", "Whitelist image");
  1837. }
  1838. }
  1839. if (mediaContainerStyle === "sideBySide")
  1840. {
  1841. }
  1842. else
  1843. {
  1844. /*Bug fix: Spoilered images must have hideToggle regardless.*/
  1845. if (isShow.hideToggle || isSpoilersTagged)
  1846. {
  1847. var imgHideToggle = getWidget("imgHideToggle", mediaContainer);
  1848. imgHideToggle.html("show");
  1849. imgHideToggle.attr("title", "Show image");
  1850. }
  1851. }
  1852. }
  1853. function loadMedia(mediaContainer)
  1854. {
  1855. print("Started loadMedia() for " + getMediaURL(mediaContainer));
  1856. getMediaRemoteInfo(mediaContainer, function(mediaInfo) {
  1857. print("Started callback for getMediaRemoteInfo() for " + getMediaURL(mediaContainer));
  1858. if (mediaInfo == undefined)
  1859. return;
  1860. updateEmbeddedImgContainer(mediaContainer, mediaInfo);
  1861. _loadMedia(mediaContainer);
  1862. });
  1863. }
  1864. function _loadMedia(mediaContainer, mediaInfo)
  1865. {
  1866. const mediaAnchor = mediaContainer.children(".embeddedImgAnchor");
  1867. const mediaURL = mediaAnchor.attr("href");
  1868. const mediaTyping = getMediaTyping(mediaURL);
  1869. const mediaResolutionSpan = getWidget("imgResolution", mediaContainer);
  1870. const mediaFilesizeSpan = getWidget("imgFilesize", mediaContainer);
  1871. const mediaIdx = mediaContainer.attr("data-idx");
  1872. const isSig = mediaContainer.hasClass("withinSig");
  1873. const mediaThumbnailImgWidth = isSig ? thumbnailImgWidthSig : thumbnailImgWidth;
  1874. const mediaThumbnailImgHeight = isSig ? thumbnailImgHeightSig : thumbnailImgHeight;
  1875. const mediaThumbnailImgWidth_css = mediaThumbnailImgWidth === 0 ? "" : mediaThumbnailImgWidth+"px";
  1876. const mediaThumbnailImgHeight_css = mediaThumbnailImgHeight === 0 ? "" : mediaThumbnailImgHeight+"px";
  1877. print("Started _loadMedia() for " + mediaURL);
  1878. var mediaStr = "";
  1879. var media;
  1880. mediaStr = createEmbeddedMediaStr({src: mediaURL});
  1881. mediaAnchor.html(mediaStr);
  1882. media = mediaAnchor.find(".embeddedImg");
  1883. bypassHotlink(media);
  1884. const styles = {
  1885. "max-width": getOptimalImgMaxWidth_css(media, mediaThumbnailImgWidth),
  1886. "max-height": mediaThumbnailImgHeight_css,
  1887. };
  1888. addStyling(media, styles);
  1889. addEvents(media);
  1890. media.attr("display", "");
  1891. if (mediaResolutionSpan.length > 0)
  1892. getMediaResolution(media, mediaResolutionSpan);
  1893. if (mediaFilesizeSpan.length > 0)
  1894. getMediaSize(media, mediaFilesizeSpan);
  1895. if (mediaContainer.hasClass("withinSig"))
  1896. mediaContainer.find(".embeddedImg").addClass("withinSig");
  1897. if (mediaTyping.type == "video" && loopThumbnailVideo)
  1898. {
  1899. media.prop('muted', true); // Must be done before play() according to chrome 66 auto-play policy
  1900. media[0].play();
  1901. media.prop("loop", true);
  1902. }
  1903. mediaContainer.addClass("loaded");
  1904. print("Finished _loadMedia() for " + mediaURL);
  1905. }
  1906. function bypassHotlink(media) {
  1907. media.prop('referrerPolicy', 'no-referrer');
  1908. if (media.is('img')) {
  1909. media.attr('src', media.attr('data-src'));
  1910. }
  1911. else {
  1912. var videoSource = media.find('source');
  1913. videoSource.attr('src', videoSource.attr('data-src'));
  1914. }
  1915. }
  1916. /*
  1917. Get an embeddable media element.
  1918. Param:
  1919. properties [obj] =
  1920. .src = [string]
  1921. .isFloatingImg = (bool)
  1922. */
  1923. function createEmbeddedMediaStr(properties) {
  1924. var mediaStr = "";
  1925. const mediaTyping = getMediaTyping(properties.src);
  1926. const src = properties.src;
  1927. var mediaClassStr = "";
  1928. if (properties.isFloatingImg === true)
  1929. mediaClassStr = "floatingImg";
  1930. else
  1931. mediaClassStr = "embeddedImg thumbnailImg";
  1932. // const imgurMatch = src.match(/imgur\.com\/(\w+)\.mp4/); // gfaqsdep
  1933. // if (imgurMatch) {
  1934. // const imgurId = imgurMatch[1];
  1935. // mediaStr = `<blockquote class="imgur-embed-pub" lang="en" data-id="${imgurId}"><a href="https://imgur.com/${imgurId}">View post on imgur.com</a></blockquote><script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script>`;
  1936. // }
  1937. if (mediaTyping.type == "image")
  1938. {
  1939. mediaStr = "<img class='"+mediaClassStr+"' alt='' display='none' data-src='"+properties.src+"'></img>";
  1940. }
  1941. else if (mediaTyping.type == "video")
  1942. {
  1943. mediaStr = "<video class='"+mediaClassStr+"' display='none' style=''>"+
  1944. "<source data-src='"+properties.src+"' type='video/"+mediaTyping.subtype+"'>" +
  1945. "</video>";
  1946. }
  1947. return mediaStr;
  1948. }
  1949. function getMediaRemoteInfo(mediaContainer, cb)
  1950. {
  1951. var mediaInfo = {};
  1952. var url = mediaContainer.find(".embeddedImgAnchor").attr("href");
  1953. var mediaTyping = getMediaTyping(url);
  1954. print("Started getMediaRemoteInfo() for " + url);
  1955. /*If gfycat url*/
  1956. if (mediaTyping != undefined && mediaTyping.type == "iframe" && mediaTyping.subtype == "gfycat")
  1957. {
  1958. url = url.match(/\w+$/)[0];
  1959. url = "https://api.gfycat.com/v1/gfycats/" + url;
  1960. GM.xmlHttpRequest({
  1961. method: "GET",
  1962. url: url,
  1963. onload: function(response) {
  1964. const rawInfo = JSON.parse(response.responseText);
  1965. if (rawInfo.error)
  1966. {
  1967. errorEvent(mediaContainer);
  1968. cb(undefined)
  1969. }
  1970. else
  1971. {
  1972. mediaInfo.url = rawInfo.gfyItem.webmUrl;
  1973. cb(mediaInfo);
  1974. }
  1975. },
  1976. onerror: function(response) {
  1977. errorEvent(mediaContainer);
  1978. cb(undefined)
  1979. }
  1980. });
  1981. }
  1982. /*If imgur url*/
  1983. else if (mediaTyping != undefined && mediaTyping.type == "iframe" && mediaTyping.subtype == "imgur")
  1984. {
  1985. const match = url.match(/https?:\/\/(?:.\.)?imgur\.com\/(a\/)?(\w+)$/);
  1986. const isAlbum = url.match(/imgur\.com\/a\/\w+/); // Workaround for firefox
  1987. const imgurId = match[match.length-1];
  1988. const requestUrl = (isAlbum) ?
  1989. `https://api.imgur.com/3/album/${imgurId}/images`
  1990. :
  1991. `https://api.imgur.com/3/image/${imgurId}`;
  1992.  
  1993. GM.xmlHttpRequest({
  1994. method: "GET",
  1995. url: requestUrl,
  1996. headers: {'Authorization': "Client-ID 05793c686154d2a"},
  1997. onload: async function(response) {
  1998. if (response.status !== 200)
  1999. {
  2000. errorEvent(mediaContainer, "Imgur API Key to resolve non-direct link is currently over-capacity.");
  2001. cb(undefined)
  2002. return;
  2003. }
  2004. const rawInfo = JSON.parse(response.responseText);
  2005. if (rawInfo.error)
  2006. {
  2007. errorEvent(mediaContainer);
  2008. cb(undefined)
  2009. }
  2010. else if (!rawInfo.success)
  2011. {
  2012. errorEvent(mediaContainer, rawInfo.data.error);
  2013. cb(undefined)
  2014. }
  2015. else
  2016. {
  2017. if (isAlbum) {
  2018. mediaInfo.url = rawInfo.data[0].link;
  2019. } else {
  2020. mediaInfo.url = rawInfo.data.link;
  2021. }
  2022.  
  2023. cb(mediaInfo);
  2024. }
  2025. },
  2026. onerror: function(response) {
  2027. errorEvent(mediaContainer);
  2028. cb(undefined)
  2029. }
  2030. });
  2031. }
  2032. else if (mediaTyping != undefined && mediaTyping.type == "iframe" && mediaTyping.subtype == "imgtc")
  2033. {
  2034. let requestUrl = url;
  2035. GM.xmlHttpRequest({
  2036. method: "GET",
  2037. url: requestUrl,
  2038. headers: {"origin": currentURL},
  2039. onload: function(response) {
  2040. var rawInfo = response.responseText;
  2041. if (rawInfo.error)
  2042. {
  2043. errorEvent(mediaContainer);
  2044. cb(undefined)
  2045. }
  2046. else
  2047. {
  2048. /*
  2049. <html style="background-color: #212121; float: center;">
  2050. <center><video controls autoplay muted loop><source src="u2KmIOe.webm" type="video/webm"></video></center>
  2051. </html>
  2052. */
  2053. let type = (rawInfo.match(/video\/webm/)) ? 'webm' :
  2054. (rawInfo.match(/video\/mp4/)) ? 'mp4' :
  2055. 'gif';
  2056. mediaInfo.url = url.replace(/gifm$/i, type);
  2057. cb(mediaInfo);
  2058. }
  2059. },
  2060. onerror: function(response) {
  2061. errorEvent(mediaContainer);
  2062. cb(undefined)
  2063. }
  2064. });
  2065. }
  2066. else
  2067. {
  2068. cb(mediaInfo);
  2069. }
  2070. }
  2071. function updateEmbeddedImgContainer(mediaContainer, mediaInfo)
  2072. {
  2073. if (mediaInfo.url)
  2074. {
  2075. print("Started updateEmbeddedImgContainer() for " + mediaInfo.url);
  2076. var mediaAnchor = mediaContainer.find(".embeddedImgAnchor");
  2077. mediaAnchor.attr("href", mediaInfo.url);
  2078. mediaAnchor.attr("data-backup-href", mediaInfo.url);
  2079. }
  2080. }
  2081. function addEvents(media) {
  2082. var mediaTyping = getMediaTyping(media);
  2083. if (media.hasClass("embeddedImg") && mediaTyping.type == "image")
  2084. {
  2085. media.error(function() {
  2086. errorEvent(media);
  2087. });
  2088. }
  2089. else if (media.hasClass("embeddedImg") && mediaTyping.type == "video")
  2090. {
  2091. /*Assigning events to videos via jquery doesn't work*/
  2092. media[0].addEventListener('error', function(event) {
  2093. errorEvent(media);
  2094. }, true);
  2095. }
  2096. }
  2097. /*
  2098. Handle case where media cannot be loaded.
  2099. Param:
  2100. media :: embeddedImg or embeddedImgContainer
  2101. */
  2102. function errorEvent(media, errMsg="Media cannot be loaded")
  2103. {
  2104. var embeddedImgContainer = getEmbeddedImgContainer(media);
  2105. var embeddedImgAnchor = embeddedImgContainer.find(".embeddedImgAnchor");
  2106. var mediaResolutionSpan = getWidget("imgResolution", embeddedImgContainer);
  2107. var mediaFilesizeSpan = getWidget("imgFilesize", embeddedImgContainer);
  2108. embeddedImgAnchor.html(errMsg);
  2109. mediaResolutionSpan.html("");
  2110. mediaFilesizeSpan.html("");
  2111. }
  2112. function addStyling(media, styles) {
  2113. var mediaTyping = getMediaTyping(media);
  2114. if (media.hasClass("embeddedImg") && mediaTyping.type.match(/video|image|iframe/i))
  2115. {
  2116. media.css(styles);
  2117. }
  2118. else if (media.hasClass("floatingImg"))
  2119. {
  2120. styles["position"] = "absolute";
  2121. styles["z-index"] = 100;
  2122. media.css(styles);
  2123. }
  2124. }
  2125. /*
  2126. Get the natural width of an embedded image.
  2127. @image :: jQuery object with the class "embeddedImg"
  2128. */
  2129. function getNatWidthOfEmbeddedImg(image)
  2130. {
  2131. var mediaTyping = getMediaTyping(image);
  2132. if (mediaTyping.type == "video")
  2133. {
  2134. return image[0].videoWidth;
  2135. }
  2136. else if (mediaTyping.type == "image")
  2137. {
  2138. return image[0].naturalWidth;
  2139. }
  2140. }
  2141. /*
  2142. Get the natural width of an embedded image.
  2143. @image :: jQuery object with the class "embeddedImg"
  2144. */
  2145. function getNatHeightOfEmbeddedImg(image)
  2146. {
  2147. var mediaTyping = getMediaTyping(image);
  2148. if (mediaTyping.type == "video")
  2149. {
  2150. return image[0].videoHeight;
  2151. }
  2152. else if (mediaTyping.type == "image")
  2153. {
  2154. return image[0].naturalHeight;
  2155. }
  2156. }
  2157. var isShowSome;
  2158. async.some(isShow, function(val, cb){
  2159. cb(null, val);
  2160. }, function results(err, results) {
  2161. isShowSome = results;
  2162. });
  2163. if (isShowSome)
  2164. {
  2165. $("body").append(
  2166. "<div class='imgMenuButton' style='display: none'>" +
  2167. "<div class='imgMenuButton_symbol'>" +
  2168. "+" +
  2169. "</div>" +
  2170. "</div>"
  2171. );
  2172. }
  2173. var imgMenuButton = $("body div.imgMenuButton");
  2174. /*
  2175. Show a transparent button in the top-right corner of a thumbnail image.
  2176. @param thumbnail :: embedded thumbnail image
  2177. @param isAppear :: true if the button should appear
  2178. */
  2179. function showImgMenuButton(thumbnail, isAppear)
  2180. {
  2181. if (imgMenuButton.length == 0)
  2182. return false;
  2183. if (isAppear)
  2184. {
  2185. if (imgMenu !== null &&
  2186. getEmbeddedImgContainer(thumbnail).attr("data-idx") === imgMenu.attr("data-idx"))
  2187. {
  2188. imgMenuButton.children().html("-");
  2189. }
  2190. else
  2191. {
  2192. imgMenuButton.children().html("+");
  2193. }
  2194. imgMenuButton.css("display", "table");
  2195. imgMenuButton.css("left", (thumbnail.offset().left + thumbnail.width() - 18) + "px");
  2196. imgMenuButton.css("top", thumbnail.offset().top - 1 + "px");
  2197. imgMenuButton.css("width", imgMenuButton.height());
  2198. }
  2199. else
  2200. {
  2201. imgMenuButton.css("display", "none");
  2202. }
  2203. }
  2204. function isHoverOverImgMenuButton(event)
  2205. {
  2206. if (imgMenuButton.length == 0)
  2207. return false;
  2208. var isCursorInButton =
  2209. imgMenuButton.css("display") === "table" &&
  2210. isHovered(imgMenuButton, event);
  2211. return isCursorInButton;
  2212. }
  2213. var imgMenu = null; // can be undefined instead of null
  2214. function showImgMenu(image)
  2215. {
  2216. if (imgMenu != null) { // check both null and undefined
  2217. imgMenu.remove();
  2218. }
  2219. var idx = getEmbeddedImgContainer(image).attr('data-idx');
  2220. imgMenu = $("<div class='imgMenu' data-idx='"+idx+"' style='display: none; position: absolute; z-index: 90;'>" +
  2221. "</div>").appendTo($("body"));
  2222. addDefaultWidgets(imgMenu);
  2223. /*Handle filesize, resolution, and displaying imgMenu*/
  2224. var imgFilesizeSpan = getWidget("imgFilesize", imgMenu);
  2225. var imgResolutionSpan = getWidget("imgResolution", imgMenu);
  2226. var imgURL = image.parent().attr("data-backup-href");
  2227. if (isShow['filesizeSpan'])
  2228. getMediaSize(image, imgFilesizeSpan);
  2229. if (isShow['resolutionSpan'])
  2230. getMediaResolution(image, imgResolutionSpan);
  2231. var img_rightOffset = image.offset().left + image.width();
  2232. var imgMenu_rightOffset = img_rightOffset + imgMenu.width();
  2233. /*if imgMenu right offset exceeds beyond window's right offset*/
  2234. if (imgMenu_rightOffset > $(window).scrollLeft() + $(window).width())
  2235. imgMenu.css("left", ($(window).scrollLeft() + $(window).width() - imgMenu.width()) + "px");
  2236. else
  2237. imgMenu.css("left", img_rightOffset + "px");
  2238. imgMenu.css("top", image.offset().top + "px");
  2239. imgMenu.css("display", "inline");
  2240. imgMenuButton.children().html("-");
  2241. }
  2242. function hideImgMenu()
  2243. {
  2244. if (imgMenu !== undefined && imgMenu !== null)
  2245. {
  2246. imgMenu.remove();
  2247. imgMenu = null;
  2248. }
  2249. }
  2250. function getImageAnchorOfImgMenu()
  2251. {
  2252. var imgIdx = $("body > .imgMenu").attr("data-idx");
  2253. return $(".embeddedImgContainer[data-idx='"+imgIdx+"']").find(".embeddedImgAnchor");
  2254. }
  2255. function isHovered(jQueryObj, event)
  2256. {
  2257. //return !!$(jQueryObj).filter(function() { return $(this).is(":hover"); }).length;
  2258. return (
  2259. event.pageX > jQueryObj.offset().left &&
  2260. event.pageX < jQueryObj.offset().left + jQueryObj.width() &&
  2261. event.pageY > jQueryObj.offset().top &&
  2262. event.pageY < jQueryObj.offset().top + jQueryObj.height()
  2263. );
  2264. }
  2265. function getHoveredThumbnail(event)
  2266. {
  2267. var hoveredMedia = undefined;
  2268. async.each(embeddedImgContainers, function(embeddedImgContainer, cb) {
  2269. var media = embeddedImgContainer.find(".embeddedImg.thumbnailImg");
  2270. if (media.length > 0 && isHovered(media, event))
  2271. {
  2272. hoveredMedia = media;
  2273. }
  2274. cb();
  2275. });
  2276. return hoveredMedia;
  2277. }
  2278. $(document).on("click", function(event) {
  2279. if (imgMenu)
  2280. {
  2281. var widgets = imgMenu.find(".widget");
  2282. widgets = $.makeArray(widgets);
  2283. var isHoveredSomeWidget = false;
  2284. async.some(widgets, function(widget, cb){
  2285. cb(null, isHovered($(widget), event));
  2286. }, function results(err, result){
  2287. isHoveredSomeWidget = result;
  2288. });
  2289. var isHoveredImgMenu = isHovered(imgMenu, event);
  2290. if (! isHoveredImgMenu || isHoveredSomeWidget) {
  2291. hideImgMenu();
  2292. }
  2293. }
  2294. });
  2295. function handleFloatingImage(event)
  2296. {
  2297. if (!enable_floatingImg)
  2298. return;
  2299. const floatingImgCSS = {
  2300. "left": undefined,
  2301. "top": undefined,
  2302. "max-width": undefined,
  2303. "max-height": undefined,
  2304. };
  2305. /*if user is hovering over thumbnail*/
  2306. if (currentHoveredThumbnail !== null)
  2307. {
  2308. /*calculate floating image size and position*/
  2309. floatingImgCSS["max-width"] = parseInt(getNatWidthOfEmbeddedImg(currentHoveredThumbnail));
  2310. floatingImgCSS["left"] = event.pageX + floatingImgRightOffset;
  2311. /*if right of image exceeds beyond right of window, restrict max width*/
  2312. if (floatingImgCSS["left"] + floatingImgCSS["max-width"] > $(window).scrollLeft() + $(window).width() - floatingImgBorder)
  2313. {
  2314. floatingImgCSS["max-width"] = $(window).scrollLeft() + $(window).width() - floatingImgBorder - floatingImgCSS["left"];
  2315. }
  2316. if (floatingImgCSS["max-width"] < 0)
  2317. floatingImgCSS["max-width"] = 0;
  2318. floatingImgCSS["max-height"] = Math.round(getNatHeightOfEmbeddedImg(currentHoveredThumbnail) * (floatingImgCSS["max-width"] / getNatWidthOfEmbeddedImg(currentHoveredThumbnail)));
  2319. floatingImgCSS["top"] = event.pageY - (floatingImgCSS["max-height"] / 2);
  2320. /*if bottom of image exceeds beyond the window, shift top upwards*/
  2321. if (floatingImgCSS["top"] + floatingImgCSS["max-height"] > $(window).scrollTop() + $(window).height() - floatingImgBorder)
  2322. {
  2323. floatingImgCSS["top"] = $(window).scrollTop() + $(window).height() - floatingImgBorder - floatingImgCSS["max-height"];
  2324. }
  2325. /*if top of image expands beyond top of window, lower top of image*/
  2326. if (floatingImgCSS["top"] < $(window).scrollTop() + floatingImgBorder)
  2327. {
  2328. floatingImgCSS["top"] = $(window).scrollTop() + floatingImgBorder;
  2329. }
  2330. /*if bottom of image exceeds beyond the window, restrict max height*/
  2331. if (floatingImgCSS["top"] + floatingImgCSS["max-height"] > $(window).scrollTop() + $(window).height() - floatingImgBorder)
  2332. {
  2333. floatingImgCSS["max-height"] = $(window).scrollTop() + $(window).height() - floatingImgBorder - floatingImgCSS["top"];
  2334. }
  2335. async.eachOf(floatingImgCSS, function(val, key, cb) {
  2336. floatingImgCSS[key] = floatingImgCSS[key] + "px";
  2337. cb();
  2338. });
  2339. /* If floating image and current hovered thumbnail isn't the same,
  2340. cut off previous reference to indicate a new floating image
  2341. */
  2342. if (curFloatingImg !== null &&
  2343. getMediaURL(curFloatingImg) != getMediaURL(currentHoveredThumbnail))
  2344. {
  2345. showImgMenuButton(null, false);
  2346. curFloatingImg.remove();
  2347. curFloatingImg = null;
  2348. }
  2349. /*if floating image doesn't exist or doesn't have an image yet...*/
  2350. if (curFloatingImg === null)
  2351. {
  2352. const mediaTyping = getMediaTyping(currentHoveredThumbnail);
  2353. const mediaURL = getMediaURL(currentHoveredThumbnail);
  2354. const mediaStr = createEmbeddedMediaStr({src: mediaURL, isFloatingImg: true});
  2355. /*create the floating image element*/
  2356. $("body").append(mediaStr);
  2357. curFloatingImg = $("body").children(".floatingImg");
  2358. bypassHotlink(curFloatingImg);
  2359. /*bug fix: need to be refreshed if curFloatingImg outdated*/
  2360. curFloatingImg.embeddedImgRef = currentHoveredThumbnail;
  2361. /*if webm video*/
  2362. if (mediaTyping.type == "video")
  2363. {
  2364. curFloatingImg[0].play();
  2365. curFloatingImg.prop("loop", true);
  2366. curFloatingImg.prop('muted', false);
  2367. }
  2368. if (getEmbeddedImgContainer(currentHoveredThumbnail).attr('data-style') == "sideBySide")
  2369. showImgMenuButton(currentHoveredThumbnail, true);
  2370. }
  2371. addStyling(curFloatingImg, floatingImgCSS);
  2372. curFloatingImg.attr("display", "");
  2373. }
  2374. /*if user is not hovering over thumbnail and floating image still exists*/
  2375. else if (currentHoveredThumbnail === null && curFloatingImg !== null)
  2376. {
  2377. showImgMenuButton(null, false);
  2378. curFloatingImg.remove();
  2379. curFloatingImg = null;
  2380. }
  2381. }
  2382. var curFloatingImg = null;
  2383. // For URL hover
  2384. var selectedContainer = null;
  2385. var isContinueWaitingForImageFromURLHover = false;
  2386. var savedEvent = null;
  2387. /*if cursor is hovering inside a thumbnail image, display expanded image as floating div
  2388. Also show a transparent button to expand the image menu (side-by-side image view only)
  2389. */
  2390. $(document).on("mousemove", function(event) {
  2391. handleFloatingImage(event);
  2392. });
  2393. /*if mouse hovers inside the image, show floating image*/
  2394. $(document).on("mouseover", ".embeddedImg", function(event){
  2395. $("html").css("cursor", "pointer");
  2396. isContinueWaitingForImageFromURLHover = false;
  2397. if (! $(this).hasClass("expandedImg"))
  2398. {
  2399. currentHoveredThumbnail = $(event.target);
  2400. handleFloatingImage(event);
  2401. }
  2402. });
  2403. /*if mouse hovers outside the image, hide floating image*/
  2404. $(document).on("mouseout", ".embeddedImg", function(event){
  2405. $("html").css("cursor", "default");
  2406. isContinueWaitingForImageFromURLHover = false;
  2407. currentHoveredThumbnail = null;
  2408. handleFloatingImage(event);
  2409. });
  2410. // img ok but width undefined
  2411. function waitUntilCanShowFloatingImage() {
  2412. if (!isContinueWaitingForImageFromURLHover) {
  2413. return;
  2414. }
  2415. if (!selectedContainer.hasClass("loaded")) {
  2416. setTimeout(waitUntilCanShowFloatingImage, 100);
  2417. return;
  2418. }
  2419. const img = selectedContainer.find(".embeddedImg");
  2420. const imgWidth = getNatWidthOfEmbeddedImg(img);
  2421. if (img.length == 0 || imgWidth == 0) {
  2422. setTimeout(waitUntilCanShowFloatingImage, 100);
  2423. }
  2424. else {
  2425. isContinueWaitingForImageFromURLHover = false;
  2426. selectedContainer = null;
  2427. currentHoveredThumbnail = img;
  2428. handleFloatingImage(savedEvent);
  2429. }
  2430. }
  2431. /*if mouse hovers inside the image URL, show floating image*/
  2432. $(document).on("mouseover", ".imgURL", function(event){
  2433. if (!enable_floatingImg_url)
  2434. return false;
  2435. selectedContainer = getEmbeddedImgContainer($(this));
  2436. const img = selectedContainer.find(".embeddedImg");
  2437. if (img.length == 0) {
  2438. showMedia(selectedContainer, false);
  2439. hideMedia(selectedContainer, false);
  2440. }
  2441. isContinueWaitingForImageFromURLHover = true;
  2442. savedEvent = event;
  2443. setTimeout(waitUntilCanShowFloatingImage, 1);
  2444. });
  2445. /*if mouse hovers outside the image URL, restore cursor to default graphic*/
  2446. $(document).on("mouseout", ".imgURL.widget", function(event){
  2447. if (!enable_floatingImg_url)
  2448. return false;
  2449. isContinueWaitingForImageFromURLHover = false;
  2450. currentHoveredThumbnail = null;
  2451. handleFloatingImage(event);
  2452. });
  2453. /*if clicked on the image URL anchor that's surrounding the embedded image, prevent default
  2454. behaviour of anchor (e.g. don't click on hyperlink when expanding image), unless it's a middle click
  2455. FIREFOX: mouseup,mousedown rather than click is only recognized for middle click.
  2456. */
  2457. $("body").on("mouseup mousedown click", ".embeddedImgAnchor", function(event){
  2458. /*left-click*/
  2459. if (event.which === 1)
  2460. {
  2461. event.preventDefault();
  2462. }
  2463. /*middle-click*/
  2464. else if (event.which === 2)
  2465. {
  2466. }
  2467. });
  2468. /* jshint -W107 */
  2469. /*toggle image size on left-click*/
  2470. $("body").on("click", ".embeddedImg", function(event){
  2471. /*left-click*/
  2472. if (event.which === 1)
  2473. {
  2474. if (isHoverOverImgMenuButton(event) && imgMenu === null)
  2475. {
  2476. event.stopImmediatePropagation();
  2477. event.preventDefault();
  2478. showImgMenu($(this));
  2479. return false;
  2480. }
  2481. else if (isHoverOverImgMenuButton(event) && imgMenu !== null)
  2482. {
  2483. /*if referring to same thumbnail*/
  2484. if (imgMenu.attr("data-idx") === getEmbeddedImgContainer($(this)).attr("data-idx"))
  2485. {
  2486. hideImgMenu();
  2487. }
  2488. else
  2489. {
  2490. showImgMenu($(this));
  2491. }
  2492. showImgMenuButton($(this), true);
  2493. return false;
  2494. }
  2495. else if (imgMenu !== null)
  2496. {
  2497. hideImgMenu();
  2498. }
  2499. showImgMenuButton($(this), false);
  2500. toggleEmbeddedImgSize($(this), false);
  2501. const embeddedImgContainer = getEmbeddedImgContainer($(this));
  2502. /*If shrunk image and still hovering over thumbnail*/
  2503. if ($(this).hasClass("thumbnailImg"))
  2504. {
  2505. const hoveredThumbnail = getHoveredThumbnail(event);
  2506. if (hoveredThumbnail)
  2507. {
  2508. if (getEmbeddedImgContainer(hoveredThumbnail).attr('data-style') == "sideBySide")
  2509. {
  2510. showImgMenuButton(hoveredThumbnail, true);
  2511. }
  2512. currentHoveredThumbnail = hoveredThumbnail;
  2513. handleFloatingImage(event);
  2514. }
  2515. }
  2516. if (autoScrollWhenThumbnailClicked)
  2517. $(window).scrollTop( embeddedImgContainer.offset().top );
  2518. return false;
  2519. }
  2520. });
  2521. /*
  2522. @param isAll :: true if your intention is to expand/shrink all images
  2523. */
  2524. function toggleEmbeddedImgSize(embeddedImg, isAll)
  2525. {
  2526. const embeddedImgContainer = embeddedImg.closest(".embeddedImgContainer");
  2527. const embeddedImgAnchor = embeddedImg.closest(".embeddedImgAnchor");
  2528. const isSig = embeddedImgContainer.hasClass("withinSig");
  2529. const mediaTyping = getMediaTyping(embeddedImg);
  2530. const thumbnailImgWidth_this = isSig ? thumbnailImgWidthSig : thumbnailImgWidth;
  2531. const thumbnailImgHeight_this = isSig ? thumbnailImgHeightSig : thumbnailImgHeight;
  2532. const thumbnailImgWidth_this_css = thumbnailImgWidth_this === 0 ? "" : thumbnailImgWidth_this+"px";
  2533. const thumbnailImgHeight_this_css = thumbnailImgHeight_this === 0 ? "" : thumbnailImgHeight_this+"px";
  2534. /*When resizing all media, don't affect sigs if set*/
  2535. if (!includeSigWhenExpanding && embeddedImg.hasClass("withinSig") && isAll)
  2536. {
  2537. return;
  2538. }
  2539. else
  2540. {
  2541. embeddedImg.toggleClass("thumbnailImg expandedImg");
  2542. }
  2543. toggleMediaCloseButton(embeddedImgContainer);
  2544. /*if going to expand image*/
  2545. if (embeddedImg.hasClass("expandedImg"))
  2546. {
  2547. $("#floatingImg").remove();
  2548. embeddedImg.css("max-width", getOptimalImgMaxWidth_css(embeddedImg, expandedImgWidth));
  2549. embeddedImg.css("max-height", expandedImgHeight_css);
  2550. /*if video file, start playing it*/
  2551. if (mediaTyping.type == "video")
  2552. {
  2553. embeddedImg[0].play();
  2554. embeddedImg.prop("controls", true); /*add controls*/
  2555. embeddedImg.prop('muted', false); /*unmute*/
  2556. if (loopExpandedVideo)
  2557. embeddedImg.attr("loop", "");
  2558. /* Prevent URL anchor from doing anything when expanded video is clicked on */
  2559. /* See also: Below case and on.click for .embeddedImgAnchor */
  2560. if (isFirefox)
  2561. embeddedImgAnchor.removeAttr("href");
  2562. }
  2563. }
  2564. else /*if shrinking image back to thumbnail*/
  2565. {
  2566. embeddedImg.css("max-width", getOptimalImgMaxWidth_css(embeddedImg, thumbnailImgWidth_this));
  2567. embeddedImg.css("max-height", thumbnailImgHeight_this_css);
  2568. /*if video file, stop playing it unless specified otherwise*/
  2569. if (mediaTyping.type == "video")
  2570. {
  2571. if (!loopThumbnailVideo)
  2572. embeddedImg[0].pause();
  2573. embeddedImg.prop("controls", false);
  2574. embeddedImg.prop("muted", true);
  2575. /* Restore URL anchor functionality */
  2576. if (isFirefox) {
  2577. const url = embeddedImgAnchor.attr("data-backup-href");
  2578. embeddedImgAnchor.attr("href", url);
  2579. }
  2580. }
  2581. }
  2582. currentHoveredThumbnail = null;
  2583. handleFloatingImage(null);
  2584. }
  2585. /*
  2586. Get the optimal max-width for an image.
  2587. The width will be one of the following:
  2588. - until the right of the browser windows border
  2589. - until the right of the parent container of the image container
  2590. - until the user-defined width limit
  2591. The smallest of the 3 will be chosen.
  2592. @param embeddedImg :: jQuery object of the image
  2593. @param userDefinedWidthLimit :: use 0 if no limit
  2594. The returned width will be the smaller of the three.
  2595. */
  2596. function getOptimalImgMaxWidth_css(embeddedImg, userDefinedWidthLimit)
  2597. {
  2598. let rv;
  2599. let optimalWidth;
  2600. let toContainerWidth;
  2601. let toWindowWidth;
  2602. if (userDefinedWidthLimit === undefined)
  2603. userDefinedWidthLimit = 0;
  2604. toContainerWidth =
  2605. embeddedImg.closest(".msg_body, blockquote").width(); /*gfaqsdep*/
  2606. toWindowWidth =
  2607. $(window).width() - embeddedImg.closest(".msg_body, blockquote").offset().left; /*gfaqsdep*/
  2608. if (toContainerWidth > toWindowWidth)
  2609. optimalWidth = toWindowWidth;
  2610. else
  2611. optimalWidth = toContainerWidth;
  2612. optimalWidth = Number(optimalWidth);
  2613. userDefinedWidthLimit = Number(userDefinedWidthLimit);
  2614. /*if no user-defined limit on the width*/
  2615. if (userDefinedWidthLimit === 0)
  2616. {
  2617. rv = optimalWidth;
  2618. }
  2619. else
  2620. {
  2621. if (optimalWidth > userDefinedWidthLimit)
  2622. rv = userDefinedWidthLimit;
  2623. else
  2624. rv = optimalWidth;
  2625. }
  2626. return rv === 0 ? "" : rv + "px";
  2627. }
  2628. function toggleSizesOfImages(embeddedImages, isExpanding) {
  2629. embeddedImages.each(function(index, element) {
  2630. if ($(this).closest(".embeddedImgContainer").hasClass("hiddenx")) {
  2631. return false;
  2632. }
  2633. if (isExpanding && $(this).hasClass("expandedImg"))
  2634. {
  2635. /*update its max-width*/
  2636. $(this).css("max-width", getOptimalImgMaxWidth_css($(this)));
  2637. }
  2638. else
  2639. {
  2640. toggleEmbeddedImgSize($(this), true);
  2641. }
  2642. });
  2643. }
  2644. function toggleMediaCloseButton(embeddedMediaContainer)
  2645. {
  2646. if (! hasWidget("closeMediaButton", embeddedMediaContainer))
  2647. {
  2648. const url = embeddedMediaContainer.find('.embeddedImgAnchor').attr('data-backup-href');
  2649. const mediaTyping = getMediaTyping(url);
  2650. if (mediaTyping && mediaTyping.type == "video")
  2651. {
  2652. const closeMediaButtonStr = getPredefinedWidgetStr("closeMediaButton");
  2653. setWidget(closeMediaButtonStr, embeddedMediaContainer);
  2654. }
  2655. }
  2656. else
  2657. {
  2658. /*remove widget*/
  2659. setWidget(null, embeddedMediaContainer, "closeMediaButton");
  2660. }
  2661. }
  2662. $("body").on("click", ".imgCloseAll", function(event) {
  2663. event.preventDefault();
  2664. toggleSizesOfImages($(".embeddedImg.expandedImg"), false);
  2665. nextImageSize = "expanded";
  2666. if (autoScrollWhenThumbnailClicked)
  2667. $(window).scrollTop( getEmbeddedImgContainer($(this)).offset().top );
  2668. if (imgMenu)
  2669. hideImgMenu();
  2670. });
  2671. $("body").on("click", ".imgClosePost", function(event) {
  2672. event.preventDefault();
  2673. const embeddedImgContainer = getEmbeddedImgContainer($(this));
  2674. const postID = embeddedImgContainer.attr("data-postID");
  2675. const postMedia = $(".embeddedImgContainer[data-postID="+postID+"]").find(".embeddedImg.expandedImg");
  2676. toggleSizesOfImages(postMedia, false);
  2677. if (autoScrollWhenThumbnailClicked)
  2678. $(window).scrollTop( embeddedImgContainer.offset().top );
  2679. if (imgMenu)
  2680. hideImgMenu();
  2681. });
  2682. $("body").on("click", ".imgExpandPost", function(event) {
  2683. event.preventDefault();
  2684. const embeddedImgContainer = getEmbeddedImgContainer($(this));
  2685. const postID = embeddedImgContainer.attr("data-postID");
  2686. const postMedia = $(".embeddedImgContainer[data-postID="+postID+"]").find(".embeddedImg");
  2687. toggleSizesOfImages(postMedia, true);
  2688. if (autoScrollWhenThumbnailClicked)
  2689. $(window).scrollTop( embeddedImgContainer.offset().top );
  2690. if (imgMenu)
  2691. hideImgMenu();
  2692. });
  2693. $("body").on("click", ".imgExpandAll", function(event) {
  2694. event.preventDefault();
  2695. toggleSizesOfImages($(".embeddedImg"), true);
  2696. nextImageSize = "thumbnail";
  2697. if (autoScrollWhenThumbnailClicked)
  2698. $(window).scrollTop( getEmbeddedImgContainer($(this)).offset().top );
  2699. if (imgMenu)
  2700. hideImgMenu();
  2701. });
  2702. $("body").on("click", ".imgBlacklistToggle", function(event) {
  2703. event.preventDefault();
  2704. let imgURL;
  2705. let imgAnchor;
  2706. /*Get embeddedImgContainer and anchor*/
  2707. imgAnchor = getEmbeddedImgContainer($(this)).find('.embeddedImgAnchor');
  2708. imgURL = getMediaURL($(this));
  2709. /*if image isn't blacklisted (but going to blacklist)*/
  2710. if (! imgAnchor.hasClass("blacklisted"))
  2711. {
  2712. /*for every embedded image anchor*/
  2713. async.each(embeddedImgContainers, function(curContainer, cb) {
  2714. let curURL = getMediaURL(curContainer);
  2715. /*if has URL that was just blacklisted, hide it*/
  2716. if (isURLmatchBlacklistedURL(imgURL, curURL))
  2717. {
  2718. hideMedia(curContainer, true);
  2719. }
  2720. cb();
  2721. });
  2722. }
  2723. else /*if image is blacklisted (but going to whitelist)*/
  2724. {
  2725. /*for every embedded image anchor*/
  2726. async.each(embeddedImgContainers, function(curContainer, cb) {
  2727. let curURL = getMediaURL(curContainer);
  2728. /*if has URL that was just whitelisted, show it*/
  2729. if (curURL === imgURL)
  2730. {
  2731. showMedia(curContainer, true);
  2732. }
  2733. cb();
  2734. });
  2735. }
  2736. if (imgMenu)
  2737. hideImgMenu();
  2738. });
  2739. $("body").on("click", "a.imgHideToggle", function(event) {
  2740. event.preventDefault();
  2741. const embeddedImgContainer = getEmbeddedImgContainer($(this));
  2742. /*if image is going to be hidden*/
  2743. if ($(this).html() === "hide")
  2744. {
  2745. hideMedia(embeddedImgContainer, false);
  2746. }
  2747. else /*if image is going to be shown*/
  2748. {
  2749. showMedia(embeddedImgContainer, false);
  2750. }
  2751. if (imgMenu)
  2752. hideImgMenu();
  2753. });
  2754. $("body").on("click", "a.imgHideAll", function(event) {
  2755. event.preventDefault();
  2756. toggleImageVisiblity($(".embeddedImgContainer"), "closeAnchor");
  2757. if (autoScrollWhenThumbnailClicked)
  2758. $(window).scrollTop( getEmbeddedImgContainer($(this)).offset().top );
  2759. if (imgMenu)
  2760. hideImgMenu();
  2761. });
  2762. $("body").on("click", "a.imgHidePost", function(event) {
  2763. event.preventDefault();
  2764. const embeddedImgContainer = getEmbeddedImgContainer($(this));
  2765. const postID = embeddedImgContainer.attr("data-postID");
  2766. const postEmbeddedImgContainers = $(".embeddedImgContainer[data-postID="+postID+"]");
  2767. toggleImageVisiblity(postEmbeddedImgContainers, "closeAnchor");
  2768. if (autoScrollWhenThumbnailClicked)
  2769. $(window).scrollTop( embeddedImgContainer.offset().top );
  2770. if (imgMenu)
  2771. hideImgMenu();
  2772. });
  2773. $("body").on("click", "a.imgShowPost", function(event) {
  2774. event.preventDefault();
  2775. const embeddedImgContainer = getEmbeddedImgContainer($(this));
  2776. const postID = embeddedImgContainer.attr("data-postID");
  2777. const postEmbeddedImgContainers = $(".embeddedImgContainer[data-postID="+postID+"]");
  2778. toggleImageVisiblity(postEmbeddedImgContainers, "showAnchor");
  2779. if (autoScrollWhenThumbnailClicked)
  2780. $(window).scrollTop( embeddedImgContainer.offset().top );
  2781. if (imgMenu)
  2782. hideImgMenu();
  2783. });
  2784. $("body").on("click", "a.imgShowAll", function(event) {
  2785. event.preventDefault();
  2786. toggleImageVisiblity($(".embeddedImgContainer"), "showAnchor");
  2787. if (autoScrollWhenThumbnailClicked)
  2788. $(window).scrollTop( getEmbeddedImgContainer($(this)).offset().top );
  2789. if (imgMenu)
  2790. hideImgMenu();
  2791. });
  2792. $("body").on("click", "a.closeMediaButton", function(event) {
  2793. event.preventDefault();
  2794. const embeddedMediaContainer = getEmbeddedImgContainer($(this));
  2795. const embeddedImg = embeddedMediaContainer.find(".embeddedImg");
  2796. toggleEmbeddedImgSize(embeddedImg, false);
  2797. if (autoScrollWhenThumbnailClicked)
  2798. $(window).scrollTop( embeddedMediaContainer.offset().top );
  2799. });
  2800.  
  2801. }, 1);