IG Helper

Downloading is possible for both photos and videos from posts, as well as for stories, reels or profile picture.

Verze ze dne 25. 04. 2025. Zobrazit nejnovější verzi.

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