IG小助手

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

当前为 2025-03-26 提交的版本,查看 最新版本

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