IG小助手

一键下载对方 Instagram 帖子中的相片、视频甚至是他们的快拍、Reels及头像图片!

当前为 2025-02-11 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name IG Helper
  3. // @name:zh-TW IG小精靈
  4. // @name:zh-CN IG小助手
  5. // @name:ja IG助手
  6. // @name:ko IG조수
  7. // @namespace https://github.snkms.com/
  8. // @version 2.43.4
  9. // @description Downloading is possible for both photos and videos from posts, as well as for stories, reels or profile picture.
  10. // @description:zh-TW 一鍵下載對方 Instagram 貼文中的相片、影片甚至是他們的限時動態、連續短片及大頭貼圖片!
  11. // @description:zh-CN 一键下载对方 Instagram 帖子中的相片、视频甚至是他们的快拍、Reels及头像图片!
  12. // @description:ja 投稿の写真と動画だけでなく、ストーリー、リール、プロフィール写真もダウンロードできます。
  13. // @description:ko 게시물의 사진과 동영상뿐만 아니라 스토리, 릴 또는 프로필 사진도 다운로드할 수 있습니다.
  14. // @description:ro Descărcarea este posibilă atât pentru fotografiile și videoclipurile din postări, cât și pentru storyuri, reels sau poze de profil.
  15. // @author SN-Koarashi (5026)
  16. // @match https://*.instagram.com/*
  17. // @grant GM_info
  18. // @grant GM_addStyle
  19. // @grant GM_setValue
  20. // @grant GM_getValue
  21. // @grant GM_xmlhttpRequest
  22. // @grant GM_registerMenuCommand
  23. // @grant GM_unregisterMenuCommand
  24. // @grant GM_getResourceText
  25. // @grant GM_notification
  26. // @grant GM_openInTab
  27. // @connect i.instagram.com
  28. // @connect raw.githubusercontent.com
  29. // @require https://code.jquery.com/jquery-3.7.1.min.js#sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=
  30. // @resource INTERNAL_CSS https://raw.githubusercontent.com/SN-Koarashi/ig-helper/master/style.css
  31. // @resource LOCALE_MANIFEST https://raw.githubusercontent.com/SN-Koarashi/ig-helper/master/locale/manifest.json
  32. // @supportURL https://github.com/SN-Koarashi/ig-helper/
  33. // @contributionURL https://ko-fi.com/snkoarashi
  34. // @icon https://www.google.com/s2/favicons?domain=www.instagram.com&sz=32
  35. // @compatible firefox >= 100
  36. // @compatible chrome >= 100
  37. // @compatible edge >= 100
  38. // @license GPL-3.0-only
  39. // @run-at document-idle
  40. // ==/UserScript==
  41.  
  42. (function ($) {
  43. 'use strict';
  44.  
  45. /******** USER SETTINGS ********/
  46. // !!! DO NOT CHANGE THIS AREA !!!
  47. // PLEASE CHANGE SETTING WITH MENU
  48. const USER_SETTING = {
  49. 'CHECK_UPDATE': true,
  50. 'AUTO_RENAME': true,
  51. 'RENAME_PUBLISH_DATE': true,
  52. 'DISABLE_VIDEO_LOOPING': false,
  53. 'HTML5_VIDEO_CONTROL': false,
  54. 'REDIRECT_CLICK_USER_STORY_PICTURE': false,
  55. 'FORCE_FETCH_ALL_RESOURCES': false,
  56. 'DIRECT_DOWNLOAD_VISIBLE_RESOURCE': false,
  57. 'DIRECT_DOWNLOAD_ALL': false,
  58. 'MODIFY_VIDEO_VOLUME': false,
  59. 'SCROLL_BUTTON': true,
  60. 'FORCE_RESOURCE_VIA_MEDIA': false,
  61. 'USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT': false,
  62. 'NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST': false,
  63. 'SKIP_VIEW_STORY_CONFIRM': false
  64. };
  65. const CHILD_NODES = ['RENAME_PUBLISH_DATE', 'USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT', 'NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST'];
  66. var VIDEO_VOLUME = (GM_getValue('G_VIDEO_VOLUME')) ? GM_getValue('G_VIDEO_VOLUME') : 1;
  67. var TEMP_FETCH_RATE_LIMIT = false;
  68. var RENAME_FORMAT = (GM_getValue('G_RENAME_FORMAT')) ? GM_getValue('G_RENAME_FORMAT') : '%USERNAME%-%SOURCE_TYPE%-%SHORTCODE%-%YEAR%%MONTH%%DAY%_%HOUR%%MINUTE%%SECOND%_%ORIGINAL_NAME_FIRST%';
  69. /*******************************/
  70.  
  71. // Icon download by https://www.flaticon.com/authors/pixel-perfect
  72. const SVG = {
  73. DOWNLOAD: '<svg width="16" height="16" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve"><g><g><path d="M382.56,233.376C379.968,227.648,374.272,224,368,224h-64V16c0-8.832-7.168-16-16-16h-64c-8.832,0-16,7.168-16,16v208h-64 c-6.272,0-11.968,3.68-14.56,9.376c-2.624,5.728-1.6,12.416,2.528,17.152l112,128c3.04,3.488,7.424,5.472,12.032,5.472 c4.608,0,8.992-2.016,12.032-5.472l112-128C384.192,245.824,385.152,239.104,382.56,233.376z"/></g></g><g><g><path d="M432,352v96H80v-96H16v128c0,17.696,14.336,32,32,32h416c17.696,0,32-14.304,32-32V352H432z"/></g></g>',
  74. NEW_TAB: '<svg width="16" height="16" viewBox="3 3 18 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M20 14a1 1 0 0 0-1 1v3.077c0 .459-.022.57-.082.684a.363.363 0 0 1-.157.157c-.113.06-.225.082-.684.082H5.923c-.459 0-.571-.022-.684-.082a.363.363 0 0 1-.157-.157c-.06-.113-.082-.225-.082-.684L4.999 5.5a.5.5 0 0 1 .5-.5l3.5.005a1 1 0 1 0 .002-2L5.501 3a2.5 2.5 0 0 0-2.502 2.5v12.577c0 .76.083 1.185.32 1.627.223.419.558.753.977.977.442.237.866.319 1.627.319h12.154c.76 0 1.185-.082 1.627-.319.419-.224.753-.558.977-.977.237-.442.319-.866.319-1.627V15a1 1 0 0 0-1-1zm-2-9.055v-.291l-.39.09A10 10 0 0 1 15.36 5H14a1 1 0 1 1 0-2l5.5.003a1.5 1.5 0 0 1 1.5 1.5V10a1 1 0 1 1-2 0V8.639c0-.757.086-1.511.256-2.249l.09-.39h-.295a10 10 0 0 1-1.411 1.775l-5.933 5.932a1 1 0 0 1-1.414-1.414l5.944-5.944A10 10 0 0 1 18 4.945z" fill="currentColor"/></svg>',
  75. THUMBNAIL: '<svg width="16" height="16" xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="512" viewBox="0 0 24 24" width="512"><circle cx="8.25" cy="5.25" r=".5"/><path d="m8.25 6.5c-.689 0-1.25-.561-1.25-1.25s.561-1.25 1.25-1.25 1.25.561 1.25 1.25-.561 1.25-1.25 1.25zm0-1.5c-.138 0-.25.112-.25.25 0 .275.5.275.5 0 0-.138-.112-.25-.25-.25z"/><path d="m7.25 11.25 2-2.5 2.25 1.5 2.25-3.5 3 4.5z"/><path d="m16.75 12h-9.5c-.288 0-.551-.165-.676-.425s-.09-.568.09-.793l2-2.5c.243-.304.678-.372 1.002-.156l1.616 1.077 1.837-2.859c.137-.212.372-.342.625-.344.246-.026.49.123.63.334l3 4.5c.153.23.168.526.037.77-.13.244-.385.396-.661.396zm-4.519-1.5h3.118l-1.587-2.381zm-3.42 0h1.712l-1.117-.745z"/><path d="m22.25 14h-2.756c-.778 0-1.452.501-1.676 1.247l-.859 2.862c-.16.533-.641.891-1.197.891h-7.524c-.556 0-1.037-.358-1.197-.891l-.859-2.861c-.224-.747-.897-1.248-1.676-1.248h-2.756c-.965 0-1.75.785-1.75 1.75v5.5c0 1.517 1.233 2.75 2.75 2.75h18.5c1.517 0 2.75-1.233 2.75-2.75v-5.5c0-.965-.785-1.75-1.75-1.75z"/><path d="m4 12c-.552 0-1-.448-1-1v-8c0-1.654 1.346-3 3-3h12c1.654 0 3 1.346 3 3v8c0 .552-.448 1-1 1s-1-.448-1-1v-8c0-.551-.449-1-1-1h-12c-.551 0-1 .449-1 1v8c0 .552-.448 1-1 1z"/></svg>',
  76. DOWNLOAD_ALL: '<svg width="16" height="16" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve"><g><g><path d="m191 208c-1-5-6-8-10-8l-42 0 0-184c0-8-5-15-11-15l-42 0c-6 0-11 7-11 15l0 184-42 0c-4 0-8 3-9 8c-2 6-1 12 1 16l74 105c2 3 5 5 8 5s6-2 8-5l74-105c2-4 4-9 2-16z"></g></g><g><g><path d="m486.3 208c-1-5-6-8-10-8l-42 0 0-184c0-8-5-15-11-15l-43 0c-6 0-11 7-11 15l0 184-41 0c-4 0-8 3-9 8c-2 6-1 12 1 16l74 105c2 3 5 5 8 5s6-2 8-5l74-105c2-4 4-9 2-16z"></g></g><g><g><path d="m342.3 299c-1-5-6-8-10-8l-42 0 0-275c0-8-5-15-11-15l-42 0c-6 0-11 7-11 15l0 275-42 0c-4 0-8 3-9 8c-2 6-1 12 1 16l74 105c2 3 5 5 8 5s6-2 8-5l74-105c2-4 4-9 2-16z"></g></g><g><g><path d="m422.79 380.79l0 74.12-338.83 0 0-74.12-67.34 0 0 89.45c0 23 14.73 40.89 33.67 40.89l408.28 0c18.94 0 33.67-17.89 33.67-40.89l0-89.45-69.45 0z"/></g></g></svg>',
  77. CLOSE: '<svg width="26" height="26" xmlns="http://www.w3.org/2000/svg" id="bold" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><path d="m14.828 12 5.303-5.303c.586-.586.586-1.536 0-2.121l-.707-.707c-.586-.586-1.536-.586-2.121 0l-5.303 5.303-5.303-5.304c-.586-.586-1.536-.586-2.121 0l-.708.707c-.586.586-.586 1.536 0 2.121l5.304 5.304-5.303 5.303c-.586.586-.586 1.536 0 2.121l.707.707c.586.586 1.536.586 2.121 0l5.303-5.303 5.303 5.303c.586.586 1.536.586 2.121 0l.707-.707c.586-.586.586-1.536 0-2.121z"></path></svg>'
  78. };
  79.  
  80. const checkInterval = 250;
  81. const style = GM_getResourceText("INTERNAL_CSS");
  82. const locale_manifest = JSON.parse(GM_getResourceText("LOCALE_MANIFEST"));
  83.  
  84. var GM_menuId = [];
  85. var locale = {};
  86. var lang = GM_getValue('lang') || navigator.language || navigator.userLanguage;
  87. var currentURL = location.href;
  88. var firstStarted = false;
  89. var pageLoaded = false;
  90.  
  91. var GL_registerEventList = [];
  92. var GL_logger = [];
  93. var GL_referrer;
  94. var GL_postPath;
  95. var GL_username;
  96. var GL_repeat;
  97. var GL_dataCache = {
  98. stories: {},
  99. highlights: {}
  100. };
  101. var GL_observer = new MutationObserver(function () {
  102. onReadyMyDW();
  103. });
  104.  
  105. initSettings();
  106. GM_addStyle(style);
  107. registerMenuCommand();
  108.  
  109. getTranslationText(lang).then((res) => {
  110. locale[lang] = res;
  111. repaintingTranslations();
  112. registerMenuCommand();
  113. checkingScriptUpdate(300);
  114. }).catch((err) => {
  115. registerMenuCommand();
  116. checkingScriptUpdate(300);
  117.  
  118. if (!lang.startsWith('en')) {
  119. console.error('getTranslationText catch error:', err);
  120. }
  121. });
  122.  
  123. // Main Timer
  124. // eslint-disable-next-line no-unused-vars
  125. var timer = setInterval(function () {
  126. // page loading or unnecessary route
  127. if ($('div#splash-screen').length > 0 && !$('div#splash-screen').is(':hidden') ||
  128. location.pathname.match(/^\/(explore(\/.*)?|challenge\/?.*|direct\/?.*|qr\/?|accounts\/.*|emails\/.*|language\/?.*?|your_activity\/?.*|settings\/help(\/.*)?$)$/ig) ||
  129. !location.hostname.startsWith('www.')
  130. ) {
  131. pageLoaded = false;
  132. return;
  133. }
  134.  
  135. if (currentURL != location.href || !firstStarted || !pageLoaded) {
  136. console.log('Main Timer', 'trigging');
  137.  
  138. clearInterval(GL_repeat);
  139. pageLoaded = false;
  140. firstStarted = true;
  141. currentURL = location.href;
  142. GL_observer.disconnect();
  143.  
  144. if (location.href.startsWith("https://www.instagram.com/p/") || location.pathname.match(/^\/(.*?)\/(p|reel)\//ig) || location.href.startsWith("https://www.instagram.com/reel/")) {
  145. GL_dataCache.stories = {};
  146. GL_dataCache.highlights = {};
  147.  
  148. logger('isDialog');
  149.  
  150. // This is a delayed function call that prevents the dialog element from appearing before the function is called.
  151. var dialogTimer = setInterval(() => {
  152. // body > div[id^="mount"] section nav + div > article << (mobile page in single post) >>
  153. // section:visible > main > div > div > div > div > div > hr << (single foreground post in page, non-floating // <hr> element here is literally the line beneath poster's username) >>
  154. // section:visible > main > div > div > article > div > div > div > div > div > header (is the same as above, except that this is on the route of the /{username}/p/{shortcode} structure)
  155. // section:visible > main > div > div.xdt5ytf << (former CSS selector for single foreground post in page, non-floating) >>
  156. // <hr> is much more unique element than "div.xdt5ytf"
  157. if ($(`body > div[class]:not([id^="mount"]) div div[role="dialog"] article,
  158. section:visible > main > div > div > div > div > div > hr,
  159. body > div[id^="mount"] section nav + div > article,
  160. section:visible > main > div > div > article > div > div > div > div > div > header
  161. `).length > 0) {
  162. clearInterval(dialogTimer);
  163.  
  164. // This is to prevent the detection of the "Modify Video Volume" setting from being too slow.
  165. setTimeout(() => {
  166. onReadyMyDW(false);
  167. }, 15);
  168. }
  169. }, 100);
  170.  
  171. pageLoaded = true;
  172. }
  173.  
  174. if (location.href.startsWith("https://www.instagram.com/reels/")) {
  175. logger('isReels');
  176. setTimeout(() => {
  177. onReels(false);
  178. }, 150);
  179. pageLoaded = true;
  180. }
  181.  
  182. if (location.href.split("?")[0] == "https://www.instagram.com/") {
  183. GL_dataCache.stories = {};
  184. GL_dataCache.highlights = {};
  185.  
  186. let hasReferrer = GL_referrer?.match(/^\/(stories|highlights)\//ig) != null;
  187.  
  188. logger('isHomepage', hasReferrer);
  189. setTimeout(() => {
  190. onReadyMyDW(false, hasReferrer);
  191.  
  192. const element = $('div[id^="mount"] > div > div div > section > main div:not([class]):not([style]) > div > article')?.parent()[0];
  193. if (element) {
  194. GL_observer.observe(element, {
  195. childList: true
  196. });
  197. }
  198. }, 150);
  199.  
  200. pageLoaded = true;
  201. }
  202. // eslint-disable-next-line no-useless-escape
  203. if ($('header > *[class]:first-child img[alt]').length && location.pathname.match(/^(\/)([0-9A-Za-z\.\-_]+)\/?(tagged|reels|saved)?\/?$/ig) && !location.pathname.match(/^(\/explore\/?$|\/stories(\/.*)?$|\/p\/)/ig)) {
  204. logger('isProfile');
  205. setTimeout(() => {
  206. onProfileAvatar(false);
  207. }, 150);
  208. pageLoaded = true;
  209. }
  210.  
  211. if (!pageLoaded) {
  212. // Call Instagram stories function
  213. if (location.href.match(/^(https:\/\/www\.instagram\.com\/stories\/highlights\/)/ig)) {
  214. GL_dataCache.highlights = {};
  215.  
  216. logger('isHighlightsStory');
  217.  
  218. onHighlightsStory(false);
  219. GL_repeat = setInterval(() => {
  220. onHighlightsStoryThumbnail(false);
  221. }, checkInterval);
  222.  
  223. if ($(".IG_DWHISTORY").length) {
  224. setTimeout(() => {
  225. if (USER_SETTING.SKIP_VIEW_STORY_CONFIRM) {
  226. var $viewStoryButton = $('div[id^="mount"] section:last-child > div > div div[role="button"]').filter(function () {
  227. return $(this).children().length === 0 && this.textContent.trim() !== "";
  228. });
  229. $viewStoryButton?.click();
  230. }
  231.  
  232. pageLoaded = true;
  233. }, 150);
  234. }
  235. }
  236. else if (location.href.match(/^(https:\/\/www\.instagram\.com\/stories\/)/ig)) {
  237. logger('isStory');
  238.  
  239. /*
  240. *
  241. * $('body div[id^="mount"] > div > div > div[class]').length >= 2 &&
  242. * $('body div[id^="mount"] > div > div > div[class]').last().find('svg > path[d^="M16.792"], svg > path[d^="M34.6 3.1c-4.5"]').length > 0 &&
  243. * $('body div[id^="mount"] > div > div > div[class]').last().find('svg > polyline + line').length > 0
  244. *
  245. */
  246. if ($('div[id^="mount"] section > div > a[href="/"]').length > 0) {
  247. $('.IG_DWSTORY').remove();
  248. $('.IG_DWNEWTAB').remove();
  249. if ($('.IG_DWSTORY_THUMBNAIL').length) {
  250. $('.IG_DWSTORY_THUMBNAIL').remove();
  251. }
  252.  
  253. onStory(false);
  254.  
  255. // Prevent buttons from being eaten by black holes sometimes
  256. setTimeout(() => {
  257. onStory(false);
  258. }, 150);
  259. }
  260.  
  261. if ($(".IG_DWSTORY").length) {
  262. setTimeout(() => {
  263. if (USER_SETTING.SKIP_VIEW_STORY_CONFIRM) {
  264. var $viewStoryButton = $('div[id^="mount"] section:last-child > div > div div[role="button"]').filter(function () {
  265. return $(this).children().length === 0 && this.textContent.trim() !== "";
  266. });
  267. $viewStoryButton?.click();
  268. }
  269.  
  270. pageLoaded = true;
  271. }, 150);
  272. }
  273. }
  274. else {
  275. pageLoaded = false;
  276. // Remove icons
  277. if ($('.IG_DWSTORY').length) {
  278. $('.IG_DWSTORY').remove();
  279. }
  280. if ($('.IG_DWSTORY_ALL').length) {
  281. $('.IG_DWSTORY_ALL').remove();
  282. }
  283. if ($('.IG_DWNEWTAB').length) {
  284. $('.IG_DWNEWTAB').remove();
  285. }
  286. if ($('.IG_DWSTORY_THUMBNAIL').length) {
  287. $('.IG_DWSTORY_THUMBNAIL').remove();
  288. }
  289.  
  290. if ($('.IG_DWHISTORY').length) {
  291. $('.IG_DWHISTORY').remove();
  292. }
  293. if ($('.IG_DWHISTORY_ALL').length) {
  294. $('.IG_DWHISTORY_ALL').remove();
  295. }
  296. if ($('.IG_DWHINEWTAB').length) {
  297. $('.IG_DWHINEWTAB').remove();
  298. }
  299. if ($('.IG_DWHISTORY_THUMBNAIL').length) {
  300. $('.IG_DWHISTORY_THUMBNAIL').remove();
  301. }
  302. }
  303. }
  304.  
  305. checkingScriptUpdate(300);
  306. GL_referrer = new URL(location.href).pathname;
  307. }
  308. }, checkInterval);
  309.  
  310. /**
  311. * onProfileAvatar
  312. * @description Trigger user avatar download event or button display event.
  313. *
  314. * @param {Boolean} isDownload - Check if it is a download operation
  315. * @return {void}
  316. */
  317. async function onProfileAvatar(isDownload) {
  318. if (isDownload) {
  319. updateLoadingBar(true);
  320.  
  321. let date = new Date().getTime();
  322. let timestamp = Math.floor(date / 1000);
  323. let username = location.pathname.replaceAll(/(reels|tagged)\/$/ig, '').split('/').filter(s => s.length > 0).at(-1);
  324. let userInfo = await getUserId(username);
  325.  
  326. try {
  327. let dataURL = await getUserHighSizeProfile(userInfo.user.pk);
  328. saveFiles(dataURL, username, "avatar", timestamp, 'jpg');
  329. }
  330. // eslint-disable-next-line no-unused-vars
  331. catch (err) {
  332. saveFiles(userInfo.user.profile_pic_url, username, "avatar", timestamp, 'jpg');
  333. }
  334.  
  335. updateLoadingBar(false);
  336. }
  337. else {
  338. // Add the profile download button
  339. if (!$('.IG_DWPROFILE').length) {
  340. let profileTimer = setInterval(() => {
  341. if ($('.IG_DWPROFILE').length) {
  342. clearInterval(profileTimer);
  343. return;
  344. }
  345.  
  346. $('header > *[class]:first-child img[alt][draggable]').parent().parent().append(`<div data-ih-locale-title="DW" title="${_i18n("DW")}" class="IG_DWPROFILE">${SVG.DOWNLOAD}</div>`);
  347. $('header > *[class]:first-child img[alt][draggable]').parent().parent().css('position', 'relative');
  348. $('header > *[class]:first-child img[alt]:not([draggable])').parent().parent().parent().append(`<div data-ih-locale-title="DW" title="${_i18n("DW")}" class="IG_DWPROFILE">${SVG.DOWNLOAD}</div>`);
  349. $('header > *[class]:first-child img[alt]:not([draggable])').parent().parent().parent().css('position', 'relative');
  350. }, 150);
  351. }
  352. }
  353. }
  354.  
  355. /**
  356. * onHighlightsStoryAll
  357. * @description Trigger user's highlight all download event.
  358. *
  359. * @return {void}
  360. */
  361. async function onHighlightsStoryAll() {
  362. updateLoadingBar(true);
  363.  
  364. let date = new Date().getTime();
  365. let timestamp = Math.floor(date / 1000);
  366. let highlightId = location.href.replace(/\/$/ig, '').split('/').at(-1);
  367. let highStories = await getHighlightStories(highlightId);
  368. let username = highStories.data.reels_media[0].owner.username;
  369.  
  370. let complete = 0;
  371. setDownloadProgress(complete, highStories.data.reels_media[0].items.length);
  372.  
  373. highStories.data.reels_media[0].items.forEach((item, idx) => {
  374. setTimeout(() => {
  375. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  376. timestamp = item.taken_at_timestamp;
  377. }
  378.  
  379. item.display_resources.sort(function (a, b) {
  380. if (a.config_width < b.config_width) return 1;
  381. if (a.config_width > b.config_width) return -1;
  382. return 0;
  383. });
  384.  
  385. if (item.is_video) {
  386. saveFiles(item.video_resources[0].src, username, "stories", timestamp, 'mp4', item.id).then(() => {
  387. setDownloadProgress(++complete, highStories.data.reels_media[0].items.length);
  388. });
  389. }
  390. else {
  391. saveFiles(item.display_resources[0].src, username, "stories", timestamp, 'jpg', item.id).then(() => {
  392. setDownloadProgress(++complete, highStories.data.reels_media[0].items.length);
  393. });
  394. }
  395. }, 100 * idx);
  396. });
  397. }
  398.  
  399. /**
  400. * onHighlightsStory
  401. * @description Trigger user's highlight download event or button display event.
  402. *
  403. * @param {Boolean} isDownload - Check if it is a download operation
  404. * @param {Boolean} isPreview - Check if it is need to open new tab
  405. * @return {void}
  406. */
  407. async function onHighlightsStory(isDownload, isPreview) {
  408. var username = $('body > div section:visible a[href^="/"]').filter(function () {
  409. return $(this).attr('href').split('/').filter(e => e.length > 0).length === 1
  410. }).first().attr('href').split('/').filter(e => e.length > 0).at(0);
  411.  
  412. if (isDownload) {
  413. let date = new Date().getTime();
  414. let timestamp = Math.floor(date / 1000);
  415. let highlightId = location.href.replace(/\/$/ig, '').split('/').at(-1);
  416. let nowIndex = $("body > div section._ac0a header._ac0k > ._ac3r ._ac3n ._ac3p[style]").length ||
  417. $('body > div section:visible > div > div:not([class]) > div > div div.x1ned7t2.x78zum5 div.x1caxmr6').length ||
  418. $('body > div div:not([hidden]) section:visible > div div[style]:not([class]) > div').find('div div.x1ned7t2.x78zum5 div.x1caxmr6').length;
  419. let target = 0;
  420.  
  421. updateLoadingBar(true);
  422.  
  423. if (GL_dataCache.highlights[highlightId]) {
  424. logger('Fetch from memory cache:', highlightId);
  425.  
  426. let totIndex = GL_dataCache.highlights[highlightId].data.reels_media[0].items.length;
  427. username = GL_dataCache.highlights[highlightId].data.reels_media[0].owner.username;
  428. target = GL_dataCache.highlights[highlightId].data.reels_media[0].items[totIndex - nowIndex];
  429. }
  430. else {
  431. let highStories = await getHighlightStories(highlightId);
  432. let totIndex = highStories.data.reels_media[0].items.length;
  433. username = highStories.data.reels_media[0].owner.username;
  434. target = highStories.data.reels_media[0].items[totIndex - nowIndex];
  435.  
  436. GL_dataCache.highlights[highlightId] = highStories;
  437. }
  438.  
  439. logger('onHighlightsStory', highlightId, GL_dataCache.highlights[highlightId]);
  440.  
  441.  
  442. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  443. timestamp = target.taken_at_timestamp;
  444. }
  445.  
  446. if (USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LIMIT) {
  447. let result = await getMediaInfo(target.id);
  448.  
  449. if (result.status === 'ok') {
  450. if (result.items[0].video_versions) {
  451. if (isPreview) {
  452. openNewTab(result.items[0].video_versions[0].url);
  453. }
  454. else {
  455. saveFiles(result.items[0].video_versions[0].url, username, "highlights", timestamp, 'mp4', highlightId);
  456. }
  457. }
  458. else {
  459. if (isPreview) {
  460. openNewTab(result.items[0].image_versions2.candidates[0].url);
  461. }
  462. else {
  463. saveFiles(result.items[0].image_versions2.candidates[0].url, username, "highlights", timestamp, 'jpg', highlightId);
  464. }
  465. }
  466. }
  467. else {
  468. if (USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT) {
  469. delete GL_dataCache.highlights[highlightId];
  470. TEMP_FETCH_RATE_LIMIT = true;
  471.  
  472. onHighlightsStory(true, isPreview);
  473. }
  474. else {
  475. alert('Fetch failed from Media API. API response message: ' + result.message);
  476. }
  477.  
  478. logger(result);
  479. }
  480. }
  481. else {
  482. if (target.is_video) {
  483. if (isPreview) {
  484. openNewTab(target.video_resources.at(-1).src, username);
  485. }
  486. else {
  487. saveFiles(target.video_resources.at(-1).src, username, "highlights", timestamp, 'mp4', highlightId);
  488. }
  489. }
  490. else {
  491. if (isPreview) {
  492. openNewTab(target.display_resources.at(-1).src, username);
  493. }
  494. else {
  495. saveFiles(target.display_resources.at(-1).src, username, "highlights", timestamp, 'jpg', highlightId);
  496. }
  497. }
  498.  
  499. TEMP_FETCH_RATE_LIMIT = false;
  500. }
  501.  
  502. updateLoadingBar(false);
  503. }
  504. else {
  505. // Add the stories download button
  506. if (!$('.IG_DWHISTORY').length) {
  507. let $element = null;
  508.  
  509. // Default detecter (section layout mode)
  510. if ($('body > div section._ac0a').length > 0) {
  511. $element = $('body > div section:visible._ac0a');
  512. }
  513. else {
  514. $element = $('body > div section:visible > div > div[style]:not([class])');
  515. $element.css('position', 'relative');
  516. }
  517.  
  518. // Detecter for div layout mode
  519. if ($element.length === 0) {
  520. let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
  521. let nowSize = 0;
  522.  
  523. $$element.each(function () {
  524. if ($(this).width() > nowSize) {
  525. nowSize = $(this).width();
  526. $element = $(this).children('div').first();
  527. }
  528. });
  529. }
  530.  
  531.  
  532. if ($element != null) {
  533. //$element.css('position','relative');
  534. $element.append(`<div data-ih-locale-title="DW" title="${_i18n("DW")}" class="IG_DWHISTORY">${SVG.DOWNLOAD}</div>`);
  535. $element.append(`<div data-ih-locale-title="NEW_TAB" title="${_i18n("NEW_TAB")}" class="IG_DWHINEWTAB">${SVG.NEW_TAB}</div>`);
  536.  
  537. let $header = getStoryProgress(username);
  538. if ($header.length > 1) {
  539. $element.append(`<div data-ih-locale-title="DW_ALL" title="${_i18n("DW_ALL")}" class="IG_DWHISTORY_ALL">${SVG.DOWNLOAD_ALL}</div>`);
  540. }
  541.  
  542. //// Modify video volume
  543. //if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  544. // $element.find('video').each(function(){
  545. // $(this).on('play playing', function(){
  546. // if(!$(this).data('modify')){
  547. // $(this).attr('data-modify', true);
  548. // this.volume = VIDEO_VOLUME;
  549. // logger('(highlight) Added video event listener #modify');
  550. // }
  551. // });
  552. // });
  553. //}
  554.  
  555. // Make sure to first remove thumbnail button if still exists and highlight is a picture
  556. $element.find('img[referrerpolicy]').each(function () {
  557. $(this).on('load', function () {
  558. if (!$(this).data('remove-thumbnail')) {
  559. if ($element.find('.IG_DWHISTORY_THUMBNAIL').length === 0) {
  560. $(this).attr('data-remove-thumbnail', true);
  561. $('.IG_DWHISTORY_THUMBNAIL').remove();
  562. logger('(highlight) Manually removing thumbnail button');
  563. }
  564. else {
  565. $(this).attr('data-remove-thumbnail', true);
  566. logger('(highlight) Thumbnail button is not present for this picture');
  567. }
  568. }
  569. });
  570. });
  571.  
  572. // Try to use event listener 'timeupdate' in order to detect if highlight is a video
  573. //$element.find('video').each(function(){
  574. // $(this).on('timeupdate',function(){
  575. // if(!$(this).data('modify-thumbnail')){
  576. // if($element.find('.IG_DWHISTORY_THUMBNAIL').length === 0){
  577. // $(this).attr('data-modify-thumbnail', true);
  578. // onHighlightsStoryThumbnail(false);
  579. // logger('(highlight) Manually inserting thumbnail button');
  580. // }
  581. // else{
  582. // $(this).attr('data-modify-thumbnail', true);
  583. // logger('(highlight) Thumbnail button already inserted');
  584. // }
  585. // }
  586. // });
  587. //});
  588. }
  589. }
  590. }
  591. }
  592.  
  593. /**
  594. * onHighlightsStoryThumbnail
  595. * @description Trigger user's highlight video thumbnail download event or button display event.
  596. *
  597. * @param {Boolean} isDownload - Check if it is a download operation
  598. * @return {void}
  599. */
  600. async function onHighlightsStoryThumbnail(isDownload) {
  601. if (isDownload) {
  602. let date = new Date().getTime();
  603. let timestamp = Math.floor(date / 1000);
  604. let highlightId = location.href.replace(/\/$/ig, '').split('/').at(-1);
  605. let username = "";
  606. let nowIndex = $("body > div section._ac0a header._ac0k > ._ac3r ._ac3n ._ac3p[style]").length ||
  607. $('body > div section:visible > div > div:not([class]) > div > div div.x1ned7t2.x78zum5 div.x1caxmr6').length ||
  608. $('body > div div:not([hidden]) section:visible > div div[style]:not([class]) > div').find('div div.x1ned7t2.x78zum5 div.x1caxmr6').length;
  609. let target = "";
  610.  
  611. updateLoadingBar(true);
  612.  
  613. if (GL_dataCache.highlights[highlightId]) {
  614. logger('Fetch from memory cache:', highlightId);
  615.  
  616. let totIndex = GL_dataCache.highlights[highlightId].data.reels_media[0].items.length;
  617. username = GL_dataCache.highlights[highlightId].data.reels_media[0].owner.username;
  618. target = GL_dataCache.highlights[highlightId].data.reels_media[0].items[totIndex - nowIndex];
  619. }
  620. else {
  621. let highStories = await getHighlightStories(highlightId);
  622. let totIndex = highStories.data.reels_media[0].items.length;
  623. username = highStories.data.reels_media[0].owner.username;
  624. target = highStories.data.reels_media[0].items[totIndex - nowIndex];
  625.  
  626. GL_dataCache.highlights[highlightId] = highStories;
  627. }
  628.  
  629. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  630. timestamp = target.taken_at_timestamp;
  631. }
  632.  
  633. if (USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LIMIT) {
  634. let result = await getMediaInfo(target.id);
  635.  
  636. if (result.status === 'ok') {
  637. saveFiles(result.items[0].image_versions2.candidates[0].url, username, "highlights", timestamp, 'jpg', highlightId);
  638. }
  639. else {
  640. if (USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT) {
  641. delete GL_dataCache.highlights[highlightId];
  642. TEMP_FETCH_RATE_LIMIT = true;
  643.  
  644. onHighlightsStoryThumbnail(true);
  645. }
  646. else {
  647. alert('Fetch failed from Media API. API response message: ' + result.message);
  648. }
  649.  
  650. logger(result);
  651. }
  652. }
  653. else {
  654. saveFiles(target.display_resources.at(-1).src, username, "highlights", timestamp, 'jpg', highlightId);
  655. TEMP_FETCH_RATE_LIMIT = false;
  656. }
  657.  
  658. updateLoadingBar(false);
  659. }
  660. else {
  661. if ($('body > div section video.xh8yej3').length) {
  662. // Add the stories thumbnail download button
  663. if (!$('.IG_DWHISTORY_THUMBNAIL').length) {
  664. let $element = null;
  665.  
  666. // Default detecter (section layout mode)
  667. if ($('body > div section._ac0a').length > 0) {
  668. $element = $('body > div section:visible._ac0a');
  669. }
  670. else {
  671. $element = $('body > div section:visible > div > div[style]:not([class])');
  672. $element.css('position', 'relative');
  673. }
  674.  
  675. // Detecter for div layout mode
  676. if ($element.length === 0) {
  677. let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
  678. let nowSize = 0;
  679.  
  680. $$element.each(function () {
  681. if ($(this).width() > nowSize) {
  682. nowSize = $(this).width();
  683. $element = $(this).children('div').first();
  684. }
  685. });
  686. }
  687.  
  688. if ($element != null) {
  689. $element.append(`<div data-ih-locale-title="THUMBNAIL_INTRO" title="${_i18n("THUMBNAIL_INTRO")}" class="IG_DWHISTORY_THUMBNAIL">${SVG.THUMBNAIL}</div>`);
  690. }
  691. }
  692. }
  693. else {
  694. $('.IG_DWHISTORY_THUMBNAIL').remove();
  695. }
  696. }
  697. }
  698.  
  699. /**
  700. * onStoryAll
  701. * @description Trigger user's story all download event.
  702. *
  703. * @return {void}
  704. */
  705. async function onStoryAll() {
  706. updateLoadingBar(true);
  707.  
  708. let date = new Date().getTime();
  709. let timestamp = Math.floor(date / 1000);
  710. let username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split("/").filter(s => s.length > 0).at(1);
  711.  
  712. let userInfo = await getUserId(username);
  713. let userId = userInfo.user.pk;
  714. let stories = await getStories(userId);
  715.  
  716. let complete = 0;
  717. setDownloadProgress(complete, stories.data.reels_media[0].items.length);
  718.  
  719. stories.data.reels_media[0].items.forEach((item, idx) => {
  720. setTimeout(() => {
  721. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  722. timestamp = item.taken_at_timestamp;
  723. }
  724.  
  725. item.display_resources.sort(function (a, b) {
  726. if (a.config_width < b.config_width) return 1;
  727. if (a.config_width > b.config_width) return -1;
  728. return 0;
  729. });
  730.  
  731. if (item.is_video) {
  732. saveFiles(item.video_resources[0].src, username, "stories", timestamp, 'mp4', item.id).then(() => {
  733. setDownloadProgress(++complete, stories.data.reels_media[0].items.length);
  734. });
  735. }
  736. else {
  737. saveFiles(item.display_resources[0].src, username, "stories", timestamp, 'jpg', item.id).then(() => {
  738. setDownloadProgress(++complete, stories.data.reels_media[0].items.length);
  739. });
  740. }
  741. }, 100 * idx);
  742. });
  743. }
  744.  
  745. /**
  746. * onStory
  747. * @description Trigger user's story download event or button display event.
  748. *
  749. * @param {Boolean} isDownload - Check if it is a download operation
  750. * @param {Boolean} isForce - Check if downloading directly from API instead of cache
  751. * @param {Boolean} isPreview - Check if it is need to open new tab
  752. * @return {void}
  753. */
  754. async function onStory(isDownload, isForce, isPreview) {
  755. var username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split("/").filter(s => s.length > 0).at(1);
  756. if (isDownload) {
  757. let date = new Date().getTime();
  758. let timestamp = Math.floor(date / 1000);
  759.  
  760. updateLoadingBar(true);
  761. if (USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LIMIT) {
  762. let mediaId = null;
  763.  
  764. let userInfo = await getUserId(username);
  765. let userId = userInfo.user.pk;
  766. let stories = await getStories(userId);
  767. let urlID = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
  768.  
  769. /*
  770. let latest_reel_media = stories.data.reels_media[0].latest_reel_media;
  771. let last_seen = stories.data.reels_media[0].seen;
  772. logger(stories);
  773.  
  774. if(urlID == null){
  775. mediaId = stories.data.reels_media[0].items.filter(function(item, index){
  776. return item.taken_at_timestamp === last_seen && item.taken_at_timestamp !== latest_reel_media || last_seen === latest_reel_media && index === 0;
  777. })?.at(0)?.id;
  778. logger('nula', mediaId);
  779. }
  780. else{
  781. stories.data.reels_media[0].items.forEach(item => {
  782. if(item.id == urlID){
  783. mediaId = item.id;
  784. }
  785. });
  786. }
  787. */
  788.  
  789. stories.data.reels_media[0].items.forEach(item => {
  790. if (item.id == urlID) {
  791. mediaId = item.id;
  792. }
  793. });
  794.  
  795. if (mediaId == null) {
  796. let $header = getStoryProgress(username);
  797.  
  798. $header.each(function (index) {
  799. if ($(this).children().length > 0) {
  800. mediaId = stories.data.reels_media[0].items[index].id;
  801. }
  802. });
  803. }
  804.  
  805. if (mediaId == null) {
  806. // appear in from profile page to story page
  807. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function (index) {
  808. if ($(this).hasClass('x1lix1fw')) {
  809. if ($(this).children().length > 0) {
  810. mediaId = stories.data.reels_media[0].items[index].id;
  811. }
  812. }
  813. });
  814.  
  815. // appear in from home page to story page
  816. $('body > div section:visible ._ac0k > ._ac3r > div').each(function (index) {
  817. if ($(this).children().hasClass('_ac3q')) {
  818. mediaId = stories.data.reels_media[0].items[index].id;
  819. }
  820. });
  821. }
  822.  
  823. if (mediaId == null) {
  824. mediaId = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
  825. }
  826.  
  827. let result = await getMediaInfo(mediaId);
  828.  
  829. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  830. timestamp = result.items[0].taken_at;
  831. }
  832.  
  833. if (result.status === 'ok') {
  834. if (result.items[0].video_versions) {
  835. if (isPreview) {
  836. openNewTab(result.items[0].video_versions[0].url);
  837. }
  838. else {
  839. saveFiles(result.items[0].video_versions[0].url, username, "stories", timestamp, 'mp4', mediaId);
  840. }
  841. }
  842. else {
  843. if (isPreview) {
  844. openNewTab(result.items[0].image_versions2.candidates[0].url);
  845. }
  846. else {
  847. saveFiles(result.items[0].image_versions2.candidates[0].url, username, "stories", timestamp, 'jpg', mediaId);
  848. }
  849. }
  850. }
  851. else {
  852. if (USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT) {
  853. TEMP_FETCH_RATE_LIMIT = true;
  854. onStory(isDownload, isForce, isPreview);
  855. }
  856. else {
  857. alert('Fetch failed from Media API. API response message: ' + result.message);
  858. }
  859. logger(result);
  860. }
  861.  
  862. updateLoadingBar(false);
  863. return;
  864. }
  865.  
  866. if ($('body > div section:visible video[playsinline]').length > 0) {
  867. // Download stories if it is video
  868. let type = "mp4";
  869. let videoURL = "";
  870. let targetURL = location.pathname.replace(/\/$/ig, '').split("/").at(-1);
  871. let mediaId = null;
  872.  
  873. if (GL_dataCache.stories[username] && !isForce) {
  874. logger('Fetch from memory cache:', username);
  875. GL_dataCache.stories[username].data.reels_media[0].items.forEach(item => {
  876. if (item.id == targetURL) {
  877. videoURL = item.video_resources[0].src;
  878. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  879. timestamp = item.taken_at_timestamp;
  880. mediaId = item.id;
  881. }
  882. }
  883. });
  884.  
  885. if (videoURL.length == 0) {
  886. logger('Memory cache not found, try fetch from API:', username);
  887. onStory(true, true);
  888. return;
  889. }
  890. }
  891. else {
  892. let userInfo = await getUserId(username);
  893. let userId = userInfo.user.pk;
  894. let stories = await getStories(userId);
  895.  
  896. stories.data.reels_media[0].items.forEach(item => {
  897. if (item.id == targetURL) {
  898. videoURL = item.video_resources[0].src;
  899. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  900. timestamp = item.taken_at_timestamp;
  901. mediaId = item.id;
  902. }
  903. }
  904. });
  905.  
  906. // GitHub issue #4: thinkpad4
  907. if (videoURL.length == 0) {
  908.  
  909. let $header = getStoryProgress(username);
  910.  
  911. $header.each(function (index) {
  912. if ($(this).children().length > 0) {
  913. videoURL = stories.data.reels_media[0].items[index].video_resources[0].src;
  914. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  915. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  916. mediaId = stories.data.reels_media[0].items[index].id;
  917. }
  918. }
  919. });
  920.  
  921.  
  922. if (videoURL.length == 0) {
  923. // appear in from profile page to story page
  924. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function (index) {
  925. if ($(this).hasClass('x1lix1fw')) {
  926. if ($(this).children().length > 0) {
  927. videoURL = stories.data.reels_media[0].items[index].video_resources[0].src;
  928. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  929. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  930. mediaId = stories.data.reels_media[0].items[index].id;
  931. }
  932. }
  933. }
  934. });
  935.  
  936. // appear in from home page to story page
  937. $('body > div section:visible ._ac0k > ._ac3r > div').each(function (index) {
  938. if ($(this).children().hasClass('_ac3q')) {
  939. videoURL = stories.data.reels_media[0].items[index].video_resources[0].src;
  940. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  941. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  942. mediaId = stories.data.reels_media[0].items[index].id;
  943. }
  944. }
  945. });
  946. }
  947. }
  948.  
  949. GL_dataCache.stories[username] = stories;
  950. }
  951.  
  952. if (videoURL.length == 0) {
  953. alert(_i18n("NO_VID_URL"));
  954. }
  955. else {
  956. if (isPreview) {
  957. openNewTab(videoURL);
  958. }
  959. else {
  960. saveFiles(videoURL, username, "stories", timestamp, type, mediaId);
  961. }
  962. }
  963. }
  964. else {
  965. // Download stories if it is image
  966. let srcset = $('body > div section:visible img[referrerpolicy][class], body > div section:visible img[crossorigin][class]:not([alt])').attr('srcset')?.split(',')[0]?.split(' ')[0];
  967. let link = (srcset) ? srcset : $('body > div section:visible img[referrerpolicy][class], body > div section:visible img[crossorigin][class]:not([alt])').filter(function () {
  968. return $(this).parents('a').length === 0 && $(this).width() === $(this).parent().width();
  969. }).attr('src');
  970.  
  971. if (!link) {
  972. // _aa63 mean stories picture in stories page (not avatar)
  973. let $element = $('body > div section:visible img._aa63');
  974. link = ($element.attr('srcset')) ? $element.attr('srcset')?.split(',')[0]?.split(' ')[0] : $element.attr('src');
  975. }
  976.  
  977. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  978. timestamp = new Date($('body > div section:visible time[datetime][class]').first().attr('datetime')).getTime();
  979. }
  980.  
  981. let downloadLink = link;
  982. let type = 'jpg';
  983.  
  984. if (isPreview) {
  985. openNewTab(downloadLink);
  986. }
  987. else {
  988. saveFiles(downloadLink, username, "stories", timestamp, type, getStoryId(downloadLink) ?? "");
  989. }
  990. }
  991.  
  992. TEMP_FETCH_RATE_LIMIT = false;
  993. updateLoadingBar(false);
  994. }
  995. else {
  996. // Add the stories download button
  997. if (!$('.IG_DWSTORY').length) {
  998. GL_dataCache.stories = {};
  999. let $element = null;
  1000. // Default detecter (section layout mode)
  1001. if ($('body > div section._ac0a').length > 0) {
  1002. $element = $('body > div section:visible._ac0a');
  1003. }
  1004. // detecter (single story layout mode)
  1005. else {
  1006. $element = $('body > div section:visible > div > div[style]:not([class])');
  1007. $element.css('position', 'relative');
  1008. }
  1009.  
  1010.  
  1011. if ($element.length === 0) {
  1012. $element = $('div[id^="mount"] section > div > a[href="/"]').parent().parent().parent().find('section:visible > div > div[style]:not([class])');
  1013. $element.css('position', 'relative');
  1014. }
  1015.  
  1016. if ($element.length === 0) {
  1017. $element = $('div[id^="mount"] section > div > a[href="/"]').parent().parent().parent().find('section:visible > div div[style]:not([class]) > div:not([data-visualcompletion="loading-state"])');
  1018. $element.css('position', 'relative');
  1019. }
  1020.  
  1021.  
  1022. // Detecter for div layout mode
  1023. if ($element.length === 0) {
  1024. let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
  1025. let nowSize = 0;
  1026.  
  1027. $$element.each(function () {
  1028. if ($(this).width() > nowSize) {
  1029. nowSize = $(this).width();
  1030. $element = $(this).children('div').first();
  1031. }
  1032. });
  1033. }
  1034.  
  1035.  
  1036. if ($element != null) {
  1037. $element.first().css('position', 'relative');
  1038. $element.first().append(`<div data-ih-locale-title="DW" title="${_i18n("DW")}" class="IG_DWSTORY">${SVG.DOWNLOAD}</div>`);
  1039. $element.first().append(`<div data-ih-locale-title="NEW_TAB" title="${_i18n("NEW_TAB")}" class="IG_DWNEWTAB">${SVG.NEW_TAB}</div>`);
  1040.  
  1041. let $header = getStoryProgress(username);
  1042. if ($header.length > 1) {
  1043. $element.first().append(`<div data-ih-locale-title="DW_ALL" title="${_i18n("DW_ALL")}" class="IG_DWSTORY_ALL">${SVG.DOWNLOAD_ALL}</div>`);
  1044. }
  1045.  
  1046. // Modify video volume
  1047. //if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  1048. // $element.find('video').each(function(){
  1049. // $(this).on('play playing', function(){
  1050. // if(!$(this).data('modify')){
  1051. // $(this).attr('data-modify', true);
  1052. // this.volume = VIDEO_VOLUME;
  1053. // logger('(story) Added video event listener #modify');
  1054. // }
  1055. // });
  1056. // });
  1057. //}
  1058.  
  1059. // Make sure to first remove thumbnail button if still exists and story is a picture
  1060. $element.find('img[referrerpolicy]').each(function () {
  1061. $(this).on('load', function () {
  1062. if (!$(this).data('remove-thumbnail')) {
  1063. if ($element.find('.IG_DWSTORY_THUMBNAIL').length === 0) {
  1064. $(this).attr('data-remove-thumbnail', true);
  1065. $('.IG_DWSTORY_THUMBNAIL').remove();
  1066. logger('(story) Manually removing thumbnail button');
  1067. }
  1068. else {
  1069. $(this).attr('data-remove-thumbnail', true);
  1070. logger('(story) Thumbnail button is not present for this picture');
  1071. }
  1072. }
  1073. });
  1074. });
  1075.  
  1076. // Try to use event listener 'timeupdate' in order to detect if story is a video
  1077. //$element.find('video').each(function(){
  1078. // $(this).on('timeupdate',function(){
  1079. // if(!$(this).data('modify-thumbnail')){
  1080. // if($element.find('.IG_DWSTORY_THUMBNAIL').length === 0){
  1081. // $(this).attr('data-modify-thumbnail', true);
  1082. // onStoryThumbnail(false);
  1083. // logger('(story) Manually inserting thumbnail button');
  1084. // }
  1085. // else{
  1086. // $(this).attr('data-modify-thumbnail', true);
  1087. // logger('(story) Thumbnail button already inserted');
  1088. // }
  1089. // }
  1090. // });
  1091. //});
  1092. }
  1093. }
  1094. }
  1095. }
  1096.  
  1097. /**
  1098. * onStoryThumbnail
  1099. * @description Trigger user's story video thumbnail download event or button display event.
  1100. *
  1101. * @param {Boolean} isDownload - Check if it is a download operation
  1102. * @param {Boolean} isForce - Check if downloading directly from API instead of cache
  1103. * @return {void}
  1104. */
  1105. async function onStoryThumbnail(isDownload, isForce) {
  1106. if (isDownload) {
  1107. // Download stories if it is video
  1108. let date = new Date().getTime();
  1109. let timestamp = Math.floor(date / 1000);
  1110. let type = 'jpg';
  1111. let username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split('/').at(2);
  1112. // Download thumbnail
  1113. let targetURL = location.pathname.replace(/\/$/ig, '').split("/").at(-1);
  1114. let videoThumbnailURL = "";
  1115. let mediaId = null;
  1116.  
  1117. updateLoadingBar(true);
  1118.  
  1119. if (USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LIMIT) {
  1120. let userInfo = await getUserId(username);
  1121. let userId = userInfo.user.pk;
  1122. let stories = await getStories(userId);
  1123. let urlID = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
  1124.  
  1125. stories.data.reels_media[0].items.forEach(item => {
  1126. if (item.id == urlID) {
  1127. mediaId = item.id;
  1128. }
  1129. });
  1130.  
  1131. if (mediaId == null) {
  1132. let $header = getStoryProgress(username);
  1133.  
  1134. $header.each(function (index) {
  1135. if ($(this).children().length > 0) {
  1136. mediaId = stories.data.reels_media[0].items[index].id;
  1137. }
  1138. });
  1139. }
  1140.  
  1141. if (mediaId == null) {
  1142. // appear in from profile page to story page
  1143. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function (index) {
  1144. if ($(this).hasClass('x1lix1fw')) {
  1145. if ($(this).children().length > 0) {
  1146. mediaId = stories.data.reels_media[0].items[index].id;
  1147. }
  1148. }
  1149. });
  1150.  
  1151. // appear in from home page to story page
  1152. $('body > div section:visible ._ac0k > ._ac3r > div').each(function (index) {
  1153. if ($(this).children().hasClass('_ac3q')) {
  1154. mediaId = stories.data.reels_media[0].items[index].id;
  1155. }
  1156. });
  1157. }
  1158.  
  1159. if (mediaId == null) {
  1160. mediaId = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
  1161. }
  1162.  
  1163. let result = await getMediaInfo(mediaId);
  1164.  
  1165. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1166. timestamp = result.items[0].taken_at;
  1167. }
  1168.  
  1169. if (result.status === 'ok') {
  1170. saveFiles(result.items[0].image_versions2.candidates[0].url, username, "stories", timestamp, 'jpg', mediaId);
  1171.  
  1172. }
  1173. else {
  1174. if (USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT) {
  1175. TEMP_FETCH_RATE_LIMIT = true;
  1176. onStoryThumbnail(true, isForce);
  1177. }
  1178. else {
  1179. alert('Fetch failed from Media API. API response message: ' + result.message);
  1180. }
  1181.  
  1182. logger(result);
  1183. }
  1184.  
  1185. updateLoadingBar(false);
  1186. return;
  1187. }
  1188.  
  1189. if (GL_dataCache.stories[username] && !isForce) {
  1190. logger('Fetch from memory cache:', username);
  1191. GL_dataCache.stories[username].data.reels_media[0].items.forEach(item => {
  1192. if (item.id == targetURL) {
  1193. videoThumbnailURL = item.display_url;
  1194. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1195. timestamp = item.taken_at_timestamp;
  1196. mediaId = item.id;
  1197. }
  1198. }
  1199. });
  1200.  
  1201. if (videoThumbnailURL.length == 0) {
  1202. logger('Memory cache not found, try fetch from API:', username);
  1203. onStoryThumbnail(true, true);
  1204. return;
  1205. }
  1206. }
  1207. else {
  1208. let userInfo = await getUserId(username);
  1209. let userId = userInfo.user.pk;
  1210. let stories = await getStories(userId);
  1211.  
  1212. stories.data.reels_media[0].items.forEach(item => {
  1213. if (item.id == targetURL) {
  1214. videoThumbnailURL = item.display_url;
  1215. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1216. timestamp = item.taken_at_timestamp;
  1217. mediaId = item.id;
  1218. }
  1219. }
  1220. });
  1221.  
  1222. // GitHub issue #4: thinkpad4
  1223. if (videoThumbnailURL.length == 0) {
  1224. let $header = getStoryProgress(username);
  1225.  
  1226. $header.each(function (index) {
  1227. if ($(this).children().length > 0) {
  1228. videoThumbnailURL = stories.data.reels_media[0].items[index].display_url;
  1229. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1230. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  1231. mediaId = stories.data.reels_media[0].items[index].id;
  1232. }
  1233. }
  1234. });
  1235.  
  1236. if (videoThumbnailURL.length == 0) {
  1237. // appear in from profile page to story page
  1238. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function (index) {
  1239. if ($(this).hasClass('x1lix1fw')) {
  1240. if ($(this).children().length > 0) {
  1241. videoThumbnailURL = stories.data.reels_media[0].items[index].display_url;
  1242. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1243. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  1244. mediaId = stories.data.reels_media[0].items[index].id;
  1245. }
  1246. }
  1247. }
  1248. });
  1249.  
  1250. // appear in from home page to story page
  1251. $('body > div section:visible ._ac0k > ._ac3r > div').each(function (index) {
  1252. if ($(this).children().hasClass('_ac3q')) {
  1253. videoThumbnailURL = stories.data.reels_media[0].items[index].display_url;
  1254. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1255. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  1256. mediaId = stories.data.reels_media[0].items[index].id;
  1257. }
  1258. }
  1259. });
  1260. }
  1261. }
  1262. }
  1263.  
  1264. saveFiles(videoThumbnailURL, username, "thumbnail", timestamp, type, mediaId);
  1265. TEMP_FETCH_RATE_LIMIT = false;
  1266. updateLoadingBar(false);
  1267. }
  1268. else {
  1269. if ($('body > div div.IG_DWSTORY').parent().find('video[class]').length) {
  1270. // Add the stories download button
  1271. let $element = null;
  1272. // Default detecter (section layout mode)
  1273. if ($('body > div section._ac0a').length > 0) {
  1274. $element = $('body > div section:visible._ac0a');
  1275. }
  1276. // detecter (single story layout mode)
  1277. else {
  1278. $element = $('body > div section:visible > div > div[style]:not([class])');
  1279. $element.css('position', 'relative');
  1280. }
  1281.  
  1282. if ($element.length === 0) {
  1283. $element = $('div[id^="mount"] section > div > a[href="/"]').parent().parent().parent().find('section:visible > div > div[style]:not([class])');
  1284. $element.css('position', 'relative');
  1285. }
  1286.  
  1287. if ($element.length === 0) {
  1288. $element = $('div[id^="mount"] section > div > a[href="/"]').parent().parent().parent().find('section:visible > div div[style]:not([class]) > div:not([data-visualcompletion="loading-state"])');
  1289. $element.css('position', 'relative');
  1290. }
  1291.  
  1292. // Detecter for div layout mode
  1293. if ($element.length === 0) {
  1294. let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
  1295. let nowSize = 0;
  1296.  
  1297. $$element.each(function () {
  1298. if ($(this).width() > nowSize) {
  1299. nowSize = $(this).width();
  1300. $element = $(this).children('div').first();
  1301. }
  1302. });
  1303. }
  1304.  
  1305.  
  1306. if ($element != null) {
  1307. $element.first().css('position', 'relative');
  1308. $element.first().append(`<div data-ih-locale-title="THUMBNAIL_INTRO" title="${_i18n("THUMBNAIL_INTRO")}" class="IG_DWSTORY_THUMBNAIL">${SVG.THUMBNAIL}</div>`);
  1309. }
  1310.  
  1311. }
  1312. }
  1313. }
  1314.  
  1315. /**
  1316. * onReels
  1317. * @description Trigger user's reels download event or button display event.
  1318. *
  1319. * @param {Boolean} isDownload - Check if it is a download operation
  1320. * @param {Boolean} isVideo - Check if reel is a video element
  1321. * @param {Boolean} isPreview - Check if it is need to open new tab
  1322. * @return {void}
  1323. */
  1324. async function onReels(isDownload, isVideo, isPreview) {
  1325. if (isDownload) {
  1326. updateLoadingBar(true);
  1327.  
  1328. let reelsPath = location.href.split('?').at(0).split('instagram.com/reels/').at(-1).replaceAll('/', '');
  1329. let result = await getBlobMedia(reelsPath);
  1330. let media = result.data;
  1331.  
  1332. let timestamp = new Date().getTime();
  1333.  
  1334. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1335. if (result.type === 'query_hash') {
  1336. timestamp = media.shortcode_media.taken_at_timestamp;
  1337. }
  1338. else {
  1339. timestamp = media.taken_at;
  1340. }
  1341. }
  1342.  
  1343. if (result.type === 'query_hash') {
  1344. if (isVideo && media.shortcode_media.is_video) {
  1345. if (isPreview) {
  1346. openNewTab(media.shortcode_media.video_url);
  1347. }
  1348. else {
  1349. let type = 'mp4';
  1350. saveFiles(media.shortcode_media.video_url, media.shortcode_media.owner.username, "reels", timestamp, type, reelsPath);
  1351. }
  1352. }
  1353. else {
  1354. if (isPreview) {
  1355. openNewTab(media.shortcode_media.display_resources.at(-1).src);
  1356. }
  1357. else {
  1358. let type = 'jpg';
  1359. saveFiles(media.shortcode_media.display_resources.at(-1).src, media.shortcode_media.owner.username, "reels", timestamp, type, reelsPath);
  1360. }
  1361. }
  1362. }
  1363. else {
  1364. if (isVideo && media.video_versions != null) {
  1365. if (isPreview) {
  1366. openNewTab(media.video_versions[0].url);
  1367. }
  1368. else {
  1369. let type = 'mp4';
  1370. saveFiles(media.video_versions[0].url, media.owner.username, "reels", timestamp, type, reelsPath);
  1371. }
  1372. }
  1373. else {
  1374. if (isPreview) {
  1375. openNewTab(media.image_versions2.candidates[0].url);
  1376. }
  1377. else {
  1378. let type = 'jpg';
  1379. saveFiles(media.image_versions2.candidates[0].url, media.owner.username, "reels", timestamp, type, reelsPath);
  1380. }
  1381. }
  1382. }
  1383.  
  1384. updateLoadingBar(false);
  1385. }
  1386. else {
  1387. //$('.IG_REELS_THUMBNAIL, .IG_REELS').remove();
  1388. var timer = setInterval(() => {
  1389. if ($('section > main[role="main"] > div div.x1qjc9v5 video').length > 0) {
  1390. clearInterval(timer);
  1391.  
  1392. if (USER_SETTING.SCROLL_BUTTON) {
  1393. $('#scrollWrapper').remove();
  1394. $('section > main[role="main"]').append('<section id="scrollWrapper"></section>');
  1395. $('section > main[role="main"] > #scrollWrapper').append('<div class="button-up"><div></div></div>');
  1396. $('section > main[role="main"] > #scrollWrapper').append('<div class="button-down"><div></div></div>');
  1397.  
  1398. $('section > main[role="main"] > #scrollWrapper > .button-up').on('click', function () {
  1399. $('section > main[role="main"] > div')[0].scrollBy({ top: -30, behavior: "smooth" });
  1400. });
  1401. $('section > main[role="main"] > #scrollWrapper > .button-down').on('click', function () {
  1402. $('section > main[role="main"] > div')[0].scrollBy({ top: 30, behavior: "smooth" });
  1403. });
  1404. }
  1405.  
  1406. // reels scroll has [tabindex] but header not.
  1407. $('section > main[role="main"] > div[tabindex]').children('div').each(function () {
  1408. if ($(this).children().length > 0) {
  1409. if (!$(this).children().find('.IG_REELS').length) {
  1410. var $main = $(this);
  1411.  
  1412. $(this).children().css('position', 'relative');
  1413.  
  1414. $(this).children().append(`<div data-ih-locale-title="DW" title="${_i18n("DW")}" class="IG_REELS">${SVG.DOWNLOAD}</div>`);
  1415. $(this).children().append(`<div data-ih-locale-title="NEW_TAB" title="${_i18n("NEW_TAB")}" class="IG_REELS_NEWTAB">${SVG.NEW_TAB}</div>`);
  1416. $(this).children().append(`<div data-ih-locale-title="THUMBNAIL_INTRO" title="${_i18n("THUMBNAIL_INTRO")}" class="IG_REELS_THUMBNAIL">${SVG.THUMBNAIL}</div>`);
  1417.  
  1418. // Disable video autoplay
  1419. if (USER_SETTING.DISABLE_VIDEO_LOOPING) {
  1420. $(this).find('video').each(function () {
  1421. $(this).on('ended', function () {
  1422. if (!$(this).data('loop')) {
  1423. let $element_play_button = $(this).next().find('div[role="presentation"] > div svg > path[d^="M5.888"]').parents('button[role="button"], div[role="button"]');
  1424. if ($element_play_button.length > 0) {
  1425. $(this).attr('data-loop', true);
  1426. $element_play_button.click();
  1427. logger('Adding video event listener #loop, then paused click()');
  1428. }
  1429. else {
  1430. $(this).attr('data-loop', true);
  1431. $(this).parent().find('.xpgaw4o').removeAttr('style');
  1432. this.pause();
  1433. logger('Adding video event listener #loop, then paused pause()');
  1434. }
  1435. }
  1436. });
  1437. });
  1438. }
  1439.  
  1440. // Modify video volume
  1441. //if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  1442. // $(this).find('video').each(function(){
  1443. // $(this).on('play playing', function(){
  1444. // if(!$(this).data('modify')){
  1445. // $(this).attr('data-modify', true);
  1446. // this.volume = VIDEO_VOLUME;
  1447. // logger('(reel) Added video event listener #modify');
  1448. // }
  1449. // });
  1450. // });
  1451. //}
  1452.  
  1453. if (USER_SETTING.HTML5_VIDEO_CONTROL) {
  1454. $(this).find('video').each(function () {
  1455. if (!$(this).data('controls')) {
  1456. let $video = $(this);
  1457.  
  1458. logger('(reel) Added video html5 contorller #modify');
  1459.  
  1460. if (USER_SETTING.MODIFY_VIDEO_VOLUME) {
  1461. this.volume = VIDEO_VOLUME;
  1462.  
  1463. $(this).on('loadstart', function () {
  1464. this.volume = VIDEO_VOLUME;
  1465. });
  1466. }
  1467.  
  1468. // Restore layout to show details interface
  1469. $(this).on('contextmenu', function (e) {
  1470. e.preventDefault();
  1471. $video.css('z-index', '-1');
  1472. $video.removeAttr('controls');
  1473. });
  1474.  
  1475. // Hide layout to show controller
  1476. $(this).parent().find('video + div div[role="button"]').filter(function () {
  1477. return $(this).parent('div[role="presentation"]').length > 0 && $(this).css('cursor') === 'pointer' && $(this).attr('style') != null;
  1478. }).first().on('contextmenu', function (e) {
  1479. e.preventDefault();
  1480. $video.css('z-index', '2');
  1481. $video.attr('controls', true);
  1482. });
  1483.  
  1484.  
  1485. $(this).on('volumechange', function () {
  1486. // eslint-disable-next-line no-unused-vars
  1487. let $element_mute_button = $(this).parent().find('video + div > div').find('button[type="button"], div[role="button"]').filter(function (idx) {
  1488. // This is mute/unmute's icon
  1489. return $(this).width() <= 64 && $(this).height() <= 64 && $(this).find('svg > path[d^="M16.636 7.028a1.5"], svg > path[d^="M1.5 13.3c-.8"]').length > 0;
  1490. });
  1491.  
  1492. var is_elelment_muted = $element_mute_button.find('svg > path[d^="M16.636"]').length === 0;
  1493.  
  1494. if (this.muted != is_elelment_muted) {
  1495. this.volume = VIDEO_VOLUME;
  1496. $element_mute_button?.click();
  1497. }
  1498.  
  1499. if ($(this).attr('data-completed')) {
  1500. VIDEO_VOLUME = this.volume;
  1501. GM_setValue('G_VIDEO_VOLUME', this.volume);
  1502. }
  1503.  
  1504. if (this.volume == VIDEO_VOLUME) {
  1505. $(this).attr('data-completed', true);
  1506. }
  1507. });
  1508.  
  1509. $(this).css('position', 'absolute');
  1510. $(this).css('z-index', '2');
  1511. $(this).attr('data-controls', true);
  1512. $(this).attr('controls', true);
  1513. }
  1514. });
  1515. }
  1516.  
  1517. var $videos = $main.find('video');
  1518. var $buttonParent = $(this).find('div[role="presentation"] > div[role="button"] > div').first();
  1519. toggleVolumeSilder($videos, $buttonParent, 'reel');
  1520. }
  1521. }
  1522. });
  1523. }
  1524. }, 250);
  1525. }
  1526. }
  1527.  
  1528. /**
  1529. * getStoryId
  1530. * @description Obtain the media id through the resource URL.
  1531. *
  1532. * @param {string} url
  1533. * @return {string}
  1534. */
  1535. function getStoryId(url) {
  1536. let obj = new URL(url);
  1537. let base64 = obj?.searchParams?.get('ig_cache_key')?.split('.').at(0);
  1538. if (base64) {
  1539. return atob(base64);
  1540. }
  1541. else {
  1542. return null;
  1543. }
  1544. }
  1545.  
  1546. /**
  1547. * getHighlightStories
  1548. * @description Get a list of all stories in highlight Id.
  1549. *
  1550. * @param {Integer} highlightId
  1551. * @return {Object}
  1552. */
  1553. function getHighlightStories(highlightId) {
  1554. return new Promise((resolve, reject) => {
  1555. let getURL = `https://www.instagram.com/graphql/query/?query_hash=45246d3fe16ccc6577e0bd297a5db1ab&variables=%7B%22highlight_reel_ids%22:%5B%22${highlightId}%22%5D,%22precomposed_overlay%22:false%7D`;
  1556.  
  1557. GM_xmlhttpRequest({
  1558. method: "GET",
  1559. url: getURL,
  1560. onload: function (response) {
  1561. try {
  1562. let obj = JSON.parse(response.response);
  1563. resolve(obj);
  1564. }
  1565. catch (err) {
  1566. logger('getHighlightStories()', 'reject', err.message);
  1567. reject(err);
  1568. }
  1569. },
  1570. onerror: function (err) {
  1571. logger('getHighlightStories()', 'reject', err);
  1572. reject(err);
  1573. }
  1574. });
  1575. });
  1576. }
  1577.  
  1578. /**
  1579. * getStories
  1580. * @description Get a list of all stories in user Id.
  1581. *
  1582. * @param {Integer} userId
  1583. * @return {Object}
  1584. */
  1585. function getStories(userId) {
  1586. return new Promise((resolve, reject) => {
  1587. let getURL = `https://www.instagram.com/graphql/query/?query_hash=15463e8449a83d3d60b06be7e90627c7&variables=%7B%22reel_ids%22:%5B%22${userId}%22%5D,%22precomposed_overlay%22:false%7D`;
  1588.  
  1589. GM_xmlhttpRequest({
  1590. method: "GET",
  1591. url: getURL,
  1592. onload: function (response) {
  1593. try {
  1594. let obj = JSON.parse(response.response);
  1595. logger('getStories()', obj);
  1596. resolve(obj);
  1597. }
  1598. catch (err) {
  1599. logger('getStories()', 'reject', err.message);
  1600. reject(err);
  1601. }
  1602. },
  1603. onerror: function (err) {
  1604. logger('getStories()', 'reject', err);
  1605. reject(err);
  1606. }
  1607. });
  1608. });
  1609. }
  1610.  
  1611. /**
  1612. * getUserId
  1613. * @description Get user's id with username
  1614. *
  1615. * @param {String} username
  1616. * @return {Integer}
  1617. */
  1618. function getUserId(username) {
  1619. return new Promise((resolve, reject) => {
  1620. let getURL = `https://www.instagram.com/web/search/topsearch/?query=${username}`;
  1621.  
  1622. GM_xmlhttpRequest({
  1623. method: "GET",
  1624. url: getURL,
  1625. onload: function (response) {
  1626. // Fix search issue by Discord: sno_w_
  1627. let obj = JSON.parse(response.response);
  1628. let result = null;
  1629. obj.users.forEach(pos => {
  1630. if (pos.user.username?.toLowerCase() === username?.toLowerCase()) {
  1631. result = pos;
  1632. }
  1633. });
  1634.  
  1635. if (result != null) {
  1636. logger('getUserId()', result);
  1637. resolve(result);
  1638. }
  1639. else {
  1640. getUserIdWithAgent(username).then((result) => {
  1641. resolve(result);
  1642. // eslint-disable-next-line no-unused-vars
  1643. }).catch((err) => {
  1644. alert("Can not find user info from getUserId()");
  1645. });
  1646. }
  1647. },
  1648. onerror: function (err) {
  1649. logger('getUserId()', 'reject', err);
  1650. reject(err);
  1651. }
  1652. });
  1653. });
  1654. }
  1655.  
  1656. /**
  1657. * getUserIdWithAgent
  1658. * @description Get user's id with username
  1659. *
  1660. * @param {String} username
  1661. * @return {Integer}
  1662. */
  1663. function getUserIdWithAgent(username) {
  1664. return new Promise((resolve, reject) => {
  1665. let getURL = `https://i.instagram.com/api/v1/users/web_profile_info/?username=${username}`;
  1666.  
  1667. GM_xmlhttpRequest({
  1668. method: "GET",
  1669. url: getURL,
  1670. headers: {
  1671. 'X-IG-App-ID': getAppID()
  1672. },
  1673. onload: function (response) {
  1674. try {
  1675. let obj = JSON.parse(response.response);
  1676. let hasUser = obj?.data?.user;
  1677.  
  1678. if (hasUser != null) {
  1679. let userInfo = obj?.data;
  1680. userInfo.user.pk = userInfo.user.id;
  1681. logger('getUserIdWithAgent()', obj);
  1682. resolve(userInfo);
  1683. }
  1684. else {
  1685. logger('getUserIdWithAgent()', 'reject', 'undefined');
  1686. reject('undefined');
  1687. }
  1688. }
  1689. catch (err) {
  1690. logger('getUserIdWithAgent()', 'reject', err.message);
  1691. reject(err);
  1692. }
  1693. },
  1694. onerror: function (err) {
  1695. logger('getUserIdWithAgent()', 'reject', err);
  1696. reject(err);
  1697. }
  1698. });
  1699. });
  1700. }
  1701.  
  1702. /**
  1703. * getUserHighSizeProfile
  1704. * @description Get user's high quality avatar image.
  1705. *
  1706. * @param {Integer} userId
  1707. * @return {String}
  1708. */
  1709. function getUserHighSizeProfile(userId) {
  1710. return new Promise((resolve, reject) => {
  1711. let getURL = `https://i.instagram.com/api/v1/users/${userId}/info/`;
  1712.  
  1713. GM_xmlhttpRequest({
  1714. method: "GET",
  1715. url: getURL,
  1716. headers: {
  1717. 'User-Agent': 'Mozilla/5.0 (Linux; Android 10; Pixel 7 XL)Build/RP1A.20845.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/5.0 Chrome/117.0.5938.60 Mobile Safari/537.36 Instagram 307.0.0.34.111'
  1718. },
  1719. onload: function (response) {
  1720. try {
  1721. let obj = JSON.parse(response.response);
  1722. if (obj.status !== 'ok') {
  1723. logger('getUserHighSizeProfile()', 'reject', obj);
  1724. reject('faild');
  1725. }
  1726. else {
  1727. logger('getUserHighSizeProfile()', obj);
  1728. resolve(obj.user.hd_profile_pic_url_info?.url);
  1729. }
  1730. }
  1731. catch (err) {
  1732. logger('getUserHighSizeProfile()', 'reject', err);
  1733. reject(err);
  1734. }
  1735. },
  1736. onerror: function (err) {
  1737. logger('getUserHighSizeProfile()', 'reject', err);
  1738. reject(err);
  1739. }
  1740. });
  1741. });
  1742. }
  1743.  
  1744. /**
  1745. * getPostOwner
  1746. * @description Get post's author with post shortcode
  1747. *
  1748. * @param {String} postPath
  1749. * @return {String}
  1750. */
  1751. function getPostOwner(postPath) {
  1752. return new Promise((resolve, reject) => {
  1753. if (!postPath) reject("NOPATH");
  1754. let postShortCode = postPath;
  1755. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  1756.  
  1757. GM_xmlhttpRequest({
  1758. method: "GET",
  1759. url: getURL,
  1760. onload: function (response) {
  1761. try {
  1762. let obj = JSON.parse(response.response);
  1763. logger('getPostOwner()', obj);
  1764. resolve(obj.data.shortcode_media.owner.username);
  1765. }
  1766. catch (err) {
  1767. logger('getPostOwner()', 'reject', err.message);
  1768. reject(err);
  1769. }
  1770. },
  1771. onerror: function (err) {
  1772. logger('getPostOwner()', 'reject', err);
  1773. reject(err);
  1774. }
  1775. });
  1776. });
  1777. }
  1778.  
  1779. /**
  1780. * getBlobMedia
  1781. * @description Get list of all media files in post with post shortcode
  1782. *
  1783. * @param {String} postPath
  1784. * @return {Object}
  1785. */
  1786. function getBlobMedia(postPath) {
  1787. return new Promise((resolve, reject) => {
  1788. if (!postPath) reject("NOPATH");
  1789. let postShortCode = postPath;
  1790. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  1791.  
  1792. GM_xmlhttpRequest({
  1793. method: "GET",
  1794. url: getURL,
  1795. headers: {
  1796. "User-Agent": "Mozilla/5.0 (Linux; Android 10; Pixel 7 XL)Build/RP1A.20845.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/5.0 Chrome/117.0.5938.60 Mobile Safari/537.36 Instagram 307.0.0.34.111"
  1797. },
  1798. onload: function (response) {
  1799. try {
  1800. let obj = JSON.parse(response.response);
  1801. logger(obj);
  1802.  
  1803. if (obj.status === 'fail') {
  1804. // alert(`Request failed with API response:\n${obj.message}: ${obj.feedback_message}`);
  1805. logger('Request with:', 'getBlobMediaWithQuery()', postShortCode);
  1806. getBlobMediaWithQueryID(postShortCode).then((res) => {
  1807. resolve({ type: 'query_id', data: res.xdt_api__v1__media__shortcode__web_info.items[0] });
  1808. }).catch((err) => {
  1809. reject(err);
  1810. })
  1811. }
  1812. else {
  1813. resolve({ type: 'query_hash', data: obj.data });
  1814. }
  1815. }
  1816. catch (err) {
  1817. logger('getBlobMedia()', 'reject', err.message);
  1818. reject(err);
  1819. }
  1820. },
  1821. onerror: function (err) {
  1822. logger('getBlobMedia()', 'reject', err);
  1823. reject(err);
  1824. }
  1825. });
  1826. });
  1827. }
  1828.  
  1829. /**
  1830. * getBlobMediaWithQueryID
  1831. * @description Get list of all media files in post with post shortcode
  1832. *
  1833. * @param {String} postPath
  1834. * @return {Object}
  1835. */
  1836. function getBlobMediaWithQueryID(postPath) {
  1837. return new Promise((resolve, reject) => {
  1838. if (!postPath) reject("NOPATH");
  1839. let postShortCode = postPath;
  1840. let getURL = `https://www.instagram.com/graphql/query/?query_id=9496392173716084&variables={%22shortcode%22:%22${postShortCode}%22,%22__relay_internal__pv__PolarisFeedShareMenurelayprovider%22:true,%22__relay_internal__pv__PolarisIsLoggedInrelayprovider%22:true}`;
  1841.  
  1842. GM_xmlhttpRequest({
  1843. method: "GET",
  1844. url: getURL,
  1845. headers: {
  1846. "User-Agent": "Mozilla/5.0 (Linux; Android 10; Pixel 7 XL)Build/RP1A.20845.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/5.0 Chrome/117.0.5938.60 Mobile Safari/537.36 Instagram 307.0.0.34.111",
  1847. 'X-IG-App-ID': getAppID()
  1848. },
  1849. onload: function (response) {
  1850. try {
  1851. let obj = JSON.parse(response.response);
  1852. logger(obj);
  1853.  
  1854. if (obj.status === 'fail') {
  1855. alert(`getBlobMediaWithQueryID(): Request failed with API response:\n${obj.message}: ${obj.feedback_message}`);
  1856. logger(`Request failed with API response ${obj.message}: ${obj.feedback_message}`);
  1857. reject(response);
  1858. }
  1859. else {
  1860. logger('getBlobMediaWithQueryID()', obj.data);
  1861. resolve(obj.data);
  1862. }
  1863. }
  1864. catch (err) {
  1865. logger('getBlobMediaWithQueryID()', 'reject', err.message);
  1866. reject(err);
  1867. }
  1868. },
  1869. onerror: function (err) {
  1870. logger('getBlobMediaWithQueryID()', 'reject', err);
  1871. reject(err);
  1872. }
  1873. });
  1874. });
  1875. }
  1876.  
  1877. /**
  1878. * onReadyMyDW
  1879. * @description Create an event entry point for the download button for the post
  1880. *
  1881. * @param {Boolean} NoDialog - Check if it not showing the dialog
  1882. * @param {?Boolean} hasReferrer - Check if the source of the previous page is a story page
  1883. * @return {void}
  1884. */
  1885. function onReadyMyDW(NoDialog, hasReferrer) {
  1886. if (hasReferrer === true) {
  1887. logger('hasReferrer', 'regenerated');
  1888. $('article[data-snig="canDownload"], div[data-snig="canDownload"]').filter(function () {
  1889. return $(this).find('.SNKMS_IG_DW_MAIN').length === 0
  1890. }).removeAttr('data-snig');
  1891. }
  1892.  
  1893. // Whether is Instagram dialog?
  1894. if (NoDialog == false) {
  1895. const maxCall = 100;
  1896. let i = 0;
  1897. var repeat = setInterval(() => {
  1898. // section:visible > main > div > div[data-snig="canDownload"] > div > div > div > hr << (single foreground post in page, non-floating // <hr> element here is literally the line beneath poster's username) >>
  1899. // section:visible > main > div > div.xdt5ytf[data-snig="canDownload"] << (former CSS selector for single foreground post in page, non-floating) >>
  1900. // <hr> is much more unique element than "div.xdt5ytf"
  1901. if (i > maxCall || $('article[data-snig="canDownload"], section:visible > main > div > div[data-snig="canDownload"] > div > div > div > hr, div[id^="mount"] > div > div > div.x1n2onr6.x1vjfegm div[data-snig="canDownload"]').length > 0) {
  1902. clearInterval(repeat);
  1903.  
  1904. if (i > maxCall) {
  1905. //alert('Trying to call button creation method reached to maximum try times. If you want to re-register method, please open script menu and press "Reload Script" button or hotkey "R" to reload main timer.');
  1906. console.warn('onReadyMyDW() Timer', 'maximum number of repetitions reached, terminated');
  1907. }
  1908. }
  1909.  
  1910. logger('onReadyMyDW() Timer', 'repeating to call detection createDownloadButton()');
  1911. createDownloadButton();
  1912. i++;
  1913. }, 50);
  1914. }
  1915. else {
  1916. createDownloadButton();
  1917. }
  1918. }
  1919.  
  1920. /**
  1921. * getAppID
  1922. * @description Get Instagram App ID
  1923. *
  1924. * @return {?integer}
  1925. */
  1926. function getAppID() {
  1927. let result = null;
  1928. $('script[type="application/json"]').each(function () {
  1929. const regexp = /"APP_ID":"([0-9]+)"/ig;
  1930. const matcher = $(this).text().match(regexp);
  1931. if (matcher != null && result == null) {
  1932. result = [...$(this).text().matchAll(regexp)];
  1933. }
  1934. })
  1935.  
  1936. return (result) ? result.at(0).at(-1) : null;
  1937. }
  1938.  
  1939. /**
  1940. * updateLoadingBar
  1941. * @description Update loading state
  1942. *
  1943. * @param {Boolean} isLoading - Check if loading state
  1944. * @return {void}
  1945. */
  1946. function updateLoadingBar(isLoading) {
  1947. if (isLoading) {
  1948. $('div[id^="mount"] > div > div > div:first').removeClass('x1s85apg');
  1949. $('div[id^="mount"] > div > div > div:first').css('z-index', '20000');
  1950. }
  1951. else {
  1952. $('div[id^="mount"] > div > div > div:first').addClass('x1s85apg');
  1953. $('div[id^="mount"] > div > div > div:first').css('z-index', '');
  1954. }
  1955. }
  1956.  
  1957. /**
  1958. * getStoryProgress
  1959. * @description Get the story progress of the username (post several stories)
  1960. *
  1961. * @param {String} username - Get progress of username
  1962. * @return {Object}
  1963. */
  1964. function getStoryProgress(username) {
  1965. let $header = $('body > div section:visible a[href^="/' + (username) + '"] span').filter(function () {
  1966. return $(this).children().length === 0 && $(this).find('svg').length === 0 && $(this).text()?.toLowerCase() === username?.toLowerCase();
  1967. }).parents('div:not([class]):not([style])').filter(function () {
  1968. return $(this).text()?.toLowerCase() !== username?.toLowerCase()
  1969. }).filter(function () {
  1970. return $(this).children().length > 1
  1971. }).first();
  1972.  
  1973. if ($header.length === 0) {
  1974. $header = $('body > div section:visible a[href^="/' + (username) + '"]').filter(function () {
  1975. return $(this).find('img').length > 0
  1976. }).parents('div:not([class]):not([style])').filter(function () {
  1977. return $(this).text()?.toLowerCase() !== username?.toLowerCase()
  1978. }).filter(function () {
  1979. return $(this).children().length > 1
  1980. }).first();
  1981. }
  1982.  
  1983. return $header.children().filter(function () {
  1984. return $(this).height() < 10
  1985. }).first().children();
  1986. }
  1987.  
  1988. /**
  1989. * getMediaInfo
  1990. * @description Get Instagram Media object
  1991. *
  1992. * @param {String} mediaId
  1993. * @return {Object}
  1994. */
  1995. function getMediaInfo(mediaId) {
  1996. return new Promise((resolve, reject) => {
  1997. let getURL = `https://i.instagram.com/api/v1/media/${mediaId}/info/`;
  1998.  
  1999. if (mediaId == null) {
  2000. alert("Can not call Media API because of the media id is invalid.");
  2001. logger('getMediaInfo()', 'reject', 'Can not call Media API because of the media id is invalid.');
  2002.  
  2003. updateLoadingBar(false);
  2004. reject(-1);
  2005. return;
  2006. }
  2007. if (getAppID() == null) {
  2008. alert("Can not call Media API because of the app id is invalid.");
  2009. logger('getMediaInfo()', 'reject', 'Can not call Media API because of the app id is invalid.');
  2010. updateLoadingBar(false);
  2011. reject(-1);
  2012. return;
  2013. }
  2014.  
  2015. GM_xmlhttpRequest({
  2016. method: "GET",
  2017. url: getURL,
  2018. headers: {
  2019. "User-Agent": window.navigator.userAgent,
  2020. "Accept": "*/*",
  2021. 'X-IG-App-ID': getAppID()
  2022. },
  2023. onload: function (response) {
  2024. if (response.finalUrl == getURL) {
  2025. let obj = JSON.parse(response.response);
  2026. logger('getMediaInfo()', obj);
  2027. resolve(obj);
  2028. }
  2029. else {
  2030. let finalURL = new URL(response.finalUrl);
  2031. if (finalURL.pathname.startsWith('/accounts/login')) {
  2032. logger('getMediaInfo()', 'reject', 'The account must be logged in to access Media API.');
  2033. alert("The account must be logged in to access Media API.");
  2034. }
  2035. else {
  2036. logger('getMediaInfo()', 'reject', 'Unable to retrieve content because the API was redirected to "' + response.finalUrl + '"');
  2037. alert('Unable to retrieve content because the API was redirected to "' + response.finalUrl + '"');
  2038. }
  2039. updateLoadingBar(false);
  2040. reject(-1);
  2041. }
  2042. },
  2043. onerror: function (err) {
  2044. logger('getMediaInfo()', 'reject', err);
  2045. resolve(err);
  2046. }
  2047. });
  2048. });
  2049. }
  2050.  
  2051. /**
  2052. * getVisibleNodeIndex
  2053. * @description Get element visible node
  2054. *
  2055. * @param {Object} $main
  2056. * @return {Integer}
  2057. */
  2058. function getVisibleNodeIndex($main) {
  2059. var index = 0;
  2060. // homepage classList
  2061. var $dot = $main.find('.x1iyjqo2 > div > div:last-child > div');
  2062.  
  2063. // dialog classList, main top classList
  2064. if ($dot == null || !$dot.hasClass('_acnb')) {
  2065. $dot = $main.find('._aatk > div > div:last-child').eq(0).children('div');
  2066. }
  2067.  
  2068. $dot.filter('._acnb').each(function (sIndex) {
  2069. if ($(this).hasClass('_acnf')) {
  2070. index = sIndex;
  2071. }
  2072. });
  2073.  
  2074. return index;
  2075. }
  2076.  
  2077. /**
  2078. * setDownloadProgress
  2079. * @description Show and set download circle progress
  2080. *
  2081. * @param {Integer} now
  2082. * @param {Integer} total
  2083. * @return {Void}
  2084. */
  2085. function setDownloadProgress(now, total) {
  2086. if ($('.circle_wrapper').length) {
  2087. $('.circle_wrapper span').text(`${now}/${total}`);
  2088.  
  2089. if (now >= total) {
  2090. $('.circle_wrapper').fadeOut(250, function () {
  2091. $(this).remove();
  2092. });
  2093. }
  2094. }
  2095. else {
  2096. $('body').append(`<div class="circle_wrapper"><circle></circle><span>${now}/${total}</span></div>`);
  2097. }
  2098. }
  2099.  
  2100. /**
  2101. * initPostVideoFunction
  2102. * @description Initialize settings related to the video resources in the post
  2103. *
  2104. * @param {Object} $mainElement
  2105. * @return {Void}
  2106. */
  2107. function initPostVideoFunction($mainElement) {
  2108. // Disable video autoplay
  2109. if (USER_SETTING.DISABLE_VIDEO_LOOPING) {
  2110. $mainElement.find('video').each(function () {
  2111. $(this).on('ended', function () {
  2112. if (!$(this).data('loop')) {
  2113. $(this).attr('data-loop', true);
  2114. this.pause();
  2115. logger('(post) Added video event listener #loop');
  2116. }
  2117. });
  2118. });
  2119. }
  2120.  
  2121. // Modify video volume
  2122. if (USER_SETTING.MODIFY_VIDEO_VOLUME) {
  2123. $mainElement.find('video').each(function () {
  2124. $(this).on('play playing', function () {
  2125. if (!$(this).data('modify')) {
  2126. $(this).attr('data-modify', true);
  2127. this.volume = VIDEO_VOLUME;
  2128. logger('(post) Added video event listener #modify');
  2129. }
  2130. });
  2131. });
  2132. }
  2133.  
  2134. if (USER_SETTING.HTML5_VIDEO_CONTROL) {
  2135. $mainElement.find('video').each(function () {
  2136. if (!$(this).data('controls')) {
  2137. let $video = $(this);
  2138.  
  2139. logger('(post) Added video html5 contorller #modify');
  2140.  
  2141. if (USER_SETTING.MODIFY_VIDEO_VOLUME) {
  2142. this.volume = VIDEO_VOLUME;
  2143.  
  2144. $(this).on('loadstart', function () {
  2145. this.volume = VIDEO_VOLUME;
  2146. });
  2147. }
  2148.  
  2149. // Restore layout to show details interface
  2150. $(this).on('contextmenu', function (e) {
  2151. e.preventDefault();
  2152. $video.css('z-index', '-1');
  2153. $video.removeAttr('controls');
  2154. });
  2155.  
  2156. // Hide layout to show controller
  2157. $(this).parent().find('video + div > div').first().on('contextmenu', function (e) {
  2158. e.preventDefault();
  2159. $video.css('z-index', '2');
  2160. $video.attr('controls', true);
  2161. });
  2162.  
  2163. $(this).on('volumechange', function () {
  2164. // eslint-disable-next-line no-unused-vars
  2165. let $element_mute_button = $(this).parent().find('video + div > div').find('button[type="button"], div[role="button"]').filter(function (idx) {
  2166. // This is mute/unmute's icon
  2167. return $(this).width() <= 64 && $(this).height() <= 64 && $(this).find('svg > path[d^="M16.636 7.028a1.5"], svg > path[d^="M1.5 13.3c-.8"]').length > 0;
  2168. });
  2169.  
  2170. var is_elelment_muted = $element_mute_button.find('svg > path[d^="M16.636"]').length === 0;
  2171.  
  2172. if (this.muted != is_elelment_muted) {
  2173. this.volume = VIDEO_VOLUME;
  2174. $element_mute_button?.click();
  2175. }
  2176.  
  2177. if ($(this).attr('data-completed')) {
  2178. VIDEO_VOLUME = this.volume;
  2179. GM_setValue('G_VIDEO_VOLUME', this.volume);
  2180. }
  2181.  
  2182. if (this.volume == VIDEO_VOLUME) {
  2183. $(this).attr('data-completed', true);
  2184. }
  2185. });
  2186.  
  2187. $(this).css('position', 'absolute');
  2188. $(this).css('z-index', '2');
  2189. $(this).attr('data-controls', true);
  2190. $(this).attr('controls', true);
  2191. }
  2192. });
  2193. }
  2194.  
  2195. var $videos = $mainElement.find('video');
  2196. var $buttonParent = $mainElement.find('video + div > div').first();
  2197. toggleVolumeSilder($videos, $buttonParent, 'post', 'bottom');
  2198. };
  2199.  
  2200. /**
  2201. * createDownloadButton
  2202. * @description Create a download button in the upper right corner of each post
  2203. *
  2204. * @return {void}
  2205. */
  2206. function createDownloadButton() {
  2207. // Add download icon per each posts
  2208. // eslint-disable-next-line no-unused-vars
  2209. $('article, section:visible > main > div > div > div > div > div > hr').map(function (index) {
  2210. return $(this).is('section:visible > main > div > div > div > div > div > hr') ? $(this).parent().parent().parent().parent()[0] : this;
  2211. }).filter(function () {
  2212. return $(this).height() > 0 && $(this).width() > 0
  2213. })
  2214. .each(function (index) {
  2215. // If it is have not download icon
  2216. // class x1iyjqo2 mean user profile pages post list container
  2217. if (!$(this).attr('data-snig') && !$(this).hasClass('x1iyjqo2') && !$(this).children('article')?.hasClass('x1iyjqo2') && $(this).parents('div#scrollview').length === 0) {
  2218. logger("Found post container", $(this));
  2219.  
  2220. const $mainElement = $(this);
  2221. const tagName = this.tagName;
  2222. const resourceCountSelector = '._acay ._acaz';
  2223.  
  2224. // not loop each in single top post
  2225. if (tagName === "DIV" && index != 0) {
  2226. return;
  2227. }
  2228.  
  2229. const $childElement = $mainElement.children("div").children("div");
  2230.  
  2231. if ($childElement.length === 0) return;
  2232.  
  2233. logger("Found insert point", $childElement);
  2234.  
  2235. // Modify carousel post counter's position to not interfere with our buttons
  2236. if ($mainElement.find('._acay').length > 0) {
  2237. if ($mainElement.find('._acay + .x24i39r').length > 0) {
  2238. $mainElement.find('._acay + .x24i39r').css('top', '37px');
  2239. }
  2240.  
  2241. const observeNode = $mainElement.find('._acay').first().parent()[0];
  2242. var observer = new MutationObserver(function () {
  2243. $mainElement.find('._acay + .x24i39r').css('top', '37px');
  2244. });
  2245.  
  2246. observer.observe(observeNode, {
  2247. childList: true
  2248. });
  2249. }
  2250.  
  2251. $childElement.eq((tagName === "DIV") ? 0 : $childElement.length - 2).append(`<div class="button_wrapper">`);
  2252.  
  2253. // Add icons
  2254. const DownloadElement = `<div data-ih-locale-title="DW" title="${_i18n("DW")}" class="SNKMS_IG_DW_MAIN">${SVG.DOWNLOAD}</div>`;
  2255. const NewTabElement = `<div data-ih-locale-title="NEW_TAB" title="${_i18n("NEW_TAB")}" class="SNKMS_IG_NEWTAB_MAIN">${SVG.NEW_TAB}</div>`;
  2256. const ThumbnailElement = `<div data-ih-locale-title="THUMBNAIL_INTRO" title="${_i18n("THUMBNAIL_INTRO")}" class="SNKMS_IG_THUMBNAIL_MAIN">${SVG.THUMBNAIL}</div>`;
  2257.  
  2258. $childElement.find(".button_wrapper").append(DownloadElement);
  2259.  
  2260. const resource_count = $mainElement.find(resourceCountSelector).length;
  2261.  
  2262. if (resource_count > 1 && USER_SETTING.DIRECT_DOWNLOAD_VISIBLE_RESOURCE && !USER_SETTING.DIRECT_DOWNLOAD_ALL) {
  2263. const DownloadAllElement = `<div data-ih-locale-title="DW_ALL" title="${_i18n("DW_ALL")}" class="SNKMS_IG_DW_ALL_MAIN">${SVG.DOWNLOAD_ALL}</div>`;
  2264. $childElement.find(".button_wrapper").append(DownloadAllElement);
  2265. }
  2266.  
  2267. $childElement.find(".button_wrapper").append(NewTabElement);
  2268.  
  2269. setTimeout(() => {
  2270. // Check if visible post is video
  2271. if ($childElement.eq((tagName === "DIV") ? 0 : $childElement.length - 2).find('div > ul li._acaz').length === 0) {
  2272. if ($childElement.find('video').length > 0) {
  2273. $childElement.find(".button_wrapper").append(ThumbnailElement);
  2274. }
  2275. }
  2276. else {
  2277. // eslint-disable-next-line no-unused-vars
  2278. const checkVideoNodeCallback = (entries, observer) => {
  2279. entries.forEach((entry) => {
  2280. //logger(entry);
  2281. if (entry.isIntersecting) {
  2282. var $targetNode = $(entry.target);
  2283.  
  2284. // Check if video?
  2285. if ($targetNode.find('video').length > 0) {
  2286. $childElement.find(".button_wrapper").append(ThumbnailElement);
  2287. initPostVideoFunction($mainElement);
  2288. }
  2289. else {
  2290. $childElement.find('.SNKMS_IG_THUMBNAIL_MAIN')?.remove();
  2291. }
  2292. }
  2293. });
  2294. };
  2295.  
  2296. const observer_i = new IntersectionObserver(checkVideoNodeCallback, {
  2297. root: $mainElement.find('div > ul._acay').first().parent().parent().parent()[0],
  2298. rootMargin: "0px",
  2299. threshold: 0.1,
  2300. });
  2301.  
  2302. // trigger when switching resources
  2303. // eslint-disable-next-line no-unused-vars
  2304. const observer = new MutationObserver(function (mutation, owner) {
  2305. var target = mutation.at(0)?.target;
  2306.  
  2307. $(target).find('li._acaz').each(function () {
  2308. observer_i.observe(this);
  2309. });
  2310. });
  2311.  
  2312. // first onload
  2313. $mainElement.find('div > ul li._acaz').each(function () {
  2314. observer_i.observe(this);
  2315. });
  2316.  
  2317.  
  2318. const element = $childElement.eq((tagName === "DIV") ? 0 : $childElement.length - 2).find('div > ul li._acaz')?.parent()[0];
  2319. const elementAttr = $childElement.eq((tagName === "DIV") ? 0 : $childElement.length - 2).find('div > ul li._acaz')?.parent().parent()[0];
  2320.  
  2321. if (element) {
  2322. observer.observe(element, {
  2323. childList: true
  2324. });
  2325. }
  2326.  
  2327. if (elementAttr) {
  2328. observer.observe(elementAttr, {
  2329. attributes: true
  2330. });
  2331. }
  2332. }
  2333. }, 50);
  2334.  
  2335.  
  2336. $childElement.css('position', 'relative');
  2337.  
  2338. initPostVideoFunction($mainElement);
  2339.  
  2340. GL_registerEventList.push({
  2341. element: this,
  2342. trigger: [
  2343. '.SNKMS_IG_THUMBNAIL_MAIN',
  2344. '.SNKMS_IG_NEWTAB_MAIN',
  2345. '.SNKMS_IG_DW_ALL_MAIN',
  2346. '.SNKMS_IG_DW_MAIN'
  2347. ]
  2348. });
  2349.  
  2350. $(this).on('click', '.SNKMS_IG_THUMBNAIL_MAIN', function () {
  2351. updateLoadingBar(true);
  2352.  
  2353. GL_username = $mainElement.attr('data-username');
  2354. GL_postPath = location.pathname.replace(/\/$/, '').split('/').at(-1) || $mainElement.find('a[href^="/p/"]').first().attr("href").split("/").at(2) || $(this).parent().parent().parent().children("div:last-child").children("div").children("div:last-child").find('a[href^="/p/"]').last().attr("href").split("/").at(2);
  2355.  
  2356. var index = getVisibleNodeIndex($mainElement);
  2357.  
  2358. IG_createDM(true, false);
  2359.  
  2360. createMediaListDOM(GL_postPath, ".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", "").then(() => {
  2361. let checkBlob = setInterval(() => {
  2362. if ($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0) {
  2363. clearInterval(checkBlob);
  2364. var $videoThumbnail = $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="' + (index + 1) + '"]')?.parent().find('.videoThumbnail')?.first();
  2365.  
  2366. if ($videoThumbnail != null && $videoThumbnail.length > 0) {
  2367. $videoThumbnail.click();
  2368. }
  2369. else {
  2370. alert('Can not find thumbnail url.');
  2371. }
  2372.  
  2373. updateLoadingBar(false);
  2374. $('.IG_SN_DIG').remove();
  2375. }
  2376. }, 250);
  2377. });
  2378. });
  2379.  
  2380. $(this).on('click', '.SNKMS_IG_NEWTAB_MAIN', function () {
  2381. updateLoadingBar(true);
  2382.  
  2383. GL_username = $mainElement.attr('data-username');
  2384. GL_postPath = location.pathname.replace(/\/$/, '').split('/').at(-1) || $mainElement.find('a[href^="/p/"]').first().attr("href").split("/").at(2) || $(this).parent().parent().parent().children("div:last-child").children("div").children("div:last-child").find('a[href^="/p/"]').last().attr("href").split("/").at(2);
  2385.  
  2386. var index = getVisibleNodeIndex($mainElement);
  2387.  
  2388. IG_createDM(true, false);
  2389.  
  2390. createMediaListDOM(GL_postPath, ".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", "").then(() => {
  2391. let checkBlob = setInterval(() => {
  2392. if ($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0) {
  2393. clearInterval(checkBlob);
  2394. var $linkElement = $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="' + (index + 1) + '"]');
  2395.  
  2396. if (USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && USER_SETTING.NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST) {
  2397. triggerLinkElement($linkElement.first()[0], true);
  2398. }
  2399. else {
  2400. let href = $linkElement?.attr('data-href');
  2401. if (href) {
  2402. // replace https://instagram.ftpe8-2.fna.fbcdn.net/ to https://scontent.cdninstagram.com/ becase of same origin policy (some video)
  2403. var urlObj = new URL(href);
  2404. urlObj.host = 'scontent.cdninstagram.com';
  2405.  
  2406. openNewTab(urlObj.href);
  2407. }
  2408. else {
  2409. alert('Can not find open tab url.');
  2410. }
  2411. }
  2412.  
  2413. updateLoadingBar(false);
  2414. $('.IG_SN_DIG').remove();
  2415. }
  2416. }, 250);
  2417. });
  2418. });
  2419.  
  2420. // Running if user click the download all icon
  2421. $(this).on('click', '.SNKMS_IG_DW_ALL_MAIN', async function () {
  2422. GL_username = $mainElement.attr('data-username');
  2423. GL_postPath = location.pathname.replace(/\/$/, '').split('/').at(-1) || $mainElement.find('a[href^="/p/"]').first().attr("href").split("/").at(2) || $(this).parent().parent().parent().children("div:last-child").children("div").children("div:last-child").find('a[href^="/p/"]').last().attr("href").split("/").at(2);
  2424.  
  2425. // Create element that download dailog
  2426. IG_createDM(USER_SETTING.DIRECT_DOWNLOAD_ALL, true);
  2427.  
  2428. $("#article-id").html(`<a href="https://www.instagram.com/p/${GL_postPath}">${GL_postPath}</a>`);
  2429.  
  2430. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function () {
  2431. $(this).wrap('<div></div>');
  2432. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  2433. $(this).after(`<div data-ih-locale-title="NEW_TAB" title="${_i18n("NEW_TAB")}" class="newTab">${SVG.NEW_TAB}</div>`);
  2434.  
  2435. if ($(this).attr('data-name') == 'video') {
  2436. $(this).after(`<div data-ih-locale-title="THUMBNAIL_INTRO" title="${_i18n("THUMBNAIL_INTRO")}" class="videoThumbnail">${SVG.THUMBNAIL}</div>`);
  2437. }
  2438. });
  2439.  
  2440.  
  2441. createMediaListDOM(GL_postPath, ".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", _i18n("LOAD_BLOB_MULTIPLE")).then(() => {
  2442. let checkBlob = setInterval(() => {
  2443. if ($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0) {
  2444. clearInterval(checkBlob);
  2445. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function () {
  2446. $(this).click();
  2447. });
  2448.  
  2449. $('.IG_SN_DIG').remove();
  2450. }
  2451. }, 250);
  2452. });
  2453. });
  2454.  
  2455. // Running if user click the download icon
  2456. $(this).on('click', '.SNKMS_IG_DW_MAIN', async function () {
  2457. GL_username = $mainElement.attr('data-username');
  2458. GL_postPath = location.pathname.replace(/\/$/, '').split('/').at(-1) || $mainElement.find('a[href^="/p/"]').first().attr("href").split("/").at(2) || $(this).parent().parent().parent().children("div:last-child").children("div").children("div:last-child").find('a[href^="/p/"]').last().attr("href").split("/").at(2);
  2459.  
  2460. // Create element that download dailog
  2461. IG_createDM(USER_SETTING.DIRECT_DOWNLOAD_ALL, true);
  2462.  
  2463. $("#article-id").html(`<a href="https://www.instagram.com/p/${GL_postPath}">${GL_postPath}</a>`);
  2464.  
  2465. if (USER_SETTING.DIRECT_DOWNLOAD_VISIBLE_RESOURCE) {
  2466. updateLoadingBar(true);
  2467. IG_setDM(true);
  2468.  
  2469. var index = getVisibleNodeIndex($(this).parent().parent().parent());
  2470.  
  2471. createMediaListDOM(GL_postPath, ".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", "").then(() => {
  2472. let checkBlob = setInterval(() => {
  2473. if ($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0) {
  2474. clearInterval(checkBlob);
  2475. var href = $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="' + (index + 1) + '"]')?.attr('data-href');
  2476.  
  2477. if (href) {
  2478. updateLoadingBar(false);
  2479. $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="' + (index + 1) + '"]')?.click();
  2480. }
  2481. else {
  2482. alert('Can not find download url.');
  2483. }
  2484.  
  2485. $('.IG_SN_DIG').remove();
  2486. }
  2487. }, 250);
  2488. });
  2489.  
  2490. return;
  2491. }
  2492.  
  2493. if (!USER_SETTING.DIRECT_DOWNLOAD_ALL) {
  2494. // Find video/image element and add the download icon
  2495. var s = 0;
  2496. var multiple = $(this).parent().parent().find(resourceCountSelector).length;
  2497. var blob = USER_SETTING.FORCE_FETCH_ALL_RESOURCES;
  2498. var publish_time = new Date($(this).parent().parent().find('a[href^="/p/"] time[datetime]').first().attr('datetime')).getTime();
  2499.  
  2500. // If posts have more than one images or videos.
  2501. if (multiple) {
  2502. $(this).parent().parent().find(resourceCountSelector).each(function () {
  2503. let element_videos = $(this).parent().parent().parent().find('video');
  2504. //if(element_videos && element_videos.attr('src') && element_videos.attr('src').match(/^blob:/ig)){
  2505. if (element_videos && element_videos.attr('src')) {
  2506. blob = true;
  2507. }
  2508. });
  2509.  
  2510.  
  2511. if (blob || USER_SETTING.FORCE_RESOURCE_VIA_MEDIA) {
  2512. createMediaListDOM(GL_postPath, ".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", _i18n("LOAD_BLOB_MULTIPLE"));
  2513. }
  2514. else {
  2515. $(this).parent().parent().find(resourceCountSelector).each(function () {
  2516. s++;
  2517. let element_videos = $(this).find('video');
  2518. let element_images = $(this).find('._aagv img');
  2519. let imgLink = (element_images.attr('srcset')) ? element_images.attr('srcset').split(" ")[0] : element_images.attr('src');
  2520.  
  2521. if (element_videos && element_videos.attr('src')) {
  2522. blob = true;
  2523. }
  2524. if (element_images && imgLink) {
  2525. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY').append(`<a datetime="${publish_time}" data-needed="direct" data-path="${GL_postPath}" data-name="photo" data-type="jpg" data-globalIndex="${s}" href="javascript:;" data-href="${imgLink}"><img width="100" src="${imgLink}" /><br/>- <span data-ih-locale="IMG">${_i18n("IMG")}</span> ${s} -</a>`);
  2526. }
  2527.  
  2528. });
  2529.  
  2530. if (blob) {
  2531. createMediaListDOM(GL_postPath, ".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", _i18n("LOAD_BLOB_RELOAD"));
  2532. }
  2533. }
  2534. }
  2535. else {
  2536. if (USER_SETTING.FORCE_RESOURCE_VIA_MEDIA) {
  2537. createMediaListDOM(GL_postPath, ".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", _i18n("LOAD_BLOB_MULTIPLE"));
  2538. }
  2539. else {
  2540. s++;
  2541. let element_videos = $(this).parent().parent().parent().find('video');
  2542. let element_images = $(this).parent().parent().parent().find('._aagv img');
  2543. let imgLink = (element_images.attr('srcset')) ? element_images.attr('srcset').split(" ")[0] : element_images.attr('src');
  2544.  
  2545.  
  2546. if (element_videos && element_videos.attr('src')) {
  2547. createMediaListDOM(GL_postPath, ".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", _i18n("LOAD_BLOB_ONE"));
  2548. }
  2549. if (element_images && imgLink) {
  2550. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY').append(`<a datetime="${publish_time}" data-needed="direct" data-path="${GL_postPath}" data-name="photo" data-type="jpg" data-globalIndex="${s}" href="javascript:;" href="" data-href="${imgLink}"><img width="100" src="${imgLink}" /><br/>- <span data-ih-locale="IMG">${_i18n("IMG")}</span> ${s} -</a>`);
  2551. }
  2552. }
  2553. }
  2554. }
  2555.  
  2556. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function () {
  2557. $(this).wrap('<div></div>');
  2558. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  2559. $(this).after(`<div data-ih-locale-title="NEW_TAB" title="${_i18n("NEW_TAB")}" class="newTab">${SVG.NEW_TAB}</div>`);
  2560.  
  2561. if ($(this).attr('data-name') == 'video') {
  2562. $(this).after(`<div data-ih-locale-title="THUMBNAIL_INTRO" title="${_i18n("THUMBNAIL_INTRO")}" class="videoThumbnail">${SVG.THUMBNAIL}</div>`);
  2563. }
  2564. });
  2565.  
  2566. if (USER_SETTING.DIRECT_DOWNLOAD_ALL) {
  2567. createMediaListDOM(GL_postPath, ".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", _i18n("LOAD_BLOB_MULTIPLE")).then(() => {
  2568. let checkBlob = setInterval(() => {
  2569. if ($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0) {
  2570. clearInterval(checkBlob);
  2571. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function () {
  2572. $(this).click();
  2573. });
  2574.  
  2575. $('.IG_SN_DIG').remove();
  2576. }
  2577. }, 250);
  2578. });
  2579. }
  2580. });
  2581.  
  2582. // Add the mark that download is ready
  2583. var username = $(this).find("header > div:last-child > div:first-child span a").first().text() || $(this).find('a[href^="/"]').filter(function () {
  2584. return $(this)?.text()?.length > 0;
  2585. }).first().text();
  2586.  
  2587. $(this).attr('data-snig', 'canDownload');
  2588. $(this).attr('data-username', username);
  2589. }
  2590. });
  2591. }
  2592.  
  2593. /**
  2594. * createMediaListDOM
  2595. * @description Create a list of media elements from post URLs
  2596. *
  2597. * @param {String} postURL
  2598. * @param {String} selector - Use CSS element selectors to choose where it appears.
  2599. * @param {String} message - i18n display loading message
  2600. * @return {void}
  2601. */
  2602. async function createMediaListDOM(postURL, selector, message) {
  2603. try {
  2604. $(`${selector} a`).remove();
  2605. $(selector).append('<p id="_SNLOAD">' + message + '</p>');
  2606. let result = await getBlobMedia(postURL);
  2607.  
  2608. if (result.type === 'query_hash') {
  2609. let idx = 1;
  2610. let media = result.data;
  2611. let resource = media.shortcode_media;
  2612.  
  2613. // GraphVideo
  2614. if (resource.__typename == "GraphVideo" && resource.video_url) {
  2615. $(selector).append(`<a media-id="${resource.id}" datetime="${resource.taken_at_timestamp}" data-blob="true" data-needed="direct" data-path="${resource.shortcode}" data-name="video" data-type="mp4" data-username="${resource.owner.username}" data-globalIndex="${idx}" href="javascript:;" data-href="${resource.video_url}"><img width="100" src="${resource.display_resources[1].src}" /><br/>- <span data-ih-locale="VID">${_i18n("VID")}</span> ${idx} -</a>`);
  2616. idx++;
  2617. }
  2618. // GraphImage
  2619. if (resource.__typename == "GraphImage") {
  2620. $(selector).append(`<a media-id="${resource.id}" datetime="${resource.taken_at_timestamp}" data-blob="true" data-needed="direct" data-path="${resource.shortcode}" data-name="photo" data-type="jpg" data-username="${resource.owner.username}" data-globalIndex="${idx}" href="javascript:;" data-href="${resource.display_resources[resource.display_resources.length - 1].src}"><img width="100" src="${resource.display_resources[1].src}" /><br/>- <span data-ih-locale="IMG">${_i18n("IMG")}</span> ${idx} -</a>`);
  2621. idx++;
  2622. }
  2623. // GraphSidecar
  2624. if (resource.__typename == "GraphSidecar" && resource.edge_sidecar_to_children) {
  2625. for (let e of resource.edge_sidecar_to_children.edges) {
  2626. if (e.node.__typename == "GraphVideo") {
  2627. $(selector).append(`<a media-id="${e.node.id}" datetime="${resource.taken_at_timestamp}" data-blob="true" data-needed="direct" data-path="${resource.shortcode}" data-name="video" data-type="mp4" data-username="${resource.owner.username}" data-globalIndex="${idx}" href="javascript:;" data-href="${e.node.video_url}"><img width="100" src="${e.node.display_resources[1].src}" /><br/>- <span data-ih-locale-title="VID">${_i18n("VID")}</span> ${idx} -</a>`);
  2628. }
  2629.  
  2630. if (e.node.__typename == "GraphImage") {
  2631. $(selector).append(`<a media-id="${e.node.id}" datetime="${resource.taken_at_timestamp}" data-blob="true" data-needed="direct" data-path="${resource.shortcode}" data-name="photo" data-type="jpg" data-username="${resource.owner.username}" data-globalIndex="${idx}" href="javascript:;" data-href="${e.node.display_resources[e.node.display_resources.length - 1].src}"><img width="100" src="${e.node.display_resources[1].src}" /><br/>- <span data-ih-locale="IMG">${_i18n("IMG")}</span> ${idx} -</a>`);
  2632. }
  2633. idx++;
  2634. }
  2635. }
  2636. }
  2637. else {
  2638. let resource = result.data;
  2639.  
  2640. if (resource.carousel_media) {
  2641. logger('carousel_media');
  2642.  
  2643. if (resource.owner == null && resource.user != null) {
  2644. resource.owner = resource.user;
  2645. }
  2646.  
  2647. if (resource.owner == null) {
  2648. logger('carousel_media:', 'undefined username');
  2649. alert('carousel_media: undefined username');
  2650. }
  2651.  
  2652. resource.carousel_media.forEach((mda, ind) => {
  2653. let idx = ind + 1;
  2654. // Image
  2655. if (mda.video_versions == null) {
  2656. mda.image_versions2.candidates.sort(function (a, b) {
  2657. let aSTP = new URL(a.url).searchParams.get('stp');
  2658. let bSTP = new URL(b.url).searchParams.get('stp');
  2659.  
  2660. if (aSTP && bSTP) {
  2661. if (aSTP.length > bSTP.length) return 1;
  2662. if (aSTP.length < bSTP.length) return -1;
  2663. }
  2664. else {
  2665. if (a.width < b.width) return 1;
  2666. if (a.width > b.width) return -1;
  2667. }
  2668.  
  2669. return 0;
  2670. });
  2671.  
  2672. $(selector).append(`<a media-id="${mda.pk}" datetime="${mda.taken_at}" data-blob="true" data-needed="direct" data-path="${resource.code}" data-name="photo" data-type="jpg" data-username="${resource.owner.username}" data-globalIndex="${idx}" href="javascript:;" data-href="${mda.image_versions2.candidates[0].url}"><img width="100" src="${mda.image_versions2.candidates[0].url}" /><br/>- <span data-ih-locale="IMG">${_i18n("IMG")}</span> ${idx} -</a>`);
  2673. }
  2674. // Video
  2675. else {
  2676. $(selector).append(`<a media-id="${mda.pk}" datetime="${mda.taken_at}" data-blob="true" data-needed="direct" data-path="${resource.code}" data-name="video" data-type="mp4" data-username="${resource.owner.username}" data-globalIndex="${idx}" href="javascript:;" data-href="${mda.video_versions[0].url}"><img width="100" src="${mda.image_versions2.candidates[0].url}" /><br/>- <span data-ih-locale="VID">${_i18n("VID")}</span> ${idx} -</a>`);
  2677. }
  2678. });
  2679. }
  2680. else {
  2681. let idx = 1;
  2682. // Image
  2683. if (resource.video_versions == null) {
  2684. resource.image_versions2.candidates.sort(function (a, b) {
  2685. let aSTP = new URL(a.url).searchParams.get('stp');
  2686. let bSTP = new URL(b.url).searchParams.get('stp');
  2687.  
  2688. if (aSTP && bSTP) {
  2689. if (aSTP.length > bSTP.length) return 1;
  2690. if (aSTP.length < bSTP.length) return -1;
  2691. }
  2692. else {
  2693. if (a.width < b.width) return 1;
  2694. if (a.width > b.width) return -1;
  2695. }
  2696.  
  2697. return 0;
  2698. });
  2699.  
  2700. $(selector).append(`<a media-id="${resource.pk}" datetime="${resource.taken_at}" data-blob="true" data-needed="direct" data-path="${resource.code}" data-name="photo" data-type="jpg" data-username="${resource.owner.username}" data-globalIndex="${idx}" href="javascript:;" data-href="${resource.image_versions2.candidates[0].url}"><img width="100" src="${resource.image_versions2.candidates[0].url}" /><br/>- <span data-ih-locale="IMG">${_i18n("IMG")}</span> ${idx} -</a>`);
  2701. }
  2702. // Video
  2703. else {
  2704. $(selector).append(`<a media-id="${resource.pk}" datetime="${resource.taken_at}" data-blob="true" data-needed="direct" data-path="${resource.code}" data-name="video" data-type="mp4" data-username="${resource.owner.username}" data-globalIndex="${idx}" href="javascript:;" data-href="${resource.video_versions[0].url}"><img width="100" src="${resource.image_versions2.candidates[0].url}" /><br/>- <span data-ih-locale="VID">${_i18n("VID")}</span> ${idx} -</a>`);
  2705. }
  2706. }
  2707. }
  2708.  
  2709. $("#_SNLOAD").remove();
  2710. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function () {
  2711. $(this).wrap('<div></div>');
  2712. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  2713. $(this).after(`<div data-ih-locale-title="NEW_TAB" title="${_i18n("NEW_TAB")}" class="newTab">${SVG.NEW_TAB}</div>`);
  2714.  
  2715. if ($(this).attr('data-name') == 'video') {
  2716. $(this).after(`<div data-ih-locale-title="THUMBNAIL_INTRO" title="${_i18n("THUMBNAIL_INTRO")}" class="videoThumbnail">${SVG.THUMBNAIL}</div>`);
  2717. }
  2718. });
  2719. }
  2720. catch (err) {
  2721. logger('createMediaListDOM', err);
  2722. };
  2723. }
  2724.  
  2725. /**
  2726. * IG_createDM
  2727. * @description A dialog showing a list of all media files in the post
  2728. *
  2729. * @param {Boolean} hasHidden
  2730. * @param {Boolean} hasCheckbox
  2731. * @return {void}
  2732. */
  2733. function IG_createDM(hasHidden, hasCheckbox) {
  2734. let isHidden = (hasHidden) ? "hidden" : "";
  2735. $('body').append('<div class="IG_SN_DIG ' + isHidden + '"><div class="IG_SN_DIG_BG"></div><div class="IG_SN_DIG_MAIN"><div class="IG_SN_DIG_TITLE"></div><div class="IG_SN_DIG_BODY"></div></div></div>');
  2736. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE').append(`<div style="position:relative;min-height:36px;text-align:center;margin-bottom: 7px;"><div style="position:absolute;left:0px;line-height: 18px;"><kbd>Alt</kbd>+<kbd>Q</kbd> [<span data-ih-locale="CLOSE">${_i18n("CLOSE")}</span>]</div><div style="line-height: 18px;">IG Helper</div><div id="post_info" style="line-height: 14px;font-size:14px;">Post ID: <span id="article-id"></span></div><div class="IG_SN_DIG_BTN">${SVG.CLOSE}</div></div>`);
  2737.  
  2738. if (hasCheckbox) {
  2739. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE').append(`<div style="text-align: center;" id="button_group"></div>`);
  2740. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE > div#button_group').append(`<button id="batch_download_selected" data-ih-locale="BATCH_DOWNLOAD_SELECTED">${_i18n('BATCH_DOWNLOAD_SELECTED')}</button>`);
  2741. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE > div#button_group').append(`<button id="batch_download_direct" data-ih-locale="BATCH_DOWNLOAD_DIRECT">${_i18n('BATCH_DOWNLOAD_DIRECT')}</button>`);
  2742. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE').append(`<label class="checkbox"><input value="yes" type="checkbox" /><span data-ih-locale="ALL_CHECK">${_i18n('ALL_CHECK')}</span></label>`);
  2743. }
  2744. }
  2745.  
  2746. /**
  2747. * IG_setDM
  2748. * @description Set a dialog status
  2749. *
  2750. * @param {Boolean} hasHidden
  2751. * @return {void}
  2752. */
  2753. function IG_setDM(hasHidden) {
  2754. if ($('.IG_SN_DIG').length) {
  2755. if (hasHidden) {
  2756. $('.IG_SN_DIG').addClass("hidden");
  2757. }
  2758. else {
  2759. $('.IG_SN_DIG').removeClass("hidden");
  2760. }
  2761. }
  2762. }
  2763.  
  2764. /**
  2765. * saveFiles
  2766. * @description Download the specified media URL to the computer
  2767. *
  2768. * @param {String} downloadLink
  2769. * @param {String} username
  2770. * @param {String} sourceType
  2771. * @param {Integer} timestamp
  2772. * @param {String} filetype
  2773. * @param {String} shortcode
  2774. * @return {Promise}
  2775. */
  2776. function saveFiles(downloadLink, username, sourceType, timestamp, filetype, shortcode) {
  2777. return new Promise((resolve) => {
  2778. setTimeout(() => {
  2779. updateLoadingBar(true);
  2780. fetch(downloadLink).then(res => {
  2781. return res.blob().then(dwel => {
  2782. updateLoadingBar(false);
  2783. createSaveFileElement(downloadLink, dwel, username, sourceType, timestamp, filetype, shortcode);
  2784.  
  2785. resolve(true);
  2786. });
  2787. });
  2788. }, 50);
  2789. });
  2790. }
  2791.  
  2792. /**
  2793. * createSaveFileElement
  2794. * @description Download the specified media with link element
  2795. *
  2796. * @param {String} downloadLink
  2797. * @param {Object} object
  2798. * @param {String} username
  2799. * @param {String} sourceType
  2800. * @param {Integer} timestamp
  2801. * @param {String} filetype
  2802. * @param {String} shortcode
  2803. * @return {void}
  2804. */
  2805. function createSaveFileElement(downloadLink, object, username, sourceType, timestamp, filetype, shortcode) {
  2806. timestamp = parseInt(timestamp.toString().padEnd(13, '0'));
  2807.  
  2808. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  2809. timestamp = parseInt(timestamp.toString().padEnd(13, '0'));
  2810. }
  2811.  
  2812. const date = new Date(timestamp);
  2813.  
  2814. const a = document.createElement("a");
  2815. const original_name = new URL(downloadLink).pathname.split('/').at(-1).split('.').slice(0, -1).join('.');
  2816. const year = date.getFullYear().toString();
  2817. const month = (date.getMonth() + 1).toString().padStart(2, '0');
  2818. const day = date.getDate().toString().padStart(2, '0');
  2819. const hour = date.getHours().toString().padStart(2, '0');
  2820. const minute = date.getMinutes().toString().padStart(2, '0');
  2821. const second = date.getSeconds().toString().padStart(2, '0');
  2822.  
  2823. var filename = RENAME_FORMAT.toUpperCase();
  2824. var format_shortcode = shortcode ?? "";
  2825. var replacements = {
  2826. '%USERNAME%': username,
  2827. '%SOURCE_TYPE%': sourceType,
  2828. '%SHORTCODE%': format_shortcode,
  2829. '%YEAR%': year,
  2830. '%2-YEAR%': year.substr(-2),
  2831. '%MONTH%': month,
  2832. '%DAY%': day,
  2833. '%HOUR%': hour,
  2834. '%MINUTE%': minute,
  2835. '%SECOND%': second,
  2836. '%ORIGINAL_NAME%': original_name,
  2837. '%ORIGINAL_NAME_FIRST%': original_name.split('_').at(0)
  2838. };
  2839.  
  2840. // eslint-disable-next-line no-useless-escape
  2841. filename = filename.replace(/%[\w\-]+%/g, function (str) {
  2842. return replacements[str] || str;
  2843. });
  2844.  
  2845. const originally = username + '_' + original_name + '.' + filetype;
  2846.  
  2847. a.href = URL.createObjectURL(object);
  2848. a.setAttribute("download", (USER_SETTING.AUTO_RENAME) ? filename + '.' + filetype : originally);
  2849. a.click();
  2850. a.remove();
  2851. }
  2852.  
  2853. /**
  2854. * triggerLinkElement
  2855. * @description Trigger the link element to start downloading the resource
  2856. *
  2857. * @param {Object} element
  2858. * @return {void}
  2859. */
  2860. async function triggerLinkElement(element, isPreview) {
  2861. let date = new Date().getTime();
  2862. let timestamp = Math.floor(date / 1000);
  2863. let username = ($(element).attr('data-username')) ? $(element).attr('data-username') : GL_username;
  2864.  
  2865. if (!username && $(element).attr('data-path')) {
  2866. logger('catching owner name from shortcode:', $(element).attr('data-href'));
  2867. username = await getPostOwner($(element).attr('data-path')).catch(err => {
  2868. logger('get username failed, replace with default string, error message:', err.message);
  2869. });
  2870.  
  2871. if (username == null) {
  2872. username = "NONE";
  2873. }
  2874. }
  2875.  
  2876. if (USER_SETTING.RENAME_PUBLISH_DATE && $(element).attr('datetime')) {
  2877. timestamp = parseInt($(element).attr('datetime'));
  2878. }
  2879.  
  2880. if (USER_SETTING.FORCE_RESOURCE_VIA_MEDIA) {
  2881. updateLoadingBar(true);
  2882. let result = await getMediaInfo($(element).attr('media-id'));
  2883. updateLoadingBar(false);
  2884.  
  2885. if (result.status === 'ok') {
  2886. var resource_url = null;
  2887. if (result.items[0].video_versions) {
  2888. resource_url = result.items[0].video_versions[0].url;
  2889. }
  2890. else {
  2891. result.items[0].image_versions2.candidates.sort(function (a, b) {
  2892. let aSTP = new URL(a.url).searchParams.get('stp');
  2893. let bSTP = new URL(b.url).searchParams.get('stp');
  2894.  
  2895. if (aSTP && bSTP) {
  2896. if (aSTP.length > bSTP.length) return 1;
  2897. if (aSTP.length < bSTP.length) return -1;
  2898. }
  2899. else {
  2900. if (a.width < b.width) return 1;
  2901. if (a.width > b.width) return -1;
  2902. }
  2903.  
  2904. return 0;
  2905. });
  2906.  
  2907. resource_url = result.items[0].image_versions2.candidates[0].url;
  2908. }
  2909.  
  2910. if (isPreview) {
  2911. let urlObj = new URL(resource_url);
  2912. urlObj.host = 'scontent.cdninstagram.com';
  2913.  
  2914. openNewTab(urlObj.href);
  2915. }
  2916. else {
  2917. saveFiles(resource_url, username, $(element).attr('data-name'), timestamp, $(element).attr('data-type'), $(element).attr('data-path'));
  2918. }
  2919. }
  2920. else {
  2921. if (USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT) {
  2922. if (isPreview) {
  2923. let urlObj = new URL($(element).attr('data-href'));
  2924. urlObj.host = 'scontent.cdninstagram.com';
  2925.  
  2926. openNewTab(urlObj.href);
  2927. }
  2928. else {
  2929. saveFiles($(element).attr('data-href'), username, $(element).attr('data-name'), timestamp, $(element).attr('data-type'), $(element).attr('data-path'));
  2930. }
  2931. }
  2932. else {
  2933. alert('Fetch failed from Media API. API response message: ' + result.message);
  2934. }
  2935. logger(result);
  2936. }
  2937. }
  2938. else {
  2939. saveFiles($(element).attr('data-href'), username, $(element).attr('data-name'), timestamp, $(element).attr('data-type'), $(element).attr('data-path'));
  2940. }
  2941. }
  2942.  
  2943. /**
  2944. * translateText
  2945. * @description i18n translation text
  2946. *
  2947. * @return {void}
  2948. */
  2949. function translateText() {
  2950. var eLocale = {
  2951. "en-US": {
  2952. "NOTICE_UPDATE_TITLE": "Wololo! New version released.",
  2953. "NOTICE_UPDATE_CONTENT": "IG-Helper has released a new version, click here to update.",
  2954. "CHECK_UPDATE": "Checking for Script Updates",
  2955. "CHECK_UPDATE_MENU": "Checking for Updates",
  2956. "CHECK_UPDATE_INTRO": "Check for updates when the script is triggered (check every 300 seconds).\nUpdate notifications will be sent as desktop notifications through the browser.",
  2957. "RELOAD_SCRIPT": "Reload Script",
  2958. "DONATE": "Donate",
  2959. "FEEDBACK": "Feedback",
  2960. "NEW_TAB": "Open in New Tab",
  2961. "SHOW_DOM_TREE": "Show DOM Tree",
  2962. "SELECT_AND_COPY": "Select All and Copy from the Input Box",
  2963. "DOWNLOAD_DOM_TREE": "Download DOM Tree as a Text File",
  2964. "REPORT_GITHUB": "Report an Issue on GitHub",
  2965. "REPORT_DISCORD": "Report an Issue on Discord Support Server",
  2966. "REPORT_FORK": "Report an Issue on Greasy Fork",
  2967. "DEBUG": "Debug Window",
  2968. "CLOSE": "Close",
  2969. "ALL_CHECK": "Select All",
  2970. "BATCH_DOWNLOAD_SELECTED": "Download Selected Resources",
  2971. "BATCH_DOWNLOAD_DIRECT": "Download All Resources",
  2972. "IMG": "Image",
  2973. "VID": "Video",
  2974. "DW": "Download",
  2975. "DW_ALL": "Download All Resources",
  2976. "THUMBNAIL_INTRO": "Download Video Thumbnail",
  2977. "LOAD_BLOB_ONE": "Loading Blob Media...",
  2978. "LOAD_BLOB_MULTIPLE": "Loading Blob Media and Others...",
  2979. "LOAD_BLOB_RELOAD": "Detecting Blob Media, reloading...",
  2980. "NO_CHECK_RESOURCE": "You need to select a resource to download.",
  2981. "NO_VID_URL": "Cannot find video URL.",
  2982. "SETTING": "Settings",
  2983. "AUTO_RENAME": "Automatically Rename Files (Right-Click to Set)",
  2984. "RENAME_SHORTCODE": "Rename the File and Include Shortcode",
  2985. "RENAME_PUBLISH_DATE": "Set Renamed File Timestamp to Resource Publish Date",
  2986. "RENAME_LOCATE_DATE": "Modify Renamed File Timestamp Date Format (Right-Click to Set)",
  2987. "DISABLE_VIDEO_LOOPING": "Disable Video Auto-looping",
  2988. "HTML5_VIDEO_CONTROL": "Display HTML5 Video Controller",
  2989. "REDIRECT_CLICK_USER_STORY_PICTURE": "Redirect When Clicking on User's Story Picture",
  2990. "FORCE_FETCH_ALL_RESOURCES": "Force Fetch All Resources in the Post",
  2991. "DIRECT_DOWNLOAD_VISIBLE_RESOURCE": "Directly Download the Visible Resources in the Post",
  2992. "DIRECT_DOWNLOAD_ALL": "Directly Download All Resources in the Post",
  2993. "MODIFY_VIDEO_VOLUME": "Modify Video Volume (Right-Click to Set)",
  2994. "SCROLL_BUTTON": "Enable Scroll Buttons for Reels Page",
  2995. "FORCE_RESOURCE_VIA_MEDIA": "Force Fetch Resource via Media API",
  2996. "USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT": "Use Alternative Methods to Download When the Media API is Not Accessible",
  2997. "NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST": "Always Use Media API for 'Open in New Tab' in Posts",
  2998. "AUTO_RENAME_INTRO": "Auto rename file to custom format:\nCustom Format List: \n%USERNAME% - Username\n%SOURCE_TYPE% - Download Source\n%SHORTCODE% - Post Shortcode\n%YEAR% - Year when downloaded/published\n%2-YEAR% - Year (last two digits) when downloaded/published\n%MONTH% - Month when downloaded/published\n%DAY% - Day when downloaded/published\n%HOUR% - Hour when downloaded/published\n%MINUTE% - Minute when downloaded/published\n%SECOND% - Second when downloaded/published\n%ORIGINAL_NAME% - Original name of downloaded file\n%ORIGINAL_NAME_FIRST% - Original name of downloaded file (first part of name)\n\nIf set to false, the file name will remain unchanged.\nExample: instagram_321565527_679025940443063_4318007696887450953_n.jpg",
  2999. "RENAME_SHORTCODE_INTRO": "Auto rename file to the following format:\nUSERNAME-TYPE-SHORTCODE-TIMESTAMP.FILETYPE\nExample: instagram-photo-CwkxyiVynpW-1670350000.jpg\n\nThis will ONLY work if [Automatically Rename Files] is set to TRUE.",
  3000. "RENAME_PUBLISH_DATE_INTRO": "Sets the timestamp in the file rename format to the resource publish date (browser time zone).\n\nThis feature only works when [Automatically Rename Files] is set to TRUE.",
  3001. "RENAME_LOCATE_DATE_INTRO": "Modify the renamed file timestamp date format to the browser's local time, and format it to your preferred regional date format.\n\nThis feature only works when [Automatically Rename Files] is set to TRUE.",
  3002. "DISABLE_VIDEO_LOOPING_INTRO": "Disable video auto-looping in Reels and posts.",
  3003. "HTML5_VIDEO_CONTROL_INTRO": "Display the HTML5 video controller in video resource.\n\nThis will hide the custom video volume slider and replace it with the HTML5 controller. The HTML5 controller can be hidden by right-clicking on the video to reveal the original details.",
  3004. "REDIRECT_CLICK_USER_STORY_PICTURE_INTRO": "Redirect to a user's profile page when right-clicking on their avatar in the story area on the homepage.\nIf you use the middle mouse button to click, it will open in a new tab.",
  3005. "FORCE_FETCH_ALL_RESOURCES_INTRO": "Force fetching of all resources (photos and videos) in a post via the Instagram API to remove the limit of three resources per post.",
  3006. "DIRECT_DOWNLOAD_VISIBLE_RESOURCE_INTRO": "Directly download the current resources available in the post.",
  3007. "DIRECT_DOWNLOAD_ALL_INTRO": "When you click the download button, all resources in the post will be forcibly fetched and downloaded.",
  3008. "MODIFY_VIDEO_VOLUME_INTRO": "Modify the video playback volume in Reels and posts (right-click to open the volume setting slider).",
  3009. "SCROLL_BUTTON_INTRO": "Enable scroll buttons for the lower right corner of the Reels page.",
  3010. "FORCE_RESOURCE_VIA_MEDIA_INTRO": "The Media API will try to get the highest quality photo or video possible, but it may take longer to load.",
  3011. "USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT_INTRO": "When the Media API reaches its rate limit or cannot be used for other reasons, the Forced Fetch API will be used to download resources (the resource quality may be slightly lower).",
  3012. "NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST_INTRO": "The [Open in New Tab] button in posts will always use the Media API to obtain high-resolution resources.",
  3013. "SKIP_VIEW_STORY_CONFIRM": "Skip the Confirmation Page for Viewing a Story/Highlight",
  3014. "SKIP_VIEW_STORY_CONFIRM_INTRO": "Automatically skip when confirmation page is shown in story or highlight."
  3015. }
  3016. };
  3017.  
  3018. var resultUnsorted = Object.assign({}, eLocale, locale);
  3019. var resultSorted = Object.keys(resultUnsorted).sort().reduce(
  3020. (obj, key) => {
  3021. obj[key] = resultUnsorted[key];
  3022. return obj;
  3023. }, {}
  3024. );
  3025.  
  3026. return resultSorted;
  3027. }
  3028.  
  3029. /**
  3030. * getTranslationText
  3031. * @description i18n translation text
  3032. *
  3033. * @param {String} lang
  3034. * @return {Object}
  3035. */
  3036. async function getTranslationText(lang) {
  3037. return new Promise((resolve, reject) => {
  3038. GM_xmlhttpRequest({
  3039. method: "GET",
  3040. url: `https://raw.githubusercontent.com/SN-Koarashi/ig-helper/master/locale/translations/${lang}.json`,
  3041. onload: function (response) {
  3042. try {
  3043. let obj = JSON.parse(response.response);
  3044. resolve(obj);
  3045. }
  3046. catch (err) {
  3047. reject(err);
  3048. }
  3049. },
  3050. onerror: function (err) {
  3051. logger('getTranslationText()', 'reject', err);
  3052. reject(err);
  3053. }
  3054. });
  3055. });
  3056. }
  3057.  
  3058. /**
  3059. * _i18n
  3060. * @description Perform i18n translation
  3061. *
  3062. * @param {String} text
  3063. * @return {void}
  3064. */
  3065. function _i18n(text) {
  3066. const translate = translateText();
  3067.  
  3068. if (translate[lang] != undefined && translate[lang][text] != undefined) {
  3069. return translate[lang][text];
  3070. }
  3071. else {
  3072. return translate["en-US"][text];
  3073. }
  3074. }
  3075.  
  3076. /**
  3077. * repaintingTranslations
  3078. * @description Perform i18n translation
  3079. *
  3080. * @return {void}
  3081. */
  3082. function repaintingTranslations() {
  3083. $('[data-ih-locale]').each(function () {
  3084. $(this).text(_i18n($(this).attr('data-ih-locale')));
  3085. });
  3086. $('[data-ih-locale-title]').each(function () {
  3087. $(this).attr('title', _i18n($(this).attr('data-ih-locale-title')));
  3088. });
  3089. }
  3090.  
  3091. /**
  3092. * registerMenuCommand
  3093. * @description register script menu command
  3094. *
  3095. * @return {void}
  3096. */
  3097. function registerMenuCommand() {
  3098. for (let id of GM_menuId) {
  3099. logger('GM_unregisterMenuCommand', id);
  3100. GM_unregisterMenuCommand(id);
  3101. }
  3102.  
  3103. GM_menuId.push(GM_registerMenuCommand(_i18n('SETTING'), () => {
  3104. showSetting();
  3105. }, {
  3106. accessKey: "w"
  3107. }));
  3108.  
  3109. GM_menuId.push(GM_registerMenuCommand(_i18n('DONATE'), () => {
  3110. GM_openInTab("https://ko-fi.com/snkoarashi", { active: true });
  3111. }, {
  3112. accessKey: "d"
  3113. }));
  3114.  
  3115. GM_menuId.push(GM_registerMenuCommand(_i18n('DEBUG'), () => {
  3116. showDebugDOM();
  3117. }, {
  3118. accessKey: "z"
  3119. }));
  3120.  
  3121. GM_menuId.push(GM_registerMenuCommand(_i18n('FEEDBACK'), () => {
  3122. showFeedbackDOM();
  3123. }, {
  3124. accessKey: "f"
  3125. }));
  3126.  
  3127. GM_menuId.push(GM_registerMenuCommand(_i18n('CHECK_UPDATE_MENU'), () => {
  3128. callNotification();
  3129. }, {
  3130. accessKey: "c"
  3131. }));
  3132.  
  3133. GM_menuId.push(GM_registerMenuCommand(_i18n('RELOAD_SCRIPT'), () => {
  3134. reloadScript();
  3135. }, {
  3136. accessKey: "r"
  3137. }));
  3138. }
  3139.  
  3140. /**
  3141. * checkingScriptUpdate
  3142. * @description Check if there is a new version of the script and push notification
  3143. *
  3144. * @param {Integer} interval
  3145. * @return {void}
  3146. */
  3147. function checkingScriptUpdate(interval) {
  3148. if (!USER_SETTING.CHECK_UPDATE) return;
  3149.  
  3150. const check_timestamp = GM_getValue('G_CHECK_TIMESTAMP') ?? new Date().getTime();
  3151. const now_time = new Date().getTime();
  3152.  
  3153. if (now_time > (parseInt(check_timestamp) + (interval * 1000))) {
  3154. GM_setValue('G_CHECK_TIMESTAMP', new Date().getTime());
  3155. callNotification();
  3156. }
  3157. }
  3158.  
  3159. /**
  3160. * callNotification
  3161. * @description call desktop notification by browser
  3162. *
  3163. * @return {void}
  3164. */
  3165. function callNotification() {
  3166. const currentVersion = GM_info.script.version;
  3167. const remoteScriptURL = 'https://raw.githubusercontent.com/SN-Koarashi/ig-helper/refs/heads/master/main.js';
  3168.  
  3169. GM_xmlhttpRequest({
  3170. method: "GET",
  3171. url: remoteScriptURL,
  3172. onload: function (response) {
  3173. const remoteScript = response.responseText;
  3174. const match = remoteScript.match(/\/\/\s+@version\s+([0-9.\-a-zA-Z]+)/i);
  3175.  
  3176. if (match && match[1]) {
  3177. const remoteVersion = match[1];
  3178. logger('Current version: ', currentVersion, '|', 'Remote version: ', remoteVersion);
  3179.  
  3180. if (remoteVersion !== currentVersion) {
  3181. GM_notification({
  3182. text: _i18n("NOTICE_UPDATE_CONTENT"),
  3183. title: _i18n("NOTICE_UPDATE_TITLE"),
  3184. tag: 'ig_helper_notice',
  3185. highlight: true,
  3186. timeout: 5000,
  3187. zombieTimeout: 5000,
  3188. image: "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Instagram_icon.png/64px-Instagram_icon.png",
  3189. onclick: (event) => {
  3190. event?.preventDefault();
  3191. var w = GM_openInTab(GM_info.script.downloadURL);
  3192. setTimeout(() => {
  3193. w.close();
  3194. }, 250);
  3195. }
  3196. });
  3197. } else {
  3198. logger('there is no new update');
  3199. }
  3200. } else {
  3201. console.error('Could not find version in the remote script.');
  3202. }
  3203. }
  3204. });
  3205. }
  3206.  
  3207. /**
  3208. * showSetting
  3209. * @description Show script settings window
  3210. *
  3211. * @return {void}
  3212. */
  3213. function showSetting() {
  3214. $('.IG_SN_DIG').remove();
  3215. IG_createDM();
  3216. $('.IG_SN_DIG #post_info').text('Preference Settings');
  3217.  
  3218. $('.IG_SN_DIG .IG_SN_DIG_TITLE > div').append('<select id="langSelect"></select><div style="font-size: 12px;">Some texts are machine-translated and may be inaccurate; translation contributions are welcome on GitHub.</div>');
  3219.  
  3220. for (let o in locale_manifest) {
  3221. $('.IG_SN_DIG .IG_SN_DIG_TITLE > div #langSelect').append(`<option value="${o}" ${(lang == o) ? 'selected' : ''}>${locale_manifest[o]}</option>`);
  3222. }
  3223.  
  3224. for (let name in USER_SETTING) {
  3225. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<label class="globalSettings${(CHILD_NODES.includes(name)) ? ' child' : ''}" title="${_i18n(name + '_INTRO')}" data-ih-locale-title="${name + '_INTRO'}"><span data-ih-locale="${name}">${_i18n(name)}</span> <input id="${name}" value="box" type="checkbox" ${(USER_SETTING[name] === true) ? 'checked' : ''}><div class="chbtn"><div class="rounds"></div></div></label>`);
  3226.  
  3227. if (name === 'MODIFY_VIDEO_VOLUME') {
  3228. $('.IG_SN_DIG .IG_SN_DIG_BODY input[id="' + name + '"]').parent('label').on('contextmenu', function (e) {
  3229. e.preventDefault();
  3230. if ($(this).find('#tempWrapper').length === 0) {
  3231. $(this).append('<div id="tempWrapper"></div>');
  3232. $(this).children('#tempWrapper').append('<input value="' + VIDEO_VOLUME + '" type="range" min="0" max="1" step="0.05" />');
  3233. $(this).children('#tempWrapper').append('<input value="' + VIDEO_VOLUME + '" step="0.05" type="number" />');
  3234. $(this).children('#tempWrapper').append(`<div class="IG_SN_DIG_BTN">${SVG.CLOSE}</div>`);
  3235. }
  3236. });
  3237. }
  3238.  
  3239. if (name === 'AUTO_RENAME') {
  3240. $('.IG_SN_DIG .IG_SN_DIG_BODY input[id="' + name + '"]').parent('label').on('contextmenu', function (e) {
  3241. e.preventDefault();
  3242. if ($(this).find('#tempWrapper').length === 0) {
  3243. $(this).append('<div id="tempWrapper"></div>');
  3244.  
  3245. $(this).children('#tempWrapper').append('<input id="date_format" value="' + RENAME_FORMAT + '" />');
  3246. $(this).children('#tempWrapper').append(`<div class="IG_SN_DIG_BTN">${SVG.CLOSE}</div>`);
  3247. }
  3248. });
  3249. }
  3250. }
  3251. }
  3252.  
  3253. /**
  3254. * showDebugDOM
  3255. * @description Show full DOM tree
  3256. *
  3257. * @return {void}
  3258. */
  3259. function showDebugDOM() {
  3260. $('.IG_SN_DIG').remove();
  3261. IG_createDM();
  3262. $('.IG_SN_DIG #post_info').text('IG Debug DOM Tree');
  3263.  
  3264. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<textarea style="font-family: monospace;width:100%;box-sizing: border-box;height:300px;background: transparent;" readonly></textarea>`);
  3265. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<span style="display:block;text-align:center;">`);
  3266. $('.IG_SN_DIG .IG_SN_DIG_BODY span').append(`<button style="margin: 3px;" class="IG_DISPLAY_DOM_TREE"><a>${_i18n('SHOW_DOM_TREE')}</a></button>`);
  3267. $('.IG_SN_DIG .IG_SN_DIG_BODY span').append(`<button style="margin: 3px;" class="IG_SELECT_DOM_TREE"><a>${_i18n('SELECT_AND_COPY')}</a></button>`);
  3268. $('.IG_SN_DIG .IG_SN_DIG_BODY span').append(`<button style="margin: 3px;" class="IG_DOWNLOAD_DOM_TREE"><a>${_i18n('DOWNLOAD_DOM_TREE')}</a></button><br/>`);
  3269. $('.IG_SN_DIG .IG_SN_DIG_BODY span').append(`<button style="margin: 3px;" class="IG_REPORT_GITHUB"><a href="https://github.com/SN-Koarashi/ig-helper/issues" target="_blank">${_i18n('REPORT_GITHUB')}</a></button>`);
  3270. $('.IG_SN_DIG .IG_SN_DIG_BODY span').append(`<button style="margin: 3px;" class="IG_REPORT_DISCORD"><a href="https://discord.gg/q3KT4hdq8x" target="_blank">${_i18n('REPORT_DISCORD')}</a></button>`);
  3271. }
  3272.  
  3273. /**
  3274. * showFeedbackDOM
  3275. * @description Show feedback options
  3276. *
  3277. * @return {void}
  3278. */
  3279. function showFeedbackDOM() {
  3280. $('.IG_SN_DIG').remove();
  3281. IG_createDM();
  3282. $('.IG_SN_DIG #post_info').text('Feedback Options');
  3283.  
  3284. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<span style="display:block;text-align:center;">`);
  3285. $('.IG_SN_DIG .IG_SN_DIG_BODY span').append(`<button style="margin: 3px;" class="IG_REPORT_FORK"><a href="https://greasyfork.org/en/scripts/404535-ig-helper/feedback" target="_blank">${_i18n('REPORT_FORK')}</a></button>`);
  3286. $('.IG_SN_DIG .IG_SN_DIG_BODY span').append(`<button style="margin: 3px;" class="IG_REPORT_GITHUB"><a href="https://github.com/SN-Koarashi/ig-helper/issues" target="_blank">${_i18n('REPORT_GITHUB')}</a></button>`);
  3287. $('.IG_SN_DIG .IG_SN_DIG_BODY span').append(`<button style="margin: 3px;" class="IG_REPORT_DISCORD"><a href="https://discord.gg/q3KT4hdq8x" target="_blank">${_i18n('REPORT_DISCORD')}</a></button>`);
  3288. }
  3289.  
  3290. /**
  3291. * openNewTab
  3292. * @description Open url in new tab
  3293. *
  3294. * @param {String} link
  3295. * @return {void}
  3296. */
  3297. function openNewTab(link) {
  3298. var a = document.createElement('a');
  3299. a.href = link;
  3300. a.target = '_blank';
  3301.  
  3302. document.body.appendChild(a);
  3303. a.click();
  3304. a.remove();
  3305. }
  3306.  
  3307. /**
  3308. * reloadScript
  3309. * @description Re-register main timer
  3310. *
  3311. * @return {void}
  3312. */
  3313. function reloadScript() {
  3314. clearInterval(GL_repeat);
  3315.  
  3316. // unregister event in post element
  3317. GL_registerEventList.forEach(item => {
  3318. item.trigger.forEach(bindElement => {
  3319. $(item.element).off('click', bindElement);
  3320. });
  3321. });
  3322. GL_registerEventList = [];
  3323.  
  3324. $('.button_wrapper').remove();
  3325. $('.IG_DWPROFILE, .IG_DWPROFILE, .IG_DWSTORY, .IG_DWSTORY_ALL, .IG_DWSTORY_THUMBNAIL, .IG_DWNEWTAB, .IG_DWHISTORY, .IG_DWHISTORY_ALL, .IG_DWHINEWTAB, .IG_DWHISTORY_THUMBNAIL, .IG_REELS, .IG_REELS_NEWTAB, .IG_REELS_THUMBNAIL').remove();
  3326. $('[data-snig]').removeAttr('data-snig');
  3327.  
  3328. pageLoaded = false;
  3329. firstStarted = false;
  3330. currentURL = location.href;
  3331. GL_observer.disconnect();
  3332.  
  3333. logger('main timer re-register completed');
  3334. }
  3335.  
  3336. /**
  3337. * logger
  3338. * @description event record
  3339. *
  3340. * @return {void}
  3341. */
  3342. function logger(...messages) {
  3343. var dd = new Date();
  3344. GL_logger.push({
  3345. time: dd.getTime(),
  3346. content: [...messages]
  3347. });
  3348.  
  3349. if (GL_logger.length > 1000) {
  3350. GL_logger = [{
  3351. time: dd.getTime(),
  3352. content: ['logger sliced']
  3353. }, ...GL_logger.slice(-999)];
  3354. }
  3355.  
  3356. console.log(`[${dd.toISOString()}]`, ...messages);
  3357. }
  3358.  
  3359. /**
  3360. * initSettings
  3361. * @description Initialize preferences
  3362. *
  3363. * @return {void}
  3364. */
  3365. function initSettings() {
  3366. for (let name in USER_SETTING) {
  3367. if (GM_getValue(name) != null && typeof GM_getValue(name) === 'boolean') {
  3368. USER_SETTING[name] = GM_getValue(name);
  3369.  
  3370. if (name === "MODIFY_VIDEO_VOLUME" && GM_getValue(name) !== true) {
  3371. VIDEO_VOLUME = 1;
  3372. }
  3373. }
  3374. }
  3375. }
  3376.  
  3377. /**
  3378. * toggleVolumeSilder
  3379. * @description Toggle display of custom volume slider.
  3380. *
  3381. * @param {object} $videos
  3382. * @param {object} $buttonParent
  3383. * @param {string} loggerType
  3384. * @param {string} customClass
  3385. * @return {void}
  3386. */
  3387. function toggleVolumeSilder($videos, $buttonParent, loggerType, customClass = "") {
  3388. if ($buttonParent.find('div.volume_slider').length === 0) {
  3389. $buttonParent.append(`<div class="volume_slider ${customClass}" />`);
  3390. $buttonParent.find('div.volume_slider').append(`<div><input type="range" max="1" min="0" step="0.05" value="${VIDEO_VOLUME}" /></div>`);
  3391. $buttonParent.find('div.volume_slider input').attr('style', `--ig-track-progress: ${(VIDEO_VOLUME * 100) + '%'}`);
  3392. $buttonParent.find('div.volume_slider input').on('input', function () {
  3393. var percent = ($(this).val() * 100) + '%';
  3394.  
  3395. VIDEO_VOLUME = $(this).val();
  3396. GM_setValue('G_VIDEO_VOLUME', $(this).val());
  3397.  
  3398. $(this).attr('style', `--ig-track-progress: ${percent}`);
  3399.  
  3400. $videos.each(function () {
  3401. logger(`(${loggerType})`, 'video volume changed #slider');
  3402. this.volume = VIDEO_VOLUME;
  3403. });
  3404. });
  3405.  
  3406. $buttonParent.find('div.volume_slider input').on('mouseenter', function () {
  3407. var percent = (VIDEO_VOLUME * 100) + '%';
  3408. $(this).attr('style', `--ig-track-progress: ${percent}`);
  3409. $(this).val(VIDEO_VOLUME);
  3410.  
  3411.  
  3412. $videos.each(function () {
  3413. logger(`(${loggerType})`, 'video volume changed #slider');
  3414. this.volume = VIDEO_VOLUME;
  3415. });
  3416. });
  3417.  
  3418. $buttonParent.find('div.volume_slider').on('click', function (e) {
  3419. e.stopPropagation();
  3420. e.preventDefault();
  3421. });
  3422. }
  3423. else {
  3424. $buttonParent.find('div.volume_slider').remove();
  3425. }
  3426. }
  3427.  
  3428. // Running if document is ready
  3429. $(function () {
  3430. function ConvertDOM(domEl) {
  3431. var obj = [];
  3432. for (var ele of domEl) {
  3433. obj.push({
  3434. tagName: ele.tagName,
  3435. id: ele.id,
  3436. className: ele.className
  3437. });
  3438. }
  3439.  
  3440. return obj;
  3441. }
  3442.  
  3443. function setDOMTreeContent() {
  3444. let text = $('div[id^="mount"]')[0];
  3445. var logger = "";
  3446. GL_logger.forEach(log => {
  3447. var jsonData = JSON.stringify(log.content, function (key, value) {
  3448. if (Array.isArray(this)) {
  3449. if (typeof value === "object" && value instanceof jQuery) {
  3450. return ConvertDOM(value);
  3451. }
  3452. return value;
  3453. }
  3454. else {
  3455. return value;
  3456. }
  3457. }, "\t");
  3458. logger += `${log.time}: ${jsonData}\n`
  3459. });
  3460. $('.IG_SN_DIG .IG_SN_DIG_BODY textarea').text("Logger:\n" + logger + "\n-----\n\nLocation: " + location.pathname + "\nDOM Tree with div#mount:\n" + text.innerHTML);
  3461. }
  3462.  
  3463. $('body').on('click', '.IG_SN_DIG .IG_SN_DIG_BODY .IG_DISPLAY_DOM_TREE', function () {
  3464. setDOMTreeContent();
  3465. });
  3466.  
  3467. $('body').on('click', '.IG_SN_DIG .IG_SN_DIG_BODY .IG_SELECT_DOM_TREE', function () {
  3468. $('.IG_SN_DIG .IG_SN_DIG_BODY textarea').select();
  3469. document.execCommand('copy');
  3470. });
  3471.  
  3472. $('body').on('click', '.IG_SN_DIG .IG_SN_DIG_BODY .IG_DOWNLOAD_DOM_TREE', function () {
  3473. if ($('.IG_SN_DIG .IG_SN_DIG_BODY textarea').text().length === 0) {
  3474. setDOMTreeContent();
  3475. }
  3476.  
  3477. var text = $('.IG_SN_DIG .IG_SN_DIG_BODY textarea').text();
  3478. var a = document.createElement("a");
  3479. var file = new Blob([text], { type: "text/plain" });
  3480. a.href = URL.createObjectURL(file);
  3481. a.download = "DOMTree-" + new Date().getTime() + ".txt";
  3482.  
  3483. document.body.appendChild(a);
  3484. a.click();
  3485. a.remove();
  3486. });
  3487.  
  3488. // Close the download dialog if user click the close icon
  3489. $('body').on('click', '.IG_SN_DIG_BTN, .IG_SN_DIG_BG', function () {
  3490. if ($(this).parent('#tempWrapper').length > 0) {
  3491. $(this).parent('#tempWrapper').fadeOut(250, function () {
  3492. $(this).remove();
  3493. });
  3494. }
  3495. else {
  3496. $('.IG_SN_DIG').remove();
  3497. }
  3498. });
  3499.  
  3500. $(window).keydown(function (e) {
  3501. // Hot key [Alt+Q] to close the download dialog
  3502. if (e.keyCode == '81' && e.altKey) {
  3503. $('.IG_SN_DIG').remove();
  3504. e.preventDefault();
  3505. }
  3506. // Hot key [Alt+W] to open the settings dialog
  3507. if (e.keyCode == '87' && e.altKey) {
  3508. showSetting();
  3509. e.preventDefault();
  3510. }
  3511.  
  3512. // Hot key [Alt+Z] to open the settings dialog
  3513. if (e.keyCode == '90' && e.altKey) {
  3514. showDebugDOM();
  3515. e.preventDefault();
  3516. }
  3517.  
  3518. // Hot key [Alt+R] to open the settings dialog
  3519. if (e.keyCode == '82' && e.altKey) {
  3520. reloadScript();
  3521. e.preventDefault();
  3522. }
  3523.  
  3524. // Hot key [Alt+S] to download story/highlights resource
  3525. if (e.keyCode == '83' && e.altKey) {
  3526. if (location.href.match(/^(https:\/\/www\.instagram\.com\/stories\/)/ig) && $('.IG_DWSTORY').length > 0) {
  3527. $('.IG_DWSTORY')?.click();
  3528. }
  3529. if (location.href.match(/^(https:\/\/www\.instagram\.com\/stories\/highlights\/)/ig) && $('.IG_DWHISTORY').length > 0) {
  3530. $('.IG_DWHISTORY')?.click();
  3531. }
  3532. e.preventDefault();
  3533. }
  3534. });
  3535.  
  3536. $('body').on('change', '.IG_SN_DIG input', function (e) {
  3537. var name = $(this).attr('id');
  3538.  
  3539. if (name && USER_SETTING[name] !== undefined) {
  3540. let isChecked = $(this).prop('checked');
  3541. GM_setValue(name, isChecked);
  3542. USER_SETTING[name] = isChecked;
  3543.  
  3544. console.log('user settings', name, isChecked);
  3545. }
  3546. });
  3547.  
  3548. $('body').on('click', '.IG_SN_DIG .globalSettings', function (e) {
  3549. if ($(this).find('#tempWrapper').length > 0) {
  3550. e.preventDefault();
  3551. }
  3552. });
  3553.  
  3554. $('body').on('change', '.IG_SN_DIG #tempWrapper input:not(#date_format)', function () {
  3555. let value = $(this).val();
  3556.  
  3557. if ($(this).attr('type') == 'range') {
  3558. $(this).next().val(value);
  3559. }
  3560. else {
  3561. $(this).prev().val(value);
  3562. }
  3563.  
  3564. if (value >= 0 && value <= 1) {
  3565. VIDEO_VOLUME = value;
  3566. GM_setValue('G_VIDEO_VOLUME', value);
  3567. }
  3568. });
  3569.  
  3570. $('body').on('input', '.IG_SN_DIG #tempWrapper input:not(#date_format)', function (e) {
  3571. if ($(this).attr('type') == 'range') {
  3572. let value = $(this).val();
  3573. $(this).next().val(value);
  3574. }
  3575. else {
  3576. let value = $(this).val();
  3577. if (value >= 0 && value <= 1) {
  3578. $(this).prev().val(value);
  3579. }
  3580. else {
  3581. if (value < 0) {
  3582. $(this).val(0);
  3583. }
  3584. else {
  3585. $(this).val(1);
  3586. }
  3587. }
  3588. }
  3589. });
  3590.  
  3591. $('body').on('input', '.IG_SN_DIG #tempWrapper input#date_format', function (e) {
  3592. GM_setValue('G_RENAME_FORMAT', $(this).val());
  3593. RENAME_FORMAT = $(this).val();
  3594. });
  3595.  
  3596. $('body').on('click', 'a[data-needed="direct"]', function (e) {
  3597. e.preventDefault();
  3598. triggerLinkElement(this);
  3599. });
  3600.  
  3601. $('body').on('click', '.IG_SN_DIG_BODY .newTab', function () {
  3602. // replace https://instagram.ftpe8-2.fna.fbcdn.net/ to https://scontent.cdninstagram.com/ becase of same origin policy (some video)
  3603.  
  3604. if (USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && USER_SETTING.NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST) {
  3605. triggerLinkElement($(this).parent().children('a').first()[0], true);
  3606. }
  3607. else {
  3608. var urlObj = new URL($(this).parent().children('a').attr('data-href'));
  3609. urlObj.host = 'scontent.cdninstagram.com';
  3610.  
  3611. openNewTab(urlObj.href);
  3612. }
  3613. });
  3614.  
  3615. $('body').on('click', '.IG_SN_DIG_BODY .videoThumbnail', function () {
  3616. let timestamp = new Date().getTime();
  3617.  
  3618. if (USER_SETTING.RENAME_PUBLISH_DATE && $(this).parent().children('a').attr('datetime')) {
  3619. timestamp = $(this).parent().children('a').attr('datetime');
  3620. }
  3621.  
  3622. let postPath = $(this).parent().children('a').attr('data-path') ?? $('#article-id').text();
  3623.  
  3624. saveFiles($(this).parent().children('a').find('img').first().attr('src'), $(this).parent().children('a').attr('data-username'), 'thumbnail', timestamp, 'jpg', postPath);
  3625. });
  3626.  
  3627. // Running if user left-click download icon in stories
  3628. $('body').on('click', '.IG_DWSTORY', function () {
  3629. onStory(true);
  3630. });
  3631.  
  3632. // Running if user left-click all download icon in stories
  3633. $('body').on('click', '.IG_DWSTORY_ALL', function () {
  3634. onStoryAll();
  3635. });
  3636.  
  3637. // Running if user left-click 'open in new tab' icon in stories
  3638. $('body').on('click', '.IG_DWNEWTAB', function (e) {
  3639. e.preventDefault();
  3640. onStory(true, true, true);
  3641. });
  3642.  
  3643. // Running if user left-click download thumbnail icon in stories
  3644. $('body').on('click', '.IG_DWSTORY_THUMBNAIL', function () {
  3645. onStoryThumbnail(true);
  3646. });
  3647.  
  3648. // Running if user left-click download icon in profile
  3649. $('body').on('click', '.IG_DWPROFILE', function (e) {
  3650. e.stopPropagation();
  3651. onProfileAvatar(true);
  3652. });
  3653.  
  3654. // Running if user left-click download icon in highlight stories
  3655. $('body').on('click', '.IG_DWHISTORY', function () {
  3656. onHighlightsStory(true);
  3657. });
  3658.  
  3659. // Running if user left-click all download icon in highlight stories
  3660. $('body').on('click', '.IG_DWHISTORY_ALL', function () {
  3661. onHighlightsStoryAll();
  3662. });
  3663.  
  3664. // Running if user left-click 'open in new tab' icon in highlight stories
  3665. $('body').on('click', '.IG_DWHINEWTAB', function (e) {
  3666. e.preventDefault();
  3667. onHighlightsStory(true, true);
  3668. });
  3669.  
  3670. // Running if user left-click thumbnail download icon in highlight stories
  3671. $('body').on('click', '.IG_DWHISTORY_THUMBNAIL', function () {
  3672. onHighlightsStoryThumbnail(true);
  3673. });
  3674.  
  3675. // Running if user left-click download icon in reels
  3676. $('body').on('click', '.IG_REELS', function () {
  3677. onReels(true, true);
  3678. });
  3679.  
  3680. // Running if user left-click newtab icon in reels
  3681. $('body').on('click', '.IG_REELS_NEWTAB', function () {
  3682. onReels(true, true, true);
  3683. });
  3684.  
  3685. // Running if user left-click download icon in reels
  3686. $('body').on('click', '.IG_REELS_THUMBNAIL', function () {
  3687. onReels(true, false);
  3688. });
  3689.  
  3690. // Running if user right-click profile picture in stories area
  3691. $('body').on('mousedown', 'button[role="menuitem"], div[role="menuitem"]', function (e) {
  3692. // Right-Click || Middle-Click
  3693. if (e.which === 3 || e.which === 2) {
  3694. if (location.href === 'https://www.instagram.com/' && USER_SETTING.REDIRECT_CLICK_USER_STORY_PICTURE) {
  3695. e.preventDefault();
  3696. if ($(this).find('canvas._aarh, canvas + span > img').length > 0) {
  3697. const targetUrl = 'https://www.instagram.com/' + $(this).children('div').last().text();
  3698. if (e.which === 2) {
  3699. GM_openInTab(targetUrl);
  3700. }
  3701. else {
  3702. location.href = targetUrl;
  3703. }
  3704. }
  3705. }
  3706. }
  3707. });
  3708.  
  3709. $('body').on('change', '.IG_SN_DIG_TITLE .checkbox', function () {
  3710. var isChecked = $(this).find('input').prop('checked');
  3711. $('.IG_SN_DIG_BODY .inner_box').each(function () {
  3712. $(this).prop('checked', isChecked);
  3713. });
  3714. });
  3715.  
  3716. $('body').on('change', '.IG_SN_DIG_BODY .inner_box', function () {
  3717. var checked = $('.IG_SN_DIG_BODY .inner_box:checked').length;
  3718. var total = $('.IG_SN_DIG_BODY .inner_box').length;
  3719.  
  3720.  
  3721. $('.IG_SN_DIG_TITLE .checkbox').find('input').prop('checked', checked == total);
  3722. });
  3723.  
  3724. $('body').on('click', '.IG_SN_DIG_TITLE #batch_download_selected', function () {
  3725. let index = 0;
  3726. $('.IG_SN_DIG_BODY a[data-needed="direct"]').each(function () {
  3727. if ($(this).prev().children('input').prop('checked')) {
  3728. $(this).click();
  3729. index++;
  3730. }
  3731. });
  3732.  
  3733. if (index == 0) {
  3734. alert(_i18n('NO_CHECK_RESOURCE'));
  3735. }
  3736. });
  3737.  
  3738. $('body').on('change', '.IG_SN_DIG_TITLE #langSelect', function () {
  3739. GM_setValue('lang', $(this).val());
  3740. lang = $(this).val();
  3741.  
  3742. if (lang?.startsWith('en') || locale[lang] != null) {
  3743. repaintingTranslations();
  3744. registerMenuCommand();
  3745. }
  3746. else {
  3747. getTranslationText(lang).then((res) => {
  3748. locale[lang] = res;
  3749. repaintingTranslations();
  3750. registerMenuCommand();
  3751. }).catch((err) => {
  3752. console.error('getTranslationText catch error:', err);
  3753. });
  3754. }
  3755. });
  3756.  
  3757. $('body').on('change', '.IG_SN_DIG_BODY #locateSelect', function () {
  3758. $('#locatePreview').text(`${(new Date().toLocaleString($(this).val(), { hour12: false, second: "2-digit", minute: "2-digit", hour: "2-digit", month: "2-digit", day: "2-digit", year: "numeric" })).replaceAll('/', '-')}`);
  3759. LOCATE_DATE_FORMAT = $(this).val();
  3760. GM_setValue('G_LOCATE_DATE_FORMAT', $(this).val());
  3761. });
  3762.  
  3763. $('body').on('click', '.IG_SN_DIG_TITLE #batch_download_direct', function () {
  3764. $('.IG_SN_DIG_BODY a[data-needed="direct"]').each(function () {
  3765. $(this).click();
  3766. });
  3767. });
  3768.  
  3769.  
  3770. const audio_observer = new MutationObserver((mutationsList) => {
  3771. for (const mutation of mutationsList) {
  3772. if (mutation.type === 'childList') {
  3773. mutation.addedNodes.forEach((node) => {
  3774. const $videos = $(node).find('video');
  3775. if ($videos.length > 0) {
  3776. // Modify video volume
  3777. if (USER_SETTING.MODIFY_VIDEO_VOLUME) {
  3778. $videos.each(function () {
  3779. $(this).on('play playing', function () {
  3780. if (!$(this).data('modify')) {
  3781. $(this).attr('data-modify', true);
  3782. this.volume = VIDEO_VOLUME;
  3783. logger('(audio_observer) Added video event listener #modify');
  3784. }
  3785. });
  3786. });
  3787. }
  3788.  
  3789. if (location.pathname.match(/^(\/stories\/)/ig)) {
  3790. const isHighlight = location.pathname.match(/^(\/stories\/highlights\/)/ig) != null;
  3791. const storyType = isHighlight ? 'highlight' : 'story';
  3792.  
  3793. $videos.each(function () {
  3794. $(this).on('timeupdate', function () {
  3795. if (!$(this).data('modify-thumbnail')) {
  3796. let $video = $(this);
  3797. if ($video.parents('div[style][class]').filter(function () {
  3798. return $(this).width() == $video.width();
  3799. }).find('.IG_DWSTORY_THUMBNAIL, .IG_DWHISTORY_THUMBNAIL').length === 0) {
  3800. $(this).attr('data-modify-thumbnail', true);
  3801.  
  3802. if (isHighlight) {
  3803. onHighlightsStoryThumbnail(false);
  3804. }
  3805. else {
  3806. onStoryThumbnail(false);
  3807. }
  3808.  
  3809. logger(`(${storyType})`, 'Manually inserting thumbnail button');
  3810. }
  3811. else {
  3812. $(this).attr('data-modify-thumbnail', true);
  3813. logger(`(${storyType})`, 'Thumbnail button already inserted');
  3814. }
  3815. }
  3816. });
  3817.  
  3818. var $video = $(this);
  3819.  
  3820. if (USER_SETTING.HTML5_VIDEO_CONTROL) {
  3821. if (!$video.data('controls')) {
  3822. logger(`(${storyType})`, 'Added video html5 contorller #modify');
  3823.  
  3824. if (USER_SETTING.MODIFY_VIDEO_VOLUME) {
  3825. this.volume = VIDEO_VOLUME;
  3826.  
  3827. $video.on('loadstart', function () {
  3828. this.volume = VIDEO_VOLUME;
  3829. });
  3830. }
  3831.  
  3832. let $videoParent = $video.parents('div').filter(function () {
  3833. return $(this).attr('class') == null && $(this).attr('style') == null;
  3834. }).first();
  3835.  
  3836. // story bottom bar
  3837. let $bottomBar = $videoParent.next();
  3838. $bottomBar.hide();
  3839.  
  3840. // read more button in center
  3841. let $readMoreButton = $videoParent.find('div[class][role="button"]');
  3842. $readMoreButton.hide();
  3843.  
  3844. const hideContextmenu = function (e) {
  3845. e.preventDefault();
  3846. $video.css('z-index', '2');
  3847. $video.attr('controls', true);
  3848.  
  3849. $readMoreButton.hide();
  3850. $bottomBar.hide();
  3851.  
  3852. toggleVolumeSilder($video, $video.parents('div[style][class]').filter(function () {
  3853. return $(this).width() == $video.width();
  3854. }).first(), storyType, 'vertical');
  3855. };
  3856.  
  3857. // Hide layout to show controller
  3858. $video.parent().find('video + div').on('contextmenu', hideContextmenu);
  3859. $readMoreButton.on('contextmenu', hideContextmenu);
  3860. $bottomBar.on('contextmenu', hideContextmenu);
  3861.  
  3862. // Restore layout to show details interface
  3863. $video.on('contextmenu', function (e) {
  3864. e.preventDefault();
  3865. $video.css('z-index', '-1');
  3866. $video.removeAttr('controls');
  3867.  
  3868. $bottomBar.show();
  3869. $readMoreButton.show();
  3870.  
  3871. toggleVolumeSilder($video, $video.parents('div[style][class]').filter(function () {
  3872. return $(this).width() == $video.width();
  3873. }).first(), storyType, 'vertical');
  3874. });
  3875.  
  3876. $video.on('volumechange', function () {
  3877. // This is mute/unmute's icon
  3878. let $element_mute_button = $videoParent.parent().find('svg > path[d^="M1.5 13.3c-.8 0-1.5.7-1.5 1.5v18.4c0"], svg > path[d^="M16.636 7.028a1.5 1.5"]').parents('[role="button"]').first();
  3879.  
  3880. var is_elelment_muted = $element_mute_button.find('svg > path[d^="M16.636"]').length === 0;
  3881.  
  3882. if (this.muted != is_elelment_muted) {
  3883. this.volume = VIDEO_VOLUME;
  3884. $element_mute_button?.click();
  3885. }
  3886.  
  3887. if ($(this).attr('data-completed')) {
  3888. VIDEO_VOLUME = this.volume;
  3889. GM_setValue('G_VIDEO_VOLUME', this.volume);
  3890. }
  3891.  
  3892. if (this.volume == VIDEO_VOLUME) {
  3893. $(this).attr('data-completed', true);
  3894. }
  3895. });
  3896.  
  3897. $video.css('position', 'absolute');
  3898. $video.css('z-index', '2');
  3899. $video.attr('data-controls', true);
  3900. $video.attr('controls', true);
  3901. }
  3902. }
  3903. else {
  3904. toggleVolumeSilder($video, $video.parents('div[style][class]').filter(function () {
  3905. return $(this).width() == $video.width();
  3906. }).first(), storyType, 'vertical');
  3907. }
  3908. });
  3909. }
  3910. }
  3911. });
  3912. }
  3913. }
  3914. });
  3915.  
  3916. audio_observer.observe($('div[id^="mount"]')[0], {
  3917. childList: true,
  3918. subtree: true,
  3919. });
  3920. });
  3921. })(jQuery);