IG Helper

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

2025-03-05 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

  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.0
  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($(this).parent().parent().find('a[href^="/p/"] time[datetime]').first().attr('datetime')).getTime();
  1135.  
  1136. // If posts have more than one images or videos.
  1137. if (multiple) {
  1138. $(this).parent().parent().find(resourceCountSelector).each(function () {
  1139. let element_videos = $(this).parent().parent().parent().find('video');
  1140. //if(element_videos && element_videos.attr('src') && element_videos.attr('src').match(/^blob:/ig)){
  1141. if (element_videos && element_videos.attr('src')) {
  1142. blob = true;
  1143. }
  1144. });
  1145.  
  1146.  
  1147. if (blob || USER_SETTING.FORCE_RESOURCE_VIA_MEDIA) {
  1148. createMediaListDOM(state.GL_postPath, ".IG_POPUP_DIG .IG_POPUP_DIG_MAIN .IG_POPUP_DIG_BODY", _i18n("LOAD_BLOB_MULTIPLE"));
  1149. }
  1150. else {
  1151. $(this).parent().parent().find(resourceCountSelector).each(function () {
  1152. s++;
  1153. let element_videos = $(this).find('video');
  1154. let element_images = $(this).find('._aagv img');
  1155. let imgLink = (element_images.attr('srcset')) ? element_images.attr('srcset').split(" ")[0] : element_images.attr('src');
  1156.  
  1157. if (element_videos && element_videos.attr('src')) {
  1158. blob = true;
  1159. }
  1160. if (element_images && imgLink) {
  1161. $('.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>`);
  1162. }
  1163.  
  1164. });
  1165.  
  1166. if (blob) {
  1167. createMediaListDOM(state.GL_postPath, ".IG_POPUP_DIG .IG_POPUP_DIG_MAIN .IG_POPUP_DIG_BODY", _i18n("LOAD_BLOB_RELOAD"));
  1168. }
  1169. }
  1170. }
  1171. else {
  1172. if (USER_SETTING.FORCE_RESOURCE_VIA_MEDIA) {
  1173. createMediaListDOM(state.GL_postPath, ".IG_POPUP_DIG .IG_POPUP_DIG_MAIN .IG_POPUP_DIG_BODY", _i18n("LOAD_BLOB_MULTIPLE"));
  1174. }
  1175. else {
  1176. s++;
  1177. let element_videos = $(this).parent().parent().parent().find('video');
  1178. let element_images = $(this).parent().parent().parent().find('._aagv img');
  1179. let imgLink = (element_images.attr('srcset')) ? element_images.attr('srcset').split(" ")[0] : element_images.attr('src');
  1180.  
  1181.  
  1182. if (element_videos && element_videos.attr('src')) {
  1183. createMediaListDOM(state.GL_postPath, ".IG_POPUP_DIG .IG_POPUP_DIG_MAIN .IG_POPUP_DIG_BODY", _i18n("LOAD_BLOB_ONE"));
  1184. }
  1185. if (element_images && imgLink) {
  1186. $('.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>`);
  1187. }
  1188. }
  1189. }
  1190. }
  1191.  
  1192. $('.IG_POPUP_DIG .IG_POPUP_DIG_MAIN .IG_POPUP_DIG_BODY a').each(function () {
  1193. $(this).wrap('<div></div>');
  1194. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  1195. $(this).after(`<div data-ih-locale-title="NEW_TAB" title="${_i18n("NEW_TAB")}" class="newTab">${SVG.NEW_TAB}</div>`);
  1196.  
  1197. if ($(this).attr('data-name') == 'video') {
  1198. $(this).after(`<div data-ih-locale-title="THUMBNAIL_INTRO" title="${_i18n("THUMBNAIL_INTRO")}" class="videoThumbnail">${SVG.THUMBNAIL}</div>`);
  1199. }
  1200. });
  1201.  
  1202. if (USER_SETTING.DIRECT_DOWNLOAD_ALL) {
  1203. createMediaListDOM(state.GL_postPath, ".IG_POPUP_DIG .IG_POPUP_DIG_MAIN .IG_POPUP_DIG_BODY", _i18n("LOAD_BLOB_MULTIPLE")).then(() => {
  1204. let checkBlob = setInterval(() => {
  1205. if ($('.IG_POPUP_DIG .IG_POPUP_DIG_MAIN .IG_POPUP_DIG_BODY a').length > 0) {
  1206. clearInterval(checkBlob);
  1207. $('.IG_POPUP_DIG .IG_POPUP_DIG_MAIN .IG_POPUP_DIG_BODY a').each(function () {
  1208. $(this).trigger("click");
  1209. });
  1210.  
  1211. $('.IG_POPUP_DIG').remove();
  1212. }
  1213. }, 250);
  1214. });
  1215. }
  1216. });
  1217.  
  1218. // Add the mark that download is ready
  1219. var username = $(this).find("header > div:last-child > div:first-child span a").first().text() || $(this).find('a[href^="/"]').filter(function () {
  1220. return $(this)?.text()?.length > 0;
  1221. }).first().text();
  1222.  
  1223. $(this).attr('data-snig', 'canDownload');
  1224. $(this).attr('data-username', username);
  1225. }
  1226. });
  1227. }
  1228.  
  1229.  
  1230. /**
  1231. * filterResourceData
  1232. * @description Standardized resource object format
  1233. *
  1234. * @param {Object} data
  1235. * @return {Object}
  1236. */
  1237. function filterResourceData(data) {
  1238. var resource = data.shortcode_media ?? data;
  1239. if (resource.owner == null && resource.user != null) {
  1240. resource.owner = resource.user;
  1241. }
  1242.  
  1243. if (resource.owner == null) {
  1244. logger('carousel_media:', 'undefined username');
  1245. alert('carousel_media: undefined username');
  1246. }
  1247.  
  1248. return resource;
  1249. }
  1250.  
  1251.  
  1252. /**
  1253. * createMediaListDOM
  1254. * @description Create a list of media elements from post URLs
  1255. *
  1256. * @param {String} postURL
  1257. * @param {String} selector - Use CSS element selectors to choose where it appears.
  1258. * @param {String} message - i18n display loading message
  1259. * @return {void}
  1260. */
  1261. async function createMediaListDOM(postURL, selector, message) {
  1262. try {
  1263. $(`${selector} a`).remove();
  1264. $(selector).append('<p id="_SNLOAD">' + message + '</p>');
  1265. let result = await getBlobMedia(postURL);
  1266. let resource = filterResourceData(result.data);
  1267.  
  1268. if (result.type === 'query_hash') {
  1269. let idx = 1;
  1270.  
  1271. // GraphVideo
  1272. if (resource.__typename == "GraphVideo" && resource.video_url) {
  1273. $(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>`);
  1274. idx++;
  1275. }
  1276. // GraphImage
  1277. if (resource.__typename == "GraphImage") {
  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="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>`);
  1279. idx++;
  1280. }
  1281. // GraphSidecar
  1282. if (resource.__typename == "GraphSidecar" && resource.edge_sidecar_to_children) {
  1283. for (let e of resource.edge_sidecar_to_children.edges) {
  1284. if (e.node.__typename == "GraphVideo") {
  1285. $(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>`);
  1286. }
  1287.  
  1288. if (e.node.__typename == "GraphImage") {
  1289. $(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>`);
  1290. }
  1291. idx++;
  1292. }
  1293. }
  1294. }
  1295. else {
  1296. if (resource.carousel_media) {
  1297. logger('carousel_media');
  1298.  
  1299. resource.carousel_media.forEach((mda, ind) => {
  1300. let idx = ind + 1;
  1301. // Image
  1302. if (mda.video_versions == null) {
  1303. mda.image_versions2.candidates.sort(function (a, b) {
  1304. let aSTP = new URL(a.url).searchParams.get('stp');
  1305. let bSTP = new URL(b.url).searchParams.get('stp');
  1306.  
  1307. if (aSTP && bSTP) {
  1308. if (aSTP.length > bSTP.length) return 1;
  1309. if (aSTP.length < bSTP.length) return -1;
  1310. }
  1311. else {
  1312. if (a.width < b.width) return 1;
  1313. if (a.width > b.width) return -1;
  1314. }
  1315.  
  1316. return 0;
  1317. });
  1318.  
  1319. $(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>`);
  1320. }
  1321. // Video
  1322. else {
  1323. $(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>`);
  1324. }
  1325. });
  1326. }
  1327. else {
  1328. let idx = 1;
  1329. // Image
  1330. if (resource.video_versions == null) {
  1331. resource.image_versions2.candidates.sort(function (a, b) {
  1332. let aSTP = new URL(a.url).searchParams.get('stp');
  1333. let bSTP = new URL(b.url).searchParams.get('stp');
  1334.  
  1335. if (aSTP && bSTP) {
  1336. if (aSTP.length > bSTP.length) return 1;
  1337. if (aSTP.length < bSTP.length) return -1;
  1338. }
  1339. else {
  1340. if (a.width < b.width) return 1;
  1341. if (a.width > b.width) return -1;
  1342. }
  1343.  
  1344. return 0;
  1345. });
  1346.  
  1347. $(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>`);
  1348. }
  1349. // Video
  1350. else {
  1351. $(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>`);
  1352. }
  1353. }
  1354. }
  1355.  
  1356. $("#_SNLOAD").remove();
  1357. $('.IG_POPUP_DIG .IG_POPUP_DIG_MAIN .IG_POPUP_DIG_BODY a').each(function () {
  1358. $(this).wrap('<div></div>');
  1359. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  1360. $(this).after(`<div data-ih-locale-title="NEW_TAB" title="${_i18n("NEW_TAB")}" class="newTab">${SVG.NEW_TAB}</div>`);
  1361.  
  1362. if ($(this).attr('data-name') == 'video') {
  1363. $(this).after(`<div data-ih-locale-title="THUMBNAIL_INTRO" title="${_i18n("THUMBNAIL_INTRO")}" class="videoThumbnail">${SVG.THUMBNAIL}</div>`);
  1364. }
  1365. });
  1366. }
  1367. catch (err) {
  1368. logger('createMediaListDOM', err);
  1369. };
  1370. }
  1371.  
  1372.  
  1373. /**
  1374. * getVisibleNodeIndex
  1375. * @description Get element visible node
  1376. *
  1377. * @param {Object} $main
  1378. * @return {Integer}
  1379. */
  1380. function getVisibleNodeIndex($main) {
  1381. var index = 0;
  1382. // homepage classList
  1383. var $dot = $main.find('.x1iyjqo2 > div > div:last-child > div');
  1384.  
  1385. // dialog classList, main top classList
  1386. if ($dot == null || !$dot.hasClass('_acnb')) {
  1387. $dot = $main.find('._aatk > div > div:last-child').eq(0).children('div');
  1388. }
  1389.  
  1390. $dot.filter('._acnb').each(function (sIndex) {
  1391. if ($(this).hasClass('_acnf')) {
  1392. index = sIndex;
  1393. }
  1394. });
  1395.  
  1396. return index;
  1397. }
  1398.  
  1399. /**
  1400. * onProfileAvatar
  1401. * @description Trigger user avatar download event or button display event.
  1402. *
  1403. * @param {Boolean} isDownload - Check if it is a download operation
  1404. * @return {void}
  1405. */
  1406. async function onProfileAvatar(isDownload) {
  1407. if (isDownload) {
  1408. updateLoadingBar(true);
  1409.  
  1410. let date = new Date().getTime();
  1411. let timestamp = Math.floor(date / 1000);
  1412. let username = location.pathname.replaceAll(/(reels|tagged)\/$/ig, '').split('/').filter(s => s.length > 0).at(-1);
  1413. let userInfo = await getUserId(username);
  1414.  
  1415. try {
  1416. let dataURL = await getUserHighSizeProfile(userInfo.user.pk);
  1417. saveFiles(dataURL, username, "avatar", timestamp, 'jpg');
  1418. }
  1419. // eslint-disable-next-line no-unused-vars
  1420. catch (err) {
  1421. saveFiles(userInfo.user.profile_pic_url, username, "avatar", timestamp, 'jpg');
  1422. }
  1423.  
  1424. updateLoadingBar(false);
  1425. }
  1426. else {
  1427. // Add the profile download button
  1428. if (!$('.IG_DWPROFILE').length) {
  1429. let profileTimer = setInterval(() => {
  1430. if ($('.IG_DWPROFILE').length) {
  1431. clearInterval(profileTimer);
  1432. return;
  1433. }
  1434.  
  1435. $('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>`);
  1436. $('header > *[class]:first-child img[alt][draggable]').parent().parent().css('position', 'relative');
  1437. $('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>`);
  1438. $('header > *[class]:first-child img[alt]:not([draggable])').parent().parent().parent().css('position', 'relative');
  1439. }, 150);
  1440. }
  1441. }
  1442. }
  1443.  
  1444. /**
  1445. * onReels
  1446. * @description Trigger user's reels download event or button display event.
  1447. *
  1448. * @param {Boolean} isDownload - Check if it is a download operation
  1449. * @param {Boolean} isVideo - Check if reel is a video element
  1450. * @param {Boolean} isPreview - Check if it is need to open new tab
  1451. * @return {void}
  1452. */
  1453. async function onReels(isDownload, isVideo, isPreview) {
  1454. if (isDownload) {
  1455. updateLoadingBar(true);
  1456.  
  1457. let reelsPath = location.href.split('?').at(0).split('instagram.com/reels/').at(-1).replaceAll('/', '');
  1458. let result = await getBlobMedia(reelsPath);
  1459. let media = filterResourceData(result.data);
  1460.  
  1461. let timestamp = new Date().getTime();
  1462.  
  1463. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1464. if (result.type === 'query_hash') {
  1465. timestamp = media.shortcode_media.taken_at_timestamp;
  1466. }
  1467. else {
  1468. timestamp = media.taken_at;
  1469. }
  1470. }
  1471.  
  1472. if (result.type === 'query_hash') {
  1473. if (isVideo && media.shortcode_media.is_video) {
  1474. if (isPreview) {
  1475. openNewTab(media.shortcode_media.video_url);
  1476. }
  1477. else {
  1478. let type = 'mp4';
  1479. saveFiles(media.shortcode_media.video_url, media.shortcode_media.owner.username, "reels", timestamp, type, reelsPath);
  1480. }
  1481. }
  1482. else {
  1483. if (isPreview) {
  1484. openNewTab(media.shortcode_media.display_resources.at(-1).src);
  1485. }
  1486. else {
  1487. let type = 'jpg';
  1488. saveFiles(media.shortcode_media.display_resources.at(-1).src, media.shortcode_media.owner.username, "reels", timestamp, type, reelsPath);
  1489. }
  1490. }
  1491. }
  1492. else {
  1493. if (isVideo && media.video_versions != null) {
  1494. if (isPreview) {
  1495. openNewTab(media.video_versions[0].url);
  1496. }
  1497. else {
  1498. let type = 'mp4';
  1499. saveFiles(media.video_versions[0].url, media.owner.username, "reels", timestamp, type, reelsPath);
  1500. }
  1501. }
  1502. else {
  1503. if (isPreview) {
  1504. openNewTab(media.image_versions2.candidates[0].url);
  1505. }
  1506. else {
  1507. let type = 'jpg';
  1508. saveFiles(media.image_versions2.candidates[0].url, media.owner.username, "reels", timestamp, type, reelsPath);
  1509. }
  1510. }
  1511. }
  1512.  
  1513. updateLoadingBar(false);
  1514. }
  1515. else {
  1516. //$('.IG_REELS_THUMBNAIL, .IG_REELS').remove();
  1517. var timer = setInterval(() => {
  1518. if ($('section > main[role="main"] > div div.x1qjc9v5 video').length > 0) {
  1519. clearInterval(timer);
  1520.  
  1521. if (USER_SETTING.SCROLL_BUTTON) {
  1522. $('#scrollWrapper').remove();
  1523. $('section > main[role="main"]').append('<section id="scrollWrapper"></section>');
  1524. $('section > main[role="main"] > #scrollWrapper').append('<div class="button-up"><div></div></div>');
  1525. $('section > main[role="main"] > #scrollWrapper').append('<div class="button-down"><div></div></div>');
  1526.  
  1527. $('section > main[role="main"] > #scrollWrapper > .button-up').on('click', function () {
  1528. $('section > main[role="main"] > div')[0].scrollBy({ top: -30, behavior: "smooth" });
  1529. });
  1530. $('section > main[role="main"] > #scrollWrapper > .button-down').on('click', function () {
  1531. $('section > main[role="main"] > div')[0].scrollBy({ top: 30, behavior: "smooth" });
  1532. });
  1533. }
  1534.  
  1535. // reels scroll has [tabindex] but header not.
  1536. $('section > main[role="main"] > div[tabindex]').children('div').each(function () {
  1537. if ($(this).children().length > 0) {
  1538. if (!$(this).children().find('.IG_REELS').length) {
  1539. var $main = $(this);
  1540.  
  1541. $(this).children().css('position', 'relative');
  1542.  
  1543. $(this).children().append(`<div data-ih-locale-title="DW" title="${_i18n("DW")}" class="IG_REELS">${SVG.DOWNLOAD}</div>`);
  1544. $(this).children().append(`<div data-ih-locale-title="NEW_TAB" title="${_i18n("NEW_TAB")}" class="IG_REELS_NEWTAB">${SVG.NEW_TAB}</div>`);
  1545. $(this).children().append(`<div data-ih-locale-title="THUMBNAIL_INTRO" title="${_i18n("THUMBNAIL_INTRO")}" class="IG_REELS_THUMBNAIL">${SVG.THUMBNAIL}</div>`);
  1546.  
  1547. // Disable video autoplay
  1548. if (USER_SETTING.DISABLE_VIDEO_LOOPING) {
  1549. $(this).find('video').each(function () {
  1550. $(this).on('ended', function () {
  1551. if (!$(this).data('loop')) {
  1552. let $element_play_button = $(this).next().find('div[role="presentation"] > div svg > path[d^="M5.888"]').parents('button[role="button"], div[role="button"]');
  1553. if ($element_play_button.length > 0) {
  1554. $(this).attr('data-loop', true);
  1555. $element_play_button.trigger("click");
  1556. logger('Adding video event listener #loop, then paused click()');
  1557. }
  1558. else {
  1559. $(this).attr('data-loop', true);
  1560. $(this).parent().find('.xpgaw4o').removeAttr('style');
  1561. this.pause();
  1562. logger('Adding video event listener #loop, then paused pause()');
  1563. }
  1564. }
  1565. });
  1566. });
  1567. }
  1568.  
  1569. // Modify video volume
  1570. //if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  1571. // $(this).find('video').each(function(){
  1572. // $(this).on('play playing', function(){
  1573. // if(!$(this).data('modify')){
  1574. // $(this).attr('data-modify', true);
  1575. // this.volume = VIDEO_VOLUME;
  1576. // logger('(reel) Added video event listener #modify');
  1577. // }
  1578. // });
  1579. // });
  1580. //}
  1581.  
  1582. if (USER_SETTING.HTML5_VIDEO_CONTROL) {
  1583. $(this).find('video').each(function () {
  1584. if (!$(this).data('controls')) {
  1585. let $video = $(this);
  1586.  
  1587. logger('(reel) Added video html5 contorller #modify');
  1588.  
  1589. if (USER_SETTING.MODIFY_VIDEO_VOLUME) {
  1590. this.volume = state.videoVolume;
  1591.  
  1592. $(this).on('loadstart', function () {
  1593. this.volume = state.videoVolume;
  1594. });
  1595. }
  1596.  
  1597. // Restore layout to show details interface
  1598. $(this).on('contextmenu', function (e) {
  1599. e.preventDefault();
  1600. $video.css('z-index', '-1');
  1601. $video.removeAttr('controls');
  1602. });
  1603.  
  1604. // Hide layout to show controller
  1605. $(this).parent().find('video + div div[role="button"]').filter(function () {
  1606. return $(this).parent('div[role="presentation"]').length > 0 && $(this).css('cursor') === 'pointer' && $(this).attr('style') != null;
  1607. }).first().on('contextmenu', function (e) {
  1608. e.preventDefault();
  1609. $video.css('z-index', '2');
  1610. $video.attr('controls', true);
  1611. });
  1612.  
  1613.  
  1614. $(this).on('volumechange', function () {
  1615. // eslint-disable-next-line no-unused-vars
  1616. let $element_mute_button = $(this).parent().find('video + div > div').find('button[type="button"], div[role="button"]').filter(function (idx) {
  1617. // This is mute/unmute's icon
  1618. 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;
  1619. });
  1620.  
  1621. var is_elelment_muted = $element_mute_button.find('svg > path[d^="M16.636"]').length === 0;
  1622.  
  1623. if (this.muted != is_elelment_muted) {
  1624. this.volume = state.videoVolume;
  1625. $element_mute_button?.trigger("click");
  1626. }
  1627.  
  1628. if ($(this).attr('data-completed')) {
  1629. state.videoVolume = this.volume;
  1630. GM_setValue('G_VIDEO_VOLUME', this.volume);
  1631. }
  1632.  
  1633. if (this.volume == state.videoVolume) {
  1634. $(this).attr('data-completed', true);
  1635. }
  1636. });
  1637.  
  1638. $(this).css('position', 'absolute');
  1639. $(this).css('z-index', '2');
  1640. $(this).attr('data-controls', true);
  1641. $(this).attr('controls', true);
  1642. }
  1643. });
  1644. }
  1645.  
  1646. var $videos = $main.find('video');
  1647. var $buttonParent = $(this).find('div[role="presentation"] > div[role="button"] > div').first();
  1648. toggleVolumeSilder($videos, $buttonParent, 'reel');
  1649. }
  1650. }
  1651. });
  1652. }
  1653. }, 250);
  1654. }
  1655. }
  1656.  
  1657. /**
  1658. * onStoryAll
  1659. * @description Trigger user's story all download event.
  1660. *
  1661. * @return {void}
  1662. */
  1663. async function onStoryAll() {
  1664. updateLoadingBar(true);
  1665.  
  1666. let date = new Date().getTime();
  1667. let timestamp = Math.floor(date / 1000);
  1668. let username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split("/").filter(s => s.length > 0).at(1);
  1669.  
  1670. let userInfo = await getUserId(username);
  1671. let userId = userInfo.user.pk;
  1672. let stories = await getStories(userId);
  1673.  
  1674. let complete = 0;
  1675. setDownloadProgress(complete, stories.data.reels_media[0].items.length);
  1676.  
  1677. stories.data.reels_media[0].items.forEach((item, idx) => {
  1678. setTimeout(() => {
  1679. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1680. timestamp = item.taken_at_timestamp;
  1681. }
  1682.  
  1683. item.display_resources.sort(function (a, b) {
  1684. if (a.config_width < b.config_width) return 1;
  1685. if (a.config_width > b.config_width) return -1;
  1686. return 0;
  1687. });
  1688.  
  1689. if (item.is_video) {
  1690. saveFiles(item.video_resources[0].src, username, "stories", timestamp, 'mp4', item.id).then(() => {
  1691. setDownloadProgress(++complete, stories.data.reels_media[0].items.length);
  1692. });
  1693. }
  1694. else {
  1695. saveFiles(item.display_resources[0].src, username, "stories", timestamp, 'jpg', item.id).then(() => {
  1696. setDownloadProgress(++complete, stories.data.reels_media[0].items.length);
  1697. });
  1698. }
  1699. }, 100 * idx);
  1700. });
  1701. }
  1702.  
  1703. /**
  1704. * onStory
  1705. * @description Trigger user's story download event or button display event.
  1706. *
  1707. * @param {Boolean} isDownload - Check if it is a download operation
  1708. * @param {Boolean} isForce - Check if downloading directly from API instead of cache
  1709. * @param {Boolean} isPreview - Check if it is need to open new tab
  1710. * @return {void}
  1711. */
  1712. async function onStory(isDownload, isForce, isPreview) {
  1713. var username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split("/").filter(s => s.length > 0).at(1);
  1714. if (isDownload) {
  1715. let date = new Date().getTime();
  1716. let timestamp = Math.floor(date / 1000);
  1717.  
  1718. updateLoadingBar(true);
  1719. if (USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !state.tempFetchRateLimit) {
  1720. let mediaId = null;
  1721.  
  1722. let userInfo = await getUserId(username);
  1723. let userId = userInfo.user.pk;
  1724. let stories = await getStories(userId);
  1725. let urlID = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
  1726.  
  1727. /*
  1728. let latest_reel_media = stories.data.reels_media[0].latest_reel_media;
  1729. let last_seen = stories.data.reels_media[0].seen;
  1730. logger(stories);
  1731.  
  1732. if(urlID == null){
  1733. mediaId = stories.data.reels_media[0].items.filter(function(item, index){
  1734. return item.taken_at_timestamp === last_seen && item.taken_at_timestamp !== latest_reel_media || last_seen === latest_reel_media && index === 0;
  1735. })?.at(0)?.id;
  1736. logger('nula', mediaId);
  1737. }
  1738. else{
  1739. stories.data.reels_media[0].items.forEach(item => {
  1740. if(item.id == urlID){
  1741. mediaId = item.id;
  1742. }
  1743. });
  1744. }
  1745. */
  1746.  
  1747. stories.data.reels_media[0].items.forEach(item => {
  1748. if (item.id == urlID) {
  1749. mediaId = item.id;
  1750. }
  1751. });
  1752.  
  1753. if (mediaId == null) {
  1754. let $header = getStoryProgress(username);
  1755.  
  1756. $header.each(function (index) {
  1757. if ($(this).children().length > 0) {
  1758. mediaId = stories.data.reels_media[0].items[index].id;
  1759. }
  1760. });
  1761. }
  1762.  
  1763. if (mediaId == null) {
  1764. // appear in from profile page to story page
  1765. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function (index) {
  1766. if ($(this).hasClass('x1lix1fw')) {
  1767. if ($(this).children().length > 0) {
  1768. mediaId = stories.data.reels_media[0].items[index].id;
  1769. }
  1770. }
  1771. });
  1772.  
  1773. // appear in from home page to story page
  1774. $('body > div section:visible ._ac0k > ._ac3r > div').each(function (index) {
  1775. if ($(this).children().hasClass('_ac3q')) {
  1776. mediaId = stories.data.reels_media[0].items[index].id;
  1777. }
  1778. });
  1779. }
  1780.  
  1781. if (mediaId == null) {
  1782. mediaId = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
  1783. }
  1784.  
  1785. let result = await getMediaInfo(mediaId);
  1786.  
  1787. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1788. timestamp = result.items[0].taken_at;
  1789. }
  1790.  
  1791. if (result.status === 'ok') {
  1792. if (result.items[0].video_versions) {
  1793. if (isPreview) {
  1794. openNewTab(result.items[0].video_versions[0].url);
  1795. }
  1796. else {
  1797. saveFiles(result.items[0].video_versions[0].url, username, "stories", timestamp, 'mp4', mediaId);
  1798. }
  1799. }
  1800. else {
  1801. if (isPreview) {
  1802. openNewTab(result.items[0].image_versions2.candidates[0].url);
  1803. }
  1804. else {
  1805. saveFiles(result.items[0].image_versions2.candidates[0].url, username, "stories", timestamp, 'jpg', mediaId);
  1806. }
  1807. }
  1808. }
  1809. else {
  1810. if (USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT) {
  1811. state.tempFetchRateLimit = true;
  1812. onStory(isDownload, isForce, isPreview);
  1813. }
  1814. else {
  1815. alert('Fetch failed from Media API. API response message: ' + result.message);
  1816. }
  1817. logger(result);
  1818. }
  1819.  
  1820. updateLoadingBar(false);
  1821. return;
  1822. }
  1823.  
  1824. if ($('body > div section:visible video[playsinline]').length > 0) {
  1825. // Download stories if it is video
  1826. let type = "mp4";
  1827. let videoURL = "";
  1828. let targetURL = location.pathname.replace(/\/$/ig, '').split("/").at(-1);
  1829. let mediaId = null;
  1830.  
  1831. if (state.GL_dataCache.stories[username] && !isForce) {
  1832. logger('Fetch from memory cache:', username);
  1833. state.GL_dataCache.stories[username].data.reels_media[0].items.forEach(item => {
  1834. if (item.id == targetURL) {
  1835. videoURL = item.video_resources[0].src;
  1836. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1837. timestamp = item.taken_at_timestamp;
  1838. mediaId = item.id;
  1839. }
  1840. }
  1841. });
  1842.  
  1843. if (videoURL.length == 0) {
  1844. logger('Memory cache not found, try fetch from API:', username);
  1845. onStory(true, true);
  1846. return;
  1847. }
  1848. }
  1849. else {
  1850. let userInfo = await getUserId(username);
  1851. let userId = userInfo.user.pk;
  1852. let stories = await getStories(userId);
  1853.  
  1854. stories.data.reels_media[0].items.forEach(item => {
  1855. if (item.id == targetURL) {
  1856. videoURL = item.video_resources[0].src;
  1857. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1858. timestamp = item.taken_at_timestamp;
  1859. mediaId = item.id;
  1860. }
  1861. }
  1862. });
  1863.  
  1864. // GitHub issue #4: thinkpad4
  1865. if (videoURL.length == 0) {
  1866.  
  1867. let $header = getStoryProgress(username);
  1868.  
  1869. $header.each(function (index) {
  1870. if ($(this).children().length > 0) {
  1871. videoURL = stories.data.reels_media[0].items[index].video_resources[0].src;
  1872. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1873. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  1874. mediaId = stories.data.reels_media[0].items[index].id;
  1875. }
  1876. }
  1877. });
  1878.  
  1879.  
  1880. if (videoURL.length == 0) {
  1881. // appear in from profile page to story page
  1882. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function (index) {
  1883. if ($(this).hasClass('x1lix1fw')) {
  1884. if ($(this).children().length > 0) {
  1885. videoURL = stories.data.reels_media[0].items[index].video_resources[0].src;
  1886. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1887. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  1888. mediaId = stories.data.reels_media[0].items[index].id;
  1889. }
  1890. }
  1891. }
  1892. });
  1893.  
  1894. // appear in from home page to story page
  1895. $('body > div section:visible ._ac0k > ._ac3r > div').each(function (index) {
  1896. if ($(this).children().hasClass('_ac3q')) {
  1897. videoURL = stories.data.reels_media[0].items[index].video_resources[0].src;
  1898. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1899. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  1900. mediaId = stories.data.reels_media[0].items[index].id;
  1901. }
  1902. }
  1903. });
  1904. }
  1905. }
  1906.  
  1907. state.GL_dataCache.stories[username] = stories;
  1908. }
  1909.  
  1910. if (videoURL.length == 0) {
  1911. alert(_i18n("NO_VID_URL"));
  1912. }
  1913. else {
  1914. if (isPreview) {
  1915. openNewTab(videoURL);
  1916. }
  1917. else {
  1918. saveFiles(videoURL, username, "stories", timestamp, type, mediaId);
  1919. }
  1920. }
  1921. }
  1922. else {
  1923. // Download stories if it is image
  1924. let srcset = $('body > div section:visible img[referrerpolicy][class], body > div section:visible img[crossorigin][class]:not([alt])').attr('srcset')?.split(',')[0]?.split(' ')[0];
  1925. let link = (srcset) ? srcset : $('body > div section:visible img[referrerpolicy][class], body > div section:visible img[crossorigin][class]:not([alt])').filter(function () {
  1926. return $(this).parents('a').length === 0 && $(this).width() === $(this).parent().width();
  1927. }).attr('src');
  1928.  
  1929. if (!link) {
  1930. // _aa63 mean stories picture in stories page (not avatar)
  1931. let $element = $('body > div section:visible img._aa63');
  1932. link = ($element.attr('srcset')) ? $element.attr('srcset')?.split(',')[0]?.split(' ')[0] : $element.attr('src');
  1933. }
  1934.  
  1935. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  1936. timestamp = new Date($('body > div section:visible time[datetime][class]').first().attr('datetime')).getTime();
  1937. }
  1938.  
  1939. let downloadLink = link;
  1940. let type = 'jpg';
  1941.  
  1942. if (isPreview) {
  1943. openNewTab(downloadLink);
  1944. }
  1945. else {
  1946. saveFiles(downloadLink, username, "stories", timestamp, type, getStoryId(downloadLink) ?? "");
  1947. }
  1948. }
  1949.  
  1950. state.tempFetchRateLimit = false;
  1951. updateLoadingBar(false);
  1952. }
  1953. else {
  1954. // Add the stories download button
  1955. if (!$('.IG_DWSTORY').length) {
  1956. state.GL_dataCache.stories = {};
  1957. let $element = null;
  1958. // Default detecter (section layout mode)
  1959. if ($('body > div section._ac0a').length > 0) {
  1960. $element = $('body > div section:visible._ac0a');
  1961. }
  1962. // detecter (single story layout mode)
  1963. else {
  1964. $element = $('body > div section:visible > div > div[style]:not([class])');
  1965. $element.css('position', 'relative');
  1966. }
  1967.  
  1968.  
  1969. if ($element.length === 0) {
  1970. $element = $('div[id^="mount"] section > div > a[href="/"]').parent().parent().parent().find('section:visible > div > div[style]:not([class])');
  1971. $element.css('position', 'relative');
  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]) > div:not([data-visualcompletion="loading-state"])');
  1976. $element.css('position', 'relative');
  1977. }
  1978.  
  1979.  
  1980. // Detecter for div layout mode
  1981. if ($element.length === 0) {
  1982. let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
  1983. let nowSize = 0;
  1984.  
  1985. $$element.each(function () {
  1986. if ($(this).width() > nowSize) {
  1987. nowSize = $(this).width();
  1988. $element = $(this).children('div').first();
  1989. }
  1990. });
  1991. }
  1992.  
  1993.  
  1994. if ($element != null) {
  1995. $element.first().css('position', 'relative');
  1996. $element.first().append(`<div data-ih-locale-title="DW" title="${_i18n("DW")}" class="IG_DWSTORY">${SVG.DOWNLOAD}</div>`);
  1997. $element.first().append(`<div data-ih-locale-title="NEW_TAB" title="${_i18n("NEW_TAB")}" class="IG_DWNEWTAB">${SVG.NEW_TAB}</div>`);
  1998.  
  1999. let $header = getStoryProgress(username);
  2000. if ($header.length > 1) {
  2001. $element.first().append(`<div data-ih-locale-title="DW_ALL" title="${_i18n("DW_ALL")}" class="IG_DWSTORY_ALL">${SVG.DOWNLOAD_ALL}</div>`);
  2002. }
  2003.  
  2004. // Modify video volume
  2005. //if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  2006. // $element.find('video').each(function(){
  2007. // $(this).on('play playing', function(){
  2008. // if(!$(this).data('modify')){
  2009. // $(this).attr('data-modify', true);
  2010. // this.volume = VIDEO_VOLUME;
  2011. // logger('(story) Added video event listener #modify');
  2012. // }
  2013. // });
  2014. // });
  2015. //}
  2016.  
  2017. // Make sure to first remove thumbnail button if still exists and story is a picture
  2018. $element.find('img[referrerpolicy]').each(function () {
  2019. $(this).on('load', function () {
  2020. if (!$(this).data('remove-thumbnail')) {
  2021. if ($element.find('.IG_DWSTORY_THUMBNAIL').length === 0) {
  2022. $(this).attr('data-remove-thumbnail', true);
  2023. $('.IG_DWSTORY_THUMBNAIL').remove();
  2024. logger('(story) Manually removing thumbnail button');
  2025. }
  2026. else {
  2027. $(this).attr('data-remove-thumbnail', true);
  2028. logger('(story) Thumbnail button is not present for this picture');
  2029. }
  2030. }
  2031. });
  2032. });
  2033.  
  2034. // Try to use event listener 'timeupdate' in order to detect if story is a video
  2035. //$element.find('video').each(function(){
  2036. // $(this).on('timeupdate',function(){
  2037. // if(!$(this).data('modify-thumbnail')){
  2038. // if($element.find('.IG_DWSTORY_THUMBNAIL').length === 0){
  2039. // $(this).attr('data-modify-thumbnail', true);
  2040. // onStoryThumbnail(false);
  2041. // logger('(story) Manually inserting thumbnail button');
  2042. // }
  2043. // else{
  2044. // $(this).attr('data-modify-thumbnail', true);
  2045. // logger('(story) Thumbnail button already inserted');
  2046. // }
  2047. // }
  2048. // });
  2049. //});
  2050. }
  2051. }
  2052. }
  2053. }
  2054.  
  2055. /**
  2056. * onStoryThumbnail
  2057. * @description Trigger user's story video thumbnail download event or button display event.
  2058. *
  2059. * @param {Boolean} isDownload - Check if it is a download operation
  2060. * @param {Boolean} isForce - Check if downloading directly from API instead of cache
  2061. * @return {void}
  2062. */
  2063. async function onStoryThumbnail(isDownload, isForce) {
  2064. if (isDownload) {
  2065. // Download stories if it is video
  2066. let date = new Date().getTime();
  2067. let timestamp = Math.floor(date / 1000);
  2068. let type = 'jpg';
  2069. let username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split('/').at(2);
  2070. // Download thumbnail
  2071. let targetURL = location.pathname.replace(/\/$/ig, '').split("/").at(-1);
  2072. let videoThumbnailURL = "";
  2073. let mediaId = null;
  2074.  
  2075. updateLoadingBar(true);
  2076.  
  2077. if (USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !state.tempFetchRateLimit) {
  2078. let userInfo = await getUserId(username);
  2079. let userId = userInfo.user.pk;
  2080. let stories = await getStories(userId);
  2081. let urlID = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
  2082.  
  2083. stories.data.reels_media[0].items.forEach(item => {
  2084. if (item.id == urlID) {
  2085. mediaId = item.id;
  2086. }
  2087. });
  2088.  
  2089. if (mediaId == null) {
  2090. let $header = getStoryProgress(username);
  2091.  
  2092. $header.each(function (index) {
  2093. if ($(this).children().length > 0) {
  2094. mediaId = stories.data.reels_media[0].items[index].id;
  2095. }
  2096. });
  2097. }
  2098.  
  2099. if (mediaId == null) {
  2100. // appear in from profile page to story page
  2101. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function (index) {
  2102. if ($(this).hasClass('x1lix1fw')) {
  2103. if ($(this).children().length > 0) {
  2104. mediaId = stories.data.reels_media[0].items[index].id;
  2105. }
  2106. }
  2107. });
  2108.  
  2109. // appear in from home page to story page
  2110. $('body > div section:visible ._ac0k > ._ac3r > div').each(function (index) {
  2111. if ($(this).children().hasClass('_ac3q')) {
  2112. mediaId = stories.data.reels_media[0].items[index].id;
  2113. }
  2114. });
  2115. }
  2116.  
  2117. if (mediaId == null) {
  2118. mediaId = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
  2119. }
  2120.  
  2121. let result = await getMediaInfo(mediaId);
  2122.  
  2123. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  2124. timestamp = result.items[0].taken_at;
  2125. }
  2126.  
  2127. if (result.status === 'ok') {
  2128. saveFiles(result.items[0].image_versions2.candidates[0].url, username, "stories", timestamp, 'jpg', mediaId);
  2129.  
  2130. }
  2131. else {
  2132. if (USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT) {
  2133. state.tempFetchRateLimit = true;
  2134. onStoryThumbnail(true, isForce);
  2135. }
  2136. else {
  2137. alert('Fetch failed from Media API. API response message: ' + result.message);
  2138. }
  2139.  
  2140. logger(result);
  2141. }
  2142.  
  2143. updateLoadingBar(false);
  2144. return;
  2145. }
  2146.  
  2147. if (state.GL_dataCache.stories[username] && !isForce) {
  2148. logger('Fetch from memory cache:', username);
  2149. state.GL_dataCache.stories[username].data.reels_media[0].items.forEach(item => {
  2150. if (item.id == targetURL) {
  2151. videoThumbnailURL = item.display_url;
  2152. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  2153. timestamp = item.taken_at_timestamp;
  2154. mediaId = item.id;
  2155. }
  2156. }
  2157. });
  2158.  
  2159. if (videoThumbnailURL.length == 0) {
  2160. logger('Memory cache not found, try fetch from API:', username);
  2161. onStoryThumbnail(true, true);
  2162. return;
  2163. }
  2164. }
  2165. else {
  2166. let userInfo = await getUserId(username);
  2167. let userId = userInfo.user.pk;
  2168. let stories = await getStories(userId);
  2169.  
  2170. stories.data.reels_media[0].items.forEach(item => {
  2171. if (item.id == targetURL) {
  2172. videoThumbnailURL = item.display_url;
  2173. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  2174. timestamp = item.taken_at_timestamp;
  2175. mediaId = item.id;
  2176. }
  2177. }
  2178. });
  2179.  
  2180. // GitHub issue #4: thinkpad4
  2181. if (videoThumbnailURL.length == 0) {
  2182. let $header = getStoryProgress(username);
  2183.  
  2184. $header.each(function (index) {
  2185. if ($(this).children().length > 0) {
  2186. videoThumbnailURL = stories.data.reels_media[0].items[index].display_url;
  2187. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  2188. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  2189. mediaId = stories.data.reels_media[0].items[index].id;
  2190. }
  2191. }
  2192. });
  2193.  
  2194. if (videoThumbnailURL.length == 0) {
  2195. // appear in from profile page to story page
  2196. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function (index) {
  2197. if ($(this).hasClass('x1lix1fw')) {
  2198. if ($(this).children().length > 0) {
  2199. videoThumbnailURL = stories.data.reels_media[0].items[index].display_url;
  2200. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  2201. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  2202. mediaId = stories.data.reels_media[0].items[index].id;
  2203. }
  2204. }
  2205. }
  2206. });
  2207.  
  2208. // appear in from home page to story page
  2209. $('body > div section:visible ._ac0k > ._ac3r > div').each(function (index) {
  2210. if ($(this).children().hasClass('_ac3q')) {
  2211. videoThumbnailURL = stories.data.reels_media[0].items[index].display_url;
  2212. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  2213. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  2214. mediaId = stories.data.reels_media[0].items[index].id;
  2215. }
  2216. }
  2217. });
  2218. }
  2219. }
  2220. }
  2221.  
  2222. saveFiles(videoThumbnailURL, username, "thumbnail", timestamp, type, mediaId);
  2223. state.tempFetchRateLimit = false;
  2224. updateLoadingBar(false);
  2225. }
  2226. else {
  2227. if ($('body > div div.IG_DWSTORY').parent().find('video[class]').length) {
  2228. // Add the stories download button
  2229. let $element = null;
  2230. // Default detecter (section layout mode)
  2231. if ($('body > div section._ac0a').length > 0) {
  2232. $element = $('body > div section:visible._ac0a');
  2233. }
  2234. // detecter (single story layout mode)
  2235. else {
  2236. $element = $('body > div section:visible > div > div[style]:not([class])');
  2237. $element.css('position', 'relative');
  2238. }
  2239.  
  2240. if ($element.length === 0) {
  2241. $element = $('div[id^="mount"] section > div > a[href="/"]').parent().parent().parent().find('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]) > div:not([data-visualcompletion="loading-state"])');
  2247. $element.css('position', 'relative');
  2248. }
  2249.  
  2250. // Detecter for div layout mode
  2251. if ($element.length === 0) {
  2252. let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
  2253. let nowSize = 0;
  2254.  
  2255. $$element.each(function () {
  2256. if ($(this).width() > nowSize) {
  2257. nowSize = $(this).width();
  2258. $element = $(this).children('div').first();
  2259. }
  2260. });
  2261. }
  2262.  
  2263.  
  2264. if ($element != null) {
  2265. $element.first().css('position', 'relative');
  2266. $element.first().append(`<div data-ih-locale-title="THUMBNAIL_INTRO" title="${_i18n("THUMBNAIL_INTRO")}" class="IG_DWSTORY_THUMBNAIL">${SVG.THUMBNAIL}</div>`);
  2267. }
  2268.  
  2269. }
  2270. }
  2271. }
  2272.  
  2273. /* untils */
  2274.  
  2275. /**
  2276. * getHighlightStories
  2277. * @description Get a list of all stories in highlight Id.
  2278. *
  2279. * @param {Integer} highlightId
  2280. * @return {Object}
  2281. */
  2282. function getHighlightStories(highlightId) {
  2283. return new Promise((resolve, reject) => {
  2284. 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`;
  2285.  
  2286. GM_xmlhttpRequest({
  2287. method: "GET",
  2288. url: getURL,
  2289. onload: function (response) {
  2290. try {
  2291. let obj = JSON.parse(response.response);
  2292. resolve(obj);
  2293. }
  2294. catch (err) {
  2295. logger('getHighlightStories()', 'reject', err.message);
  2296. reject(err);
  2297. }
  2298. },
  2299. onerror: function (err) {
  2300. logger('getHighlightStories()', 'reject', err);
  2301. reject(err);
  2302. }
  2303. });
  2304. });
  2305. }
  2306.  
  2307. /**
  2308. * getStories
  2309. * @description Get a list of all stories in user Id.
  2310. *
  2311. * @param {Integer} userId
  2312. * @return {Object}
  2313. */
  2314. function getStories(userId) {
  2315. return new Promise((resolve, reject) => {
  2316. 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`;
  2317.  
  2318. GM_xmlhttpRequest({
  2319. method: "GET",
  2320. url: getURL,
  2321. onload: function (response) {
  2322. try {
  2323. let obj = JSON.parse(response.response);
  2324. logger('getStories()', obj);
  2325. resolve(obj);
  2326. }
  2327. catch (err) {
  2328. logger('getStories()', 'reject', err.message);
  2329. reject(err);
  2330. }
  2331. },
  2332. onerror: function (err) {
  2333. logger('getStories()', 'reject', err);
  2334. reject(err);
  2335. }
  2336. });
  2337. });
  2338. }
  2339.  
  2340. /**
  2341. * getUserId
  2342. * @description Get user's id with username
  2343. *
  2344. * @param {String} username
  2345. * @return {Integer}
  2346. */
  2347. function getUserId(username) {
  2348. return new Promise((resolve, reject) => {
  2349. let getURL = `https://www.instagram.com/web/search/topsearch/?query=${username}`;
  2350.  
  2351. GM_xmlhttpRequest({
  2352. method: "GET",
  2353. url: getURL,
  2354. onload: function (response) {
  2355. // Fix search issue by Discord: sno_w_
  2356. let obj = JSON.parse(response.response);
  2357. let result = null;
  2358. obj.users.forEach(pos => {
  2359. if (pos.user.username?.toLowerCase() === username?.toLowerCase()) {
  2360. result = pos;
  2361. }
  2362. });
  2363.  
  2364. if (result != null) {
  2365. logger('getUserId()', result);
  2366. resolve(result);
  2367. }
  2368. else {
  2369. getUserIdWithAgent(username).then((result) => {
  2370. resolve(result);
  2371. // eslint-disable-next-line no-unused-vars
  2372. }).catch((err) => {
  2373. alert("Can not find user info from getUserId()");
  2374. });
  2375. }
  2376. },
  2377. onerror: function (err) {
  2378. logger('getUserId()', 'reject', err);
  2379. reject(err);
  2380. }
  2381. });
  2382. });
  2383. }
  2384.  
  2385. /**
  2386. * getUserIdWithAgent
  2387. * @description Get user's id with username
  2388. *
  2389. * @param {String} username
  2390. * @return {Integer}
  2391. */
  2392. function getUserIdWithAgent(username) {
  2393. return new Promise((resolve, reject) => {
  2394. let getURL = `https://i.instagram.com/api/v1/users/web_profile_info/?username=${username}`;
  2395.  
  2396. GM_xmlhttpRequest({
  2397. method: "GET",
  2398. url: getURL,
  2399. headers: {
  2400. 'X-IG-App-ID': getAppID()
  2401. },
  2402. onload: function (response) {
  2403. try {
  2404. let obj = JSON.parse(response.response);
  2405. let hasUser = obj?.data?.user;
  2406.  
  2407. if (hasUser != null) {
  2408. let userInfo = obj?.data;
  2409. userInfo.user.pk = userInfo.user.id;
  2410. logger('getUserIdWithAgent()', obj);
  2411. resolve(userInfo);
  2412. }
  2413. else {
  2414. logger('getUserIdWithAgent()', 'reject', 'undefined');
  2415. reject('undefined');
  2416. }
  2417. }
  2418. catch (err) {
  2419. logger('getUserIdWithAgent()', 'reject', err.message);
  2420. reject(err);
  2421. }
  2422. },
  2423. onerror: function (err) {
  2424. logger('getUserIdWithAgent()', 'reject', err);
  2425. reject(err);
  2426. }
  2427. });
  2428. });
  2429. }
  2430.  
  2431. /**
  2432. * getUserHighSizeProfile
  2433. * @description Get user's high quality avatar image.
  2434. *
  2435. * @param {Integer} userId
  2436. * @return {String}
  2437. */
  2438. function getUserHighSizeProfile(userId) {
  2439. return new Promise((resolve, reject) => {
  2440. let getURL = `https://i.instagram.com/api/v1/users/${userId}/info/`;
  2441.  
  2442. GM_xmlhttpRequest({
  2443. method: "GET",
  2444. url: getURL,
  2445. headers: {
  2446. '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'
  2447. },
  2448. onload: function (response) {
  2449. try {
  2450. let obj = JSON.parse(response.response);
  2451. if (obj.status !== 'ok') {
  2452. logger('getUserHighSizeProfile()', 'reject', obj);
  2453. reject('faild');
  2454. }
  2455. else {
  2456. logger('getUserHighSizeProfile()', obj);
  2457. resolve(obj.user.hd_profile_pic_url_info?.url);
  2458. }
  2459. }
  2460. catch (err) {
  2461. logger('getUserHighSizeProfile()', 'reject', err);
  2462. reject(err);
  2463. }
  2464. },
  2465. onerror: function (err) {
  2466. logger('getUserHighSizeProfile()', 'reject', err);
  2467. reject(err);
  2468. }
  2469. });
  2470. });
  2471. }
  2472.  
  2473. /**
  2474. * getPostOwner
  2475. * @description Get post's author with post shortcode
  2476. *
  2477. * @param {String} postPath
  2478. * @return {String}
  2479. */
  2480. function getPostOwner(postPath) {
  2481. return new Promise((resolve, reject) => {
  2482. if (!postPath) reject("NOPATH");
  2483. let postShortCode = postPath;
  2484. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  2485.  
  2486. GM_xmlhttpRequest({
  2487. method: "GET",
  2488. url: getURL,
  2489. onload: function (response) {
  2490. try {
  2491. let obj = JSON.parse(response.response);
  2492. logger('getPostOwner()', obj);
  2493. resolve(obj.data.shortcode_media.owner.username);
  2494. }
  2495. catch (err) {
  2496. logger('getPostOwner()', 'reject', err.message);
  2497. reject(err);
  2498. }
  2499. },
  2500. onerror: function (err) {
  2501. logger('getPostOwner()', 'reject', err);
  2502. reject(err);
  2503. }
  2504. });
  2505. });
  2506. }
  2507.  
  2508. /**
  2509. * getBlobMedia
  2510. * @description Get list of all media files in post with post shortcode
  2511. *
  2512. * @param {String} postPath
  2513. * @return {Object}
  2514. */
  2515. function getBlobMedia(postPath) {
  2516. return new Promise((resolve, reject) => {
  2517. if (!postPath) reject("NOPATH");
  2518. let postShortCode = postPath;
  2519. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  2520.  
  2521. GM_xmlhttpRequest({
  2522. method: "GET",
  2523. url: getURL,
  2524. headers: {
  2525. "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"
  2526. },
  2527. onload: function (response) {
  2528. try {
  2529. let obj = JSON.parse(response.response);
  2530. logger(obj);
  2531.  
  2532. if (obj.status === 'fail') {
  2533. // alert(`Request failed with API response:\n${obj.message}: ${obj.feedback_message}`);
  2534. logger('Request with:', 'getBlobMediaWithQuery()', postShortCode);
  2535. getBlobMediaWithQueryID(postShortCode).then((res) => {
  2536. resolve({ type: 'query_id', data: res.xdt_api__v1__media__shortcode__web_info.items[0] });
  2537. }).catch((err) => {
  2538. reject(err);
  2539. })
  2540. }
  2541. else {
  2542. resolve({ type: 'query_hash', data: obj.data });
  2543. }
  2544. }
  2545. catch (err) {
  2546. logger('getBlobMedia()', 'reject', err.message);
  2547. reject(err);
  2548. }
  2549. },
  2550. onerror: function (err) {
  2551. logger('getBlobMedia()', 'reject', err);
  2552. reject(err);
  2553. }
  2554. });
  2555. });
  2556. }
  2557.  
  2558. /**
  2559. * getBlobMediaWithQueryID
  2560. * @description Get list of all media files in post with post shortcode
  2561. *
  2562. * @param {String} postPath
  2563. * @return {Object}
  2564. */
  2565. function getBlobMediaWithQueryID(postPath) {
  2566. return new Promise((resolve, reject) => {
  2567. if (!postPath) reject("NOPATH");
  2568. let postShortCode = postPath;
  2569. 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}`;
  2570.  
  2571. GM_xmlhttpRequest({
  2572. method: "GET",
  2573. url: getURL,
  2574. headers: {
  2575. "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",
  2576. 'X-IG-App-ID': getAppID()
  2577. },
  2578. onload: function (response) {
  2579. try {
  2580. let obj = JSON.parse(response.response);
  2581. logger(obj);
  2582.  
  2583. if (obj.status === 'fail') {
  2584. alert(`getBlobMediaWithQueryID(): Request failed with API response:\n${obj.message}: ${obj.feedback_message}`);
  2585. logger(`Request failed with API response ${obj.message}: ${obj.feedback_message}`);
  2586. reject(response);
  2587. }
  2588. else {
  2589. logger('getBlobMediaWithQueryID()', obj.data);
  2590. resolve(obj.data);
  2591. }
  2592. }
  2593. catch (err) {
  2594. logger('getBlobMediaWithQueryID()', 'reject', err.message);
  2595. reject(err);
  2596. }
  2597. },
  2598. onerror: function (err) {
  2599. logger('getBlobMediaWithQueryID()', 'reject', err);
  2600. reject(err);
  2601. }
  2602. });
  2603. });
  2604. }
  2605.  
  2606. /**
  2607. * getMediaInfo
  2608. * @description Get Instagram Media object
  2609. *
  2610. * @param {String} mediaId
  2611. * @return {Object}
  2612. */
  2613. function getMediaInfo(mediaId) {
  2614. return new Promise((resolve, reject) => {
  2615. let getURL = `https://i.instagram.com/api/v1/media/${mediaId}/info/`;
  2616.  
  2617. if (mediaId == null) {
  2618. alert("Can not call Media API because of the media id is invalid.");
  2619. logger('getMediaInfo()', 'reject', 'Can not call Media API because of the media id is invalid.');
  2620.  
  2621. updateLoadingBar(false);
  2622. reject(-1);
  2623. return;
  2624. }
  2625. if (getAppID() == null) {
  2626. alert("Can not call Media API because of the app id is invalid.");
  2627. logger('getMediaInfo()', 'reject', 'Can not call Media API because of the app id is invalid.');
  2628. updateLoadingBar(false);
  2629. reject(-1);
  2630. return;
  2631. }
  2632.  
  2633. GM_xmlhttpRequest({
  2634. method: "GET",
  2635. url: getURL,
  2636. headers: {
  2637. "User-Agent": window.navigator.userAgent,
  2638. "Accept": "*/*",
  2639. 'X-IG-App-ID': getAppID()
  2640. },
  2641. onload: function (response) {
  2642. if (response.finalUrl == getURL) {
  2643. let obj = JSON.parse(response.response);
  2644. logger('getMediaInfo()', obj);
  2645. resolve(obj);
  2646. }
  2647. else {
  2648. let finalURL = new URL(response.finalUrl);
  2649. if (finalURL.pathname.startsWith('/accounts/login')) {
  2650. logger('getMediaInfo()', 'reject', 'The account must be logged in to access Media API.');
  2651. alert("The account must be logged in to access Media API.");
  2652. }
  2653. else {
  2654. logger('getMediaInfo()', 'reject', 'Unable to retrieve content because the API was redirected to "' + response.finalUrl + '"');
  2655. alert('Unable to retrieve content because the API was redirected to "' + response.finalUrl + '"');
  2656. }
  2657. updateLoadingBar(false);
  2658. reject(-1);
  2659. }
  2660. },
  2661. onerror: function (err) {
  2662. logger('getMediaInfo()', 'reject', err);
  2663. resolve(err);
  2664. }
  2665. });
  2666. });
  2667. }
  2668.  
  2669. /**
  2670. * getStoryId
  2671. * @description Obtain the media id through the resource URL.
  2672. *
  2673. * @param {string} url
  2674. * @return {string}
  2675. */
  2676. function getStoryId(url) {
  2677. let obj = new URL(url);
  2678. let base64 = obj?.searchParams?.get('ig_cache_key')?.split('.').at(0);
  2679. if (base64) {
  2680. return atob(base64);
  2681. }
  2682. else {
  2683. return null;
  2684. }
  2685. }
  2686.  
  2687. /**
  2688. * getAppID
  2689. * @description Get Instagram App ID
  2690. *
  2691. * @return {?integer}
  2692. */
  2693. function getAppID() {
  2694. let result = null;
  2695. $('script[type="application/json"]').each(function () {
  2696. const regexp = /"APP_ID":"([0-9]+)"/ig;
  2697. const matcher = $(this).text().match(regexp);
  2698. if (matcher != null && result == null) {
  2699. result = [...$(this).text().matchAll(regexp)];
  2700. }
  2701. })
  2702.  
  2703. return (result) ? result.at(0).at(-1) : null;
  2704. }
  2705.  
  2706.  
  2707. /**
  2708. * updateLoadingBar
  2709. * @description Update loading state
  2710. *
  2711. * @param {Boolean} isLoading - Check if loading state
  2712. * @return {void}
  2713. */
  2714. function updateLoadingBar(isLoading) {
  2715. if (isLoading) {
  2716. $('div[id^="mount"] > div > div > div:first').removeClass('x1s85apg');
  2717. $('div[id^="mount"] > div > div > div:first').css('z-index', '20000');
  2718. }
  2719. else {
  2720. $('div[id^="mount"] > div > div > div:first').addClass('x1s85apg');
  2721. $('div[id^="mount"] > div > div > div:first').css('z-index', '');
  2722. }
  2723. }
  2724.  
  2725. /**
  2726. * getStoryProgress
  2727. * @description Get the story progress of the username (post several stories)
  2728. *
  2729. * @param {String} username - Get progress of username
  2730. * @return {Object}
  2731. */
  2732. function getStoryProgress(username) {
  2733. let $header = $('body > div section:visible a[href^="/' + (username) + '"] span').filter(function () {
  2734. return $(this).children().length === 0 && $(this).find('svg').length === 0 && $(this).text()?.toLowerCase() === username?.toLowerCase();
  2735. }).parents('div:not([class]):not([style])').filter(function () {
  2736. return $(this).text()?.toLowerCase() !== username?.toLowerCase()
  2737. }).filter(function () {
  2738. return $(this).children().length > 1
  2739. }).first();
  2740.  
  2741. if ($header.length === 0) {
  2742. $header = $('body > div section:visible a[href^="/' + (username) + '"]').filter(function () {
  2743. return $(this).find('img').length > 0
  2744. }).parents('div:not([class]):not([style])').filter(function () {
  2745. return $(this).text()?.toLowerCase() !== username?.toLowerCase()
  2746. }).filter(function () {
  2747. return $(this).children().length > 1
  2748. }).first();
  2749. }
  2750.  
  2751. return $header.children().filter(function () {
  2752. return $(this).height() < 10
  2753. }).first().children();
  2754. }
  2755.  
  2756. /**
  2757. * setDownloadProgress
  2758. * @description Show and set download circle progress
  2759. *
  2760. * @param {Integer} now
  2761. * @param {Integer} total
  2762. * @return {Void}
  2763. */
  2764. function setDownloadProgress(now, total) {
  2765. if ($('.circle_wrapper').length) {
  2766. $('.circle_wrapper span').text(`${now}/${total}`);
  2767.  
  2768. if (now >= total) {
  2769. $('.circle_wrapper').fadeOut(250, function () {
  2770. $(this).remove();
  2771. });
  2772. }
  2773. }
  2774. else {
  2775. $('body').append(`<div class="circle_wrapper"><circle></circle><span>${now}/${total}</span></div>`);
  2776. }
  2777. }
  2778.  
  2779.  
  2780. /**
  2781. * IG_createDM
  2782. * @description A dialog showing a list of all media files in the post
  2783. *
  2784. * @param {Boolean} hasHidden
  2785. * @param {Boolean} hasCheckbox
  2786. * @return {void}
  2787. */
  2788. function IG_createDM(hasHidden, hasCheckbox) {
  2789. let isHidden = (hasHidden) ? "hidden" : "";
  2790. $('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>');
  2791. $('.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>`);
  2792.  
  2793. if (hasCheckbox) {
  2794. $('.IG_POPUP_DIG .IG_POPUP_DIG_MAIN .IG_POPUP_DIG_TITLE').append(`<div style="text-align: center;" id="button_group"></div>`);
  2795. $('.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>`);
  2796. $('.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>`);
  2797. $('.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>`);
  2798. }
  2799. }
  2800.  
  2801. /**
  2802. * IG_setDM
  2803. * @description Set a dialog status
  2804. *
  2805. * @param {Boolean} hasHidden
  2806. * @return {void}
  2807. */
  2808. function IG_setDM(hasHidden) {
  2809. if ($('.IG_POPUP_DIG').length) {
  2810. if (hasHidden) {
  2811. $('.IG_POPUP_DIG').addClass("hidden");
  2812. }
  2813. else {
  2814. $('.IG_POPUP_DIG').removeClass("hidden");
  2815. }
  2816. }
  2817. }
  2818.  
  2819. /**
  2820. * saveFiles
  2821. * @description Download the specified media URL to the computer
  2822. *
  2823. * @param {String} downloadLink
  2824. * @param {String} username
  2825. * @param {String} sourceType
  2826. * @param {Integer} timestamp
  2827. * @param {String} filetype
  2828. * @param {String} shortcode
  2829. * @return {Promise}
  2830. */
  2831. function saveFiles(downloadLink, username, sourceType, timestamp, filetype, shortcode) {
  2832. return new Promise((resolve) => {
  2833. setTimeout(() => {
  2834. updateLoadingBar(true);
  2835. fetch(downloadLink).then(res => {
  2836. return res.blob().then(dwel => {
  2837. updateLoadingBar(false);
  2838. createSaveFileElement(downloadLink, dwel, username, sourceType, timestamp, filetype, shortcode);
  2839.  
  2840. resolve(true);
  2841. });
  2842. });
  2843. }, 50);
  2844. });
  2845. }
  2846.  
  2847. /**
  2848. * createSaveFileElement
  2849. * @description Download the specified media with link element
  2850. *
  2851. * @param {String} downloadLink
  2852. * @param {Object} object
  2853. * @param {String} username
  2854. * @param {String} sourceType
  2855. * @param {Integer} timestamp
  2856. * @param {String} filetype
  2857. * @param {String} shortcode
  2858. * @return {void}
  2859. */
  2860. function createSaveFileElement(downloadLink, object, username, sourceType, timestamp, filetype, shortcode) {
  2861. timestamp = parseInt(timestamp.toString().padEnd(13, '0'));
  2862.  
  2863. if (USER_SETTING.RENAME_PUBLISH_DATE) {
  2864. timestamp = parseInt(timestamp.toString().padEnd(13, '0'));
  2865. }
  2866.  
  2867. const date = new Date(timestamp);
  2868.  
  2869. const a = document.createElement("a");
  2870. const original_name = new URL(downloadLink).pathname.split('/').at(-1).split('.').slice(0, -1).join('.');
  2871. const year = date.getFullYear().toString();
  2872. const month = (date.getMonth() + 1).toString().padStart(2, '0');
  2873. const day = date.getDate().toString().padStart(2, '0');
  2874. const hour = date.getHours().toString().padStart(2, '0');
  2875. const minute = date.getMinutes().toString().padStart(2, '0');
  2876. const second = date.getSeconds().toString().padStart(2, '0');
  2877.  
  2878. var filename = state.fileRenameFormat.toUpperCase();
  2879. var format_shortcode = shortcode ?? "";
  2880. var replacements = {
  2881. '%USERNAME%': username,
  2882. '%SOURCE_TYPE%': sourceType,
  2883. '%SHORTCODE%': format_shortcode,
  2884. '%YEAR%': year,
  2885. '%2-YEAR%': year.substr(-2),
  2886. '%MONTH%': month,
  2887. '%DAY%': day,
  2888. '%HOUR%': hour,
  2889. '%MINUTE%': minute,
  2890. '%SECOND%': second,
  2891. '%ORIGINAL_NAME%': original_name,
  2892. '%ORIGINAL_NAME_FIRST%': original_name.split('_').at(0)
  2893. };
  2894.  
  2895. // eslint-disable-next-line no-useless-escape
  2896. filename = filename.replace(/%[\w\-]+%/g, function (str) {
  2897. return replacements[str] || str;
  2898. });
  2899.  
  2900. const originally = username + '_' + original_name + '.' + filetype;
  2901.  
  2902. a.href = URL.createObjectURL(object);
  2903. a.setAttribute("download", (USER_SETTING.AUTO_RENAME) ? filename + '.' + filetype : originally);
  2904. a.click();
  2905. a.remove();
  2906. }
  2907.  
  2908. /**
  2909. * triggerLinkElement
  2910. * @description Trigger the link element to start downloading the resource
  2911. *
  2912. * @param {Object} element
  2913. * @return {void}
  2914. */
  2915. async function triggerLinkElement(element, isPreview) {
  2916. let date = new Date().getTime();
  2917. let timestamp = Math.floor(date / 1000);
  2918. let username = ($(element).attr('data-username')) ? $(element).attr('data-username') : state.GL_username;
  2919.  
  2920. if (!username && $(element).attr('data-path')) {
  2921. logger('catching owner name from shortcode:', $(element).attr('data-href'));
  2922. username = await getPostOwner($(element).attr('data-path')).catch(err => {
  2923. logger('get username failed, replace with default string, error message:', err.message);
  2924. });
  2925.  
  2926. if (username == null) {
  2927. username = "NONE";
  2928. }
  2929. }
  2930.  
  2931. if (USER_SETTING.RENAME_PUBLISH_DATE && $(element).attr('datetime')) {
  2932. timestamp = parseInt($(element).attr('datetime'));
  2933. }
  2934.  
  2935. if (USER_SETTING.FORCE_RESOURCE_VIA_MEDIA) {
  2936. updateLoadingBar(true);
  2937. let result = await getMediaInfo($(element).attr('media-id'));
  2938. updateLoadingBar(false);
  2939.  
  2940. if (result.status === 'ok') {
  2941. var resource_url = null;
  2942. if (result.items[0].video_versions) {
  2943. resource_url = result.items[0].video_versions[0].url;
  2944. }
  2945. else {
  2946. result.items[0].image_versions2.candidates.sort(function (a, b) {
  2947. let aSTP = new URL(a.url).searchParams.get('stp');
  2948. let bSTP = new URL(b.url).searchParams.get('stp');
  2949.  
  2950. if (aSTP && bSTP) {
  2951. if (aSTP.length > bSTP.length) return 1;
  2952. if (aSTP.length < bSTP.length) return -1;
  2953. }
  2954. else {
  2955. if (a.width < b.width) return 1;
  2956. if (a.width > b.width) return -1;
  2957. }
  2958.  
  2959. return 0;
  2960. });
  2961.  
  2962. resource_url = result.items[0].image_versions2.candidates[0].url;
  2963. }
  2964.  
  2965. if (isPreview) {
  2966. let urlObj = new URL(resource_url);
  2967. urlObj.host = 'scontent.cdninstagram.com';
  2968.  
  2969. openNewTab(urlObj.href);
  2970. }
  2971. else {
  2972. saveFiles(resource_url, username, $(element).attr('data-name'), timestamp, $(element).attr('data-type'), $(element).attr('data-path'));
  2973. }
  2974. }
  2975. else {
  2976. if (USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT) {
  2977. if (isPreview) {
  2978. let urlObj = new URL($(element).attr('data-href'));
  2979. urlObj.host = 'scontent.cdninstagram.com';
  2980.  
  2981. openNewTab(urlObj.href);
  2982. }
  2983. else {
  2984. saveFiles($(element).attr('data-href'), username, $(element).attr('data-name'), timestamp, $(element).attr('data-type'), $(element).attr('data-path'));
  2985. }
  2986. }
  2987. else {
  2988. alert('Fetch failed from Media API. API response message: ' + result.message);
  2989. }
  2990. logger(result);
  2991. }
  2992. }
  2993. else {
  2994. saveFiles($(element).attr('data-href'), username, $(element).attr('data-name'), timestamp, $(element).attr('data-type'), $(element).attr('data-path'));
  2995. }
  2996. }
  2997.  
  2998.  
  2999. /**
  3000. * registerMenuCommand
  3001. * @description register script menu command
  3002. *
  3003. * @return {void}
  3004. */
  3005. function registerMenuCommand() {
  3006. for (let id of state.registerMenuIds) {
  3007. logger('GM_unregisterMenuCommand', id);
  3008. GM_unregisterMenuCommand(id);
  3009. }
  3010.  
  3011. state.registerMenuIds.push(GM_registerMenuCommand(_i18n('SETTING'), () => {
  3012. showSetting();
  3013. }, {
  3014. accessKey: "w"
  3015. }));
  3016.  
  3017. state.registerMenuIds.push(GM_registerMenuCommand(_i18n('DONATE'), () => {
  3018. GM_openInTab("https://ko-fi.com/snkoarashi", { active: true });
  3019. }, {
  3020. accessKey: "d"
  3021. }));
  3022.  
  3023. state.registerMenuIds.push(GM_registerMenuCommand(_i18n('DEBUG'), () => {
  3024. showDebugDOM();
  3025. }, {
  3026. accessKey: "z"
  3027. }));
  3028.  
  3029. state.registerMenuIds.push(GM_registerMenuCommand(_i18n('FEEDBACK'), () => {
  3030. showFeedbackDOM();
  3031. }, {
  3032. accessKey: "f"
  3033. }));
  3034.  
  3035. state.registerMenuIds.push(GM_registerMenuCommand(_i18n('CHECK_UPDATE_MENU'), () => {
  3036. callNotification();
  3037. }, {
  3038. accessKey: "c"
  3039. }));
  3040.  
  3041. state.registerMenuIds.push(GM_registerMenuCommand(_i18n('RELOAD_SCRIPT'), () => {
  3042. reloadScript();
  3043. }, {
  3044. accessKey: "r"
  3045. }));
  3046. }
  3047.  
  3048. /**
  3049. * checkingScriptUpdate
  3050. * @description Check if there is a new version of the script and push notification
  3051. *
  3052. * @param {Integer} interval
  3053. * @return {void}
  3054. */
  3055. function checkingScriptUpdate(interval) {
  3056. if (!USER_SETTING.CHECK_UPDATE) return;
  3057.  
  3058. const check_timestamp = GM_getValue('G_CHECK_TIMESTAMP') ?? new Date().getTime();
  3059. const now_time = new Date().getTime();
  3060.  
  3061. if (now_time > (parseInt(check_timestamp) + (interval * 1000))) {
  3062. GM_setValue('G_CHECK_TIMESTAMP', new Date().getTime());
  3063. callNotification();
  3064. }
  3065. }
  3066.  
  3067. /**
  3068. * callNotification
  3069. * @description call desktop notification by browser
  3070. *
  3071. * @return {void}
  3072. */
  3073. function callNotification() {
  3074. const currentVersion = GM_info.script.version;
  3075. const remoteScriptURL = 'https://raw.githubusercontent.com/SN-Koarashi/ig-helper/refs/heads/master/main.js';
  3076.  
  3077. GM_xmlhttpRequest({
  3078. method: "GET",
  3079. url: remoteScriptURL,
  3080. onload: function (response) {
  3081. const remoteScript = response.responseText;
  3082. const match = remoteScript.match(/\/\/\s+@version\s+([0-9.\-a-zA-Z]+)/i);
  3083.  
  3084. if (match && match[1]) {
  3085. const remoteVersion = match[1];
  3086. logger('Current version: ', currentVersion, '|', 'Remote version: ', remoteVersion);
  3087.  
  3088. if (remoteVersion !== currentVersion) {
  3089. GM_notification({
  3090. text: _i18n("NOTICE_UPDATE_CONTENT"),
  3091. title: _i18n("NOTICE_UPDATE_TITLE"),
  3092. tag: 'ig_helper_notice',
  3093. highlight: true,
  3094. timeout: 5000,
  3095. zombieTimeout: 5000,
  3096. image: "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Instagram_icon.png/64px-Instagram_icon.png",
  3097. onclick: (event) => {
  3098. event?.preventDefault();
  3099. var w = GM_openInTab(GM_info.script.downloadURL);
  3100. setTimeout(() => {
  3101. w.close();
  3102. }, 250);
  3103. }
  3104. });
  3105. } else {
  3106. logger('there is no new update');
  3107. }
  3108. } else {
  3109. console.error('Could not find version in the remote script.');
  3110. }
  3111. }
  3112. });
  3113. }
  3114.  
  3115. /**
  3116. * showSetting
  3117. * @description Show script settings window
  3118. *
  3119. * @return {void}
  3120. */
  3121. function showSetting() {
  3122. $('.IG_POPUP_DIG').remove();
  3123. IG_createDM();
  3124. $('.IG_POPUP_DIG #post_info').text('Preference Settings');
  3125.  
  3126. $('.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>');
  3127.  
  3128. for (let o in locale_manifest) {
  3129. $('.IG_POPUP_DIG .IG_POPUP_DIG_TITLE > div #langSelect').append(`<option value="${o}" ${(state.lang == o) ? 'selected' : ''}>${locale_manifest[o]}</option>`);
  3130. }
  3131.  
  3132. for (let name in USER_SETTING) {
  3133. $('.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>`);
  3134.  
  3135. if (name === 'MODIFY_VIDEO_VOLUME') {
  3136. $('.IG_POPUP_DIG .IG_POPUP_DIG_BODY input[id="' + name + '"]').parent('label').on('contextmenu', function (e) {
  3137. e.preventDefault();
  3138. if ($(this).find('#tempWrapper').length === 0) {
  3139. $(this).append('<div id="tempWrapper"></div>');
  3140. $(this).children('#tempWrapper').append('<input value="' + state.videoVolume + '" type="range" min="0" max="1" step="0.05" />');
  3141. $(this).children('#tempWrapper').append('<input value="' + state.videoVolume + '" step="0.05" type="number" />');
  3142. $(this).children('#tempWrapper').append(`<div class="IG_POPUP_DIG_BTN">${SVG.CLOSE}</div>`);
  3143. }
  3144. });
  3145. }
  3146.  
  3147. if (name === 'AUTO_RENAME') {
  3148. $('.IG_POPUP_DIG .IG_POPUP_DIG_BODY input[id="' + name + '"]').parent('label').on('contextmenu', function (e) {
  3149. e.preventDefault();
  3150. if ($(this).find('#tempWrapper').length === 0) {
  3151. $(this).append('<div id="tempWrapper"></div>');
  3152.  
  3153. $(this).children('#tempWrapper').append('<input id="date_format" value="' + state.fileRenameFormat + '" />');
  3154. $(this).children('#tempWrapper').append(`<div class="IG_POPUP_DIG_BTN">${SVG.CLOSE}</div>`);
  3155. }
  3156. });
  3157. }
  3158. }
  3159. }
  3160.  
  3161. /**
  3162. * showDebugDOM
  3163. * @description Show full DOM tree
  3164. *
  3165. * @return {void}
  3166. */
  3167. function showDebugDOM() {
  3168. $('.IG_POPUP_DIG').remove();
  3169. IG_createDM();
  3170. $('.IG_POPUP_DIG #post_info').text('IG Debug DOM Tree');
  3171.  
  3172. $('.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>`);
  3173. $('.IG_POPUP_DIG .IG_POPUP_DIG_BODY').append(`<span style="display:block;text-align:center;">`);
  3174. $('.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>`);
  3175. $('.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>`);
  3176. $('.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/>`);
  3177. $('.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>`);
  3178. $('.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>`);
  3179. }
  3180.  
  3181. /**
  3182. * showFeedbackDOM
  3183. * @description Show feedback options
  3184. *
  3185. * @return {void}
  3186. */
  3187. function showFeedbackDOM() {
  3188. $('.IG_POPUP_DIG').remove();
  3189. IG_createDM();
  3190. $('.IG_POPUP_DIG #post_info').text('Feedback Options');
  3191.  
  3192. $('.IG_POPUP_DIG .IG_POPUP_DIG_BODY').append(`<span style="display:block;text-align:center;">`);
  3193. $('.IG_POPUP_DIG .IG_POPUP_DIG_BODY span').append(`<button style="margin: 3px;" class="IG_REPORT_FORK"><a href="https://greatest.deepsurf.us/en/scripts/404535-ig-helper/feedback" target="_blank">${_i18n('REPORT_FORK')}</a></button>`);
  3194. $('.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>`);
  3195. $('.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>`);
  3196. }
  3197.  
  3198. /**
  3199. * openNewTab
  3200. * @description Open url in new tab
  3201. *
  3202. * @param {String} link
  3203. * @return {void}
  3204. */
  3205. function openNewTab(link) {
  3206. var a = document.createElement('a');
  3207. a.href = link;
  3208. a.target = '_blank';
  3209.  
  3210. document.body.appendChild(a);
  3211. a.click();
  3212. a.remove();
  3213. }
  3214.  
  3215. /**
  3216. * reloadScript
  3217. * @description Re-register main timer
  3218. *
  3219. * @return {void}
  3220. */
  3221. function reloadScript() {
  3222. clearInterval(state.GL_repeat);
  3223.  
  3224. // unregister event in post element
  3225. state.GL_registerEventList.forEach(item => {
  3226. item.trigger.forEach(bindElement => {
  3227. $(item.element).off('click', bindElement);
  3228. });
  3229. });
  3230. state.GL_registerEventList = [];
  3231.  
  3232. $('.button_wrapper').remove();
  3233. $('.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();
  3234. $('[data-snig]').removeAttr('data-snig');
  3235.  
  3236. state.pageLoaded = false;
  3237. state.firstStarted = false;
  3238. state.currentURL = location.href;
  3239. state.GL_observer.disconnect();
  3240.  
  3241. logger('main timer re-register completed');
  3242. }
  3243.  
  3244. /**
  3245. * logger
  3246. * @description event record
  3247. *
  3248. * @return {void}
  3249. */
  3250. function logger(...messages) {
  3251. var dd = new Date();
  3252. state.GL_logger.push({
  3253. time: dd.getTime(),
  3254. content: [...messages]
  3255. });
  3256.  
  3257. if (state.GL_logger.length > 1000) {
  3258. state.GL_logger = [{
  3259. time: dd.getTime(),
  3260. content: ['logger sliced']
  3261. }, ...state.GL_logger.slice(-999)];
  3262. }
  3263.  
  3264. console.log(`[${dd.toISOString()}]`, ...messages);
  3265. }
  3266.  
  3267. /**
  3268. * initSettings
  3269. * @description Initialize preferences
  3270. *
  3271. * @return {void}
  3272. */
  3273. function initSettings() {
  3274. for (let name in USER_SETTING) {
  3275. if (GM_getValue(name) != null && typeof GM_getValue(name) === 'boolean') {
  3276. USER_SETTING[name] = GM_getValue(name);
  3277.  
  3278. if (name === "MODIFY_VIDEO_VOLUME" && GM_getValue(name) !== true) {
  3279. state.videoVolume = 1;
  3280. }
  3281. }
  3282. }
  3283. }
  3284.  
  3285.  
  3286. /**
  3287. * toggleVolumeSilder
  3288. * @description Toggle display of custom volume slider.
  3289. *
  3290. * @param {object} $videos
  3291. * @param {object} $buttonParent
  3292. * @param {string} loggerType
  3293. * @param {string} customClass
  3294. * @return {void}
  3295. */
  3296. function toggleVolumeSilder($videos, $buttonParent, loggerType, customClass = "") {
  3297. if ($buttonParent.find('div.volume_slider').length === 0) {
  3298. $buttonParent.append(`<div class="volume_slider ${customClass}" />`);
  3299. $buttonParent.find('div.volume_slider').append(`<div><input type="range" max="1" min="0" step="0.05" value="${state.videoVolume}" /></div>`);
  3300. $buttonParent.find('div.volume_slider input').attr('style', `--ig-track-progress: ${(state.videoVolume * 100) + '%'}`);
  3301. $buttonParent.find('div.volume_slider input').on('input', function () {
  3302. var percent = ($(this).val() * 100) + '%';
  3303.  
  3304. state.videoVolume = $(this).val();
  3305. GM_setValue('G_VIDEO_VOLUME', $(this).val());
  3306.  
  3307. $(this).attr('style', `--ig-track-progress: ${percent}`);
  3308.  
  3309. $videos.each(function () {
  3310. logger(`(${loggerType})`, 'video volume changed #slider');
  3311. this.volume = state.videoVolume;
  3312. });
  3313. });
  3314.  
  3315. $buttonParent.find('div.volume_slider input').on('mouseenter', function () {
  3316. var percent = (state.videoVolume * 100) + '%';
  3317. $(this).attr('style', `--ig-track-progress: ${percent}`);
  3318. $(this).val(state.videoVolume);
  3319.  
  3320.  
  3321. $videos.each(function () {
  3322. logger(`(${loggerType})`, 'video volume changed #slider');
  3323. this.volume = state.videoVolume;
  3324. });
  3325. });
  3326.  
  3327. $buttonParent.find('div.volume_slider').on('click', function (e) {
  3328. e.stopPropagation();
  3329. e.preventDefault();
  3330. });
  3331. }
  3332. else {
  3333. $buttonParent.find('div.volume_slider').remove();
  3334. }
  3335. }
  3336.  
  3337. function openImageViewer(imageUrl) {
  3338. removeImageViewer();
  3339.  
  3340. $('body').append(
  3341. `<div id="imageViewer">
  3342. <div id="iv_header">
  3343. <div style="flex:1;">Image Viewer</div>
  3344. <div id="iv_close">${SVG.CLOSE}</div>
  3345. </div>
  3346. <img id="iv_image" src="" />
  3347. </div>`);
  3348.  
  3349. const $container = $('#imageViewer');
  3350. const $header = $('#iv_header');
  3351. const $closeIcon = $('#iv_close');
  3352. const $image = $('#iv_image');
  3353.  
  3354.  
  3355. $image.attr('src', imageUrl);
  3356. $container.css('display', 'flex');
  3357.  
  3358. let scale = 0.75;
  3359. let posX = 0, posY = 0;
  3360. let isDragging = false;
  3361. let startX, startY;
  3362.  
  3363. $image.on('load', () => {
  3364. posX = (window.innerWidth - $image[0].width) / 2;
  3365. posY = (window.innerHeight - $image[0].height) / 2;
  3366. updateImageStyle();
  3367. });
  3368.  
  3369. $image.on('dragstart drop', (e) => {
  3370. e.preventDefault();
  3371. });
  3372.  
  3373. $image.on('click', (e) => {
  3374. e.preventDefault();
  3375. e.stopPropagation();
  3376. });
  3377.  
  3378. $image.on('wheel', (e) => {
  3379. e.preventDefault();
  3380. scale += e.originalEvent.deltaY > 0 ? -0.15 : 0.15;
  3381. scale = Math.min(Math.max(0.75, scale), 5);
  3382. updateImageStyle();
  3383. });
  3384.  
  3385. $image.on('mousedown', (e) => {
  3386. isDragging = true;
  3387. startX = e.pageX - posX;
  3388. startY = e.pageY - posY;
  3389. $image.css('cursor', 'grabbing');
  3390. });
  3391.  
  3392. $image.on('mouseup', () => {
  3393. isDragging = false;
  3394. $image.css('cursor', 'grab');
  3395. });
  3396.  
  3397. $(document).on('mousemove.igHelper', (e) => {
  3398. if (!isDragging) return;
  3399. e.preventDefault();
  3400.  
  3401. posX = e.pageX - startX;
  3402. posY = e.pageY - startY;
  3403.  
  3404. updateImageStyle();
  3405. });
  3406.  
  3407. $container.on('click', () => {
  3408. removeImageViewer();
  3409. });
  3410.  
  3411. $closeIcon.on('click', () => {
  3412. removeImageViewer();
  3413. });
  3414.  
  3415. $header.on('click', (e) => {
  3416. e.preventDefault();
  3417. e.stopPropagation();
  3418. });
  3419.  
  3420. function updateImageStyle() {
  3421. $image.css('transform', `scale(${scale})`);
  3422. $image.css('left', `${posX}px`);
  3423. $image.css('top', `${posY}px`);
  3424. }
  3425. }
  3426.  
  3427. function removeImageViewer() {
  3428. $('#imageViewer').remove();
  3429. $(document).off('mousemove.igHelper');
  3430. }
  3431.  
  3432. /**
  3433. * translateText
  3434. * @description i18n translation text
  3435. *
  3436. * @return {void}
  3437. */
  3438. function translateText() {
  3439. var eLocale = {
  3440. "en-US": {
  3441. "NOTICE_UPDATE_TITLE": "Wololo! New version released.",
  3442. "NOTICE_UPDATE_CONTENT": "IG-Helper has released a new version, click here to update.",
  3443. "CHECK_UPDATE": "Checking for Script Updates",
  3444. "CHECK_UPDATE_MENU": "Checking for Updates",
  3445. "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.",
  3446. "RELOAD_SCRIPT": "Reload Script",
  3447. "DONATE": "Donate",
  3448. "FEEDBACK": "Feedback",
  3449. "NEW_TAB": "Open in New Tab",
  3450. "SHOW_DOM_TREE": "Show DOM Tree",
  3451. "SELECT_AND_COPY": "Select All and Copy from the Input Box",
  3452. "DOWNLOAD_DOM_TREE": "Download DOM Tree as a Text File",
  3453. "REPORT_GITHUB": "Report an Issue on GitHub",
  3454. "REPORT_DISCORD": "Report an Issue on Discord Support Server",
  3455. "REPORT_FORK": "Report an Issue on Greasy Fork",
  3456. "DEBUG": "Debug Window",
  3457. "CLOSE": "Close",
  3458. "ALL_CHECK": "Select All",
  3459. "BATCH_DOWNLOAD_SELECTED": "Download Selected Resources",
  3460. "BATCH_DOWNLOAD_DIRECT": "Download All Resources",
  3461. "IMG": "Image",
  3462. "VID": "Video",
  3463. "DW": "Download",
  3464. "DW_ALL": "Download All Resources",
  3465. "THUMBNAIL_INTRO": "Download Video Thumbnail",
  3466. "LOAD_BLOB_ONE": "Loading Blob Media...",
  3467. "LOAD_BLOB_MULTIPLE": "Loading Blob Media and Others...",
  3468. "LOAD_BLOB_RELOAD": "Detecting Blob Media, reloading...",
  3469. "NO_CHECK_RESOURCE": "You need to select a resource to download.",
  3470. "NO_VID_URL": "Cannot find video URL.",
  3471. "SETTING": "Settings",
  3472. "AUTO_RENAME": "Automatically Rename Files (Right-Click to Set)",
  3473. "RENAME_SHORTCODE": "Rename the File and Include Shortcode",
  3474. "RENAME_PUBLISH_DATE": "Set Renamed File Timestamp to Resource Publish Date",
  3475. "RENAME_LOCATE_DATE": "Modify Renamed File Timestamp Date Format (Right-Click to Set)",
  3476. "DISABLE_VIDEO_LOOPING": "Disable Video Auto-looping",
  3477. "HTML5_VIDEO_CONTROL": "Display HTML5 Video Controller",
  3478. "REDIRECT_CLICK_USER_STORY_PICTURE": "Redirect When Clicking on User's Story Picture",
  3479. "FORCE_FETCH_ALL_RESOURCES": "Force Fetch All Resources in the Post",
  3480. "DIRECT_DOWNLOAD_VISIBLE_RESOURCE": "Directly Download the Visible Resources in the Post",
  3481. "DIRECT_DOWNLOAD_ALL": "Directly Download All Resources in the Post",
  3482. "MODIFY_VIDEO_VOLUME": "Modify Video Volume (Right-Click to Set)",
  3483. "SCROLL_BUTTON": "Enable Scroll Buttons for Reels Page",
  3484. "FORCE_RESOURCE_VIA_MEDIA": "Force Fetch Resource via Media API",
  3485. "USE_BLOB_FETCH_WHEN_MEDIA_RATE_LIMIT": "Use Alternative Methods to Download When the Media API is Not Accessible",
  3486. "NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST": "Always Use Media API for 'Open in New Tab' in Posts",
  3487. "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",
  3488. "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.",
  3489. "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.",
  3490. "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.",
  3491. "DISABLE_VIDEO_LOOPING_INTRO": "Disable video auto-looping in Reels and posts.",
  3492. "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.",
  3493. "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.",
  3494. "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.",
  3495. "DIRECT_DOWNLOAD_VISIBLE_RESOURCE_INTRO": "Directly download the current resources available in the post.",
  3496. "DIRECT_DOWNLOAD_ALL_INTRO": "When you click the download button, all resources in the post will be forcibly fetched and downloaded.",
  3497. "MODIFY_VIDEO_VOLUME_INTRO": "Modify the video playback volume in Reels and posts (right-click to open the volume setting slider).",
  3498. "SCROLL_BUTTON_INTRO": "Enable scroll buttons for the lower right corner of the Reels page.",
  3499. "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.",
  3500. "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).",
  3501. "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.",
  3502. "SKIP_VIEW_STORY_CONFIRM": "Skip the Confirmation Page for Viewing a Story/Highlight",
  3503. "SKIP_VIEW_STORY_CONFIRM_INTRO": "Automatically skip when confirmation page is shown in story or highlight."
  3504. }
  3505. };
  3506.  
  3507. var resultUnsorted = Object.assign({}, eLocale, state.locale);
  3508. var resultSorted = Object.keys(resultUnsorted).sort().reduce(
  3509. (obj, key) => {
  3510. obj[key] = resultUnsorted[key];
  3511. return obj;
  3512. }, {}
  3513. );
  3514.  
  3515. return resultSorted;
  3516. }
  3517.  
  3518. /**
  3519. * getTranslationText
  3520. * @description i18n translation text
  3521. *
  3522. * @param {String} lang
  3523. * @return {Object}
  3524. */
  3525. async function getTranslationText(lang) {
  3526. return new Promise((resolve, reject) => {
  3527. GM_xmlhttpRequest({
  3528. method: "GET",
  3529. url: `https://raw.githubusercontent.com/SN-Koarashi/ig-helper/master/locale/translations/${lang}.json`,
  3530. onload: function (response) {
  3531. try {
  3532. let obj = JSON.parse(response.response);
  3533. resolve(obj);
  3534. }
  3535. catch (err) {
  3536. reject(err);
  3537. }
  3538. },
  3539. onerror: function (err) {
  3540. logger('getTranslationText()', 'reject', err);
  3541. reject(err);
  3542. }
  3543. });
  3544. });
  3545. }
  3546.  
  3547. /**
  3548. * _i18n
  3549. * @description Perform i18n translation
  3550. *
  3551. * @param {String} text
  3552. * @return {void}
  3553. */
  3554. function _i18n(text) {
  3555. const translate = translateText();
  3556.  
  3557. if (translate[state.lang] != undefined && translate[state.lang][text] != undefined) {
  3558. return translate[state.lang][text];
  3559. }
  3560. else {
  3561. return translate["en-US"][text];
  3562. }
  3563. }
  3564.  
  3565. /**
  3566. * repaintingTranslations
  3567. * @description Perform i18n translation
  3568. *
  3569. * @return {void}
  3570. */
  3571. function repaintingTranslations() {
  3572. $('[data-ih-locale]').each(function () {
  3573. $(this).text(_i18n($(this).attr('data-ih-locale')));
  3574. });
  3575. $('[data-ih-locale-title]').each(function () {
  3576. $(this).attr('title', _i18n($(this).attr('data-ih-locale-title')));
  3577. });
  3578. }
  3579.  
  3580. /* register all events */
  3581.  
  3582. // Running if document is ready
  3583. $(function () {
  3584. function ConvertDOM(domEl) {
  3585. var obj = [];
  3586. for (var ele of domEl) {
  3587. obj.push({
  3588. tagName: ele.tagName,
  3589. id: ele.id,
  3590. className: ele.className
  3591. });
  3592. }
  3593.  
  3594. return obj;
  3595. }
  3596.  
  3597. function setDOMTreeContent() {
  3598. let text = $('div[id^="mount"]')[0];
  3599. var logger = "";
  3600. state.GL_logger.forEach(log => {
  3601. var jsonData = JSON.stringify(log.content, function (key, value) {
  3602. if (Array.isArray(this)) {
  3603. if (typeof value === "object" && value instanceof jQuery) {
  3604. return ConvertDOM(value);
  3605. }
  3606. return value;
  3607. }
  3608. else {
  3609. return value;
  3610. }
  3611. }, "\t");
  3612. logger += `${new Date(log.time).toISOString()}: ${jsonData}\n`
  3613. });
  3614. $('.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);
  3615. }
  3616.  
  3617. $('body').on('click', '.IG_POPUP_DIG .IG_POPUP_DIG_BODY .IG_DISPLAY_DOM_TREE', function () {
  3618. setDOMTreeContent();
  3619. });
  3620.  
  3621. $('body').on('click', '.IG_POPUP_DIG .IG_POPUP_DIG_BODY .IG_SELECT_DOM_TREE', function () {
  3622. $('.IG_POPUP_DIG .IG_POPUP_DIG_BODY textarea').select();
  3623. document.execCommand('copy');
  3624. });
  3625.  
  3626. $('body').on('click', '.IG_POPUP_DIG .IG_POPUP_DIG_BODY .IG_DOWNLOAD_DOM_TREE', function () {
  3627. if ($('.IG_POPUP_DIG .IG_POPUP_DIG_BODY textarea').text().length === 0) {
  3628. setDOMTreeContent();
  3629. }
  3630.  
  3631. var text = $('.IG_POPUP_DIG .IG_POPUP_DIG_BODY textarea').text();
  3632. var a = document.createElement("a");
  3633. var file = new Blob([text], { type: "text/plain" });
  3634. a.href = URL.createObjectURL(file);
  3635. a.download = "DOMTree-" + new Date().getTime() + ".txt";
  3636.  
  3637. document.body.appendChild(a);
  3638. a.click();
  3639. a.remove();
  3640. });
  3641.  
  3642. // Close the download dialog if user click the close icon
  3643. $('body').on('click', '.IG_POPUP_DIG_BTN, .IG_POPUP_DIG_BG', function () {
  3644. if ($(this).parent('#tempWrapper').length > 0) {
  3645. $(this).parent('#tempWrapper').fadeOut(250, function () {
  3646. $(this).remove();
  3647. });
  3648. }
  3649. else {
  3650. $('.IG_POPUP_DIG').remove();
  3651. }
  3652. });
  3653.  
  3654. $(window).on('keydown', function (e) {
  3655. // Hot key [Alt+Q] to close the download dialog
  3656. if (e.which == '81' && e.altKey) {
  3657. $('.IG_POPUP_DIG').remove();
  3658. e.preventDefault();
  3659. }
  3660. // Hot key [Alt+W] to open the settings dialog
  3661. if (e.which == '87' && e.altKey) {
  3662. showSetting();
  3663. e.preventDefault();
  3664. }
  3665.  
  3666. // Hot key [Alt+Z] to open the settings dialog
  3667. if (e.which == '90' && e.altKey) {
  3668. showDebugDOM();
  3669. e.preventDefault();
  3670. }
  3671.  
  3672. // Hot key [Alt+R] to open the settings dialog
  3673. if (e.which == '82' && e.altKey) {
  3674. reloadScript();
  3675. e.preventDefault();
  3676. }
  3677.  
  3678. // Hot key [Alt+S] to download story/highlights resource
  3679. if (e.which == '83' && e.altKey) {
  3680. if (location.href.match(/^(https:\/\/www\.instagram\.com\/stories\/)/ig) && $('.IG_DWSTORY').length > 0) {
  3681. $('.IG_DWSTORY')?.trigger("click");
  3682. }
  3683. if (location.href.match(/^(https:\/\/www\.instagram\.com\/stories\/highlights\/)/ig) && $('.IG_DWHISTORY').length > 0) {
  3684. $('.IG_DWHISTORY')?.trigger("click");
  3685. }
  3686. e.preventDefault();
  3687. }
  3688. });
  3689.  
  3690. $('body').on('change', '.IG_POPUP_DIG input', function () {
  3691. var name = $(this).attr('id');
  3692.  
  3693. if (name && USER_SETTING[name] !== undefined) {
  3694. let isChecked = $(this).prop('checked');
  3695. GM_setValue(name, isChecked);
  3696. USER_SETTING[name] = isChecked;
  3697.  
  3698. console.log('user settings', name, isChecked);
  3699. }
  3700. });
  3701.  
  3702. $('body').on('click', '.IG_POPUP_DIG .globalSettings', function (e) {
  3703. if ($(this).find('#tempWrapper').length > 0) {
  3704. e.preventDefault();
  3705. }
  3706. });
  3707.  
  3708. $('body').on('change', '.IG_POPUP_DIG #tempWrapper input:not(#date_format)', function () {
  3709. let value = $(this).val();
  3710.  
  3711. if ($(this).attr('type') == 'range') {
  3712. $(this).next().val(value);
  3713. }
  3714. else {
  3715. $(this).prev().val(value);
  3716. }
  3717.  
  3718. if (value >= 0 && value <= 1) {
  3719. state.videoVolume = value;
  3720. GM_setValue('G_VIDEO_VOLUME', value);
  3721. }
  3722. });
  3723.  
  3724. $('body').on('input', '.IG_POPUP_DIG #tempWrapper input:not(#date_format)', function () {
  3725. if ($(this).attr('type') == 'range') {
  3726. let value = $(this).val();
  3727. $(this).next().val(value);
  3728. }
  3729. else {
  3730. let value = $(this).val();
  3731. if (value >= 0 && value <= 1) {
  3732. $(this).prev().val(value);
  3733. }
  3734. else {
  3735. if (value < 0) {
  3736. $(this).val(0);
  3737. }
  3738. else {
  3739. $(this).val(1);
  3740. }
  3741. }
  3742. }
  3743. });
  3744.  
  3745. $('body').on('input', '.IG_POPUP_DIG #tempWrapper input#date_format', function () {
  3746. GM_setValue('G_RENAME_FORMAT', $(this).val());
  3747. state.fileRenameFormat = $(this).val();
  3748. });
  3749.  
  3750. $('body').on('click', 'a[data-needed="direct"]', function (e) {
  3751. e.preventDefault();
  3752. triggerLinkElement(this);
  3753. });
  3754.  
  3755. $('body').on('click', '.IG_POPUP_DIG_BODY .newTab', function () {
  3756. // replace https://instagram.ftpe8-2.fna.fbcdn.net/ to https://scontent.cdninstagram.com/ becase of same origin policy (some video)
  3757.  
  3758. if (USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && USER_SETTING.NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST) {
  3759. triggerLinkElement($(this).parent().children('a').first()[0], true);
  3760. }
  3761. else {
  3762. var urlObj = new URL($(this).parent().children('a').attr('data-href'));
  3763. urlObj.host = 'scontent.cdninstagram.com';
  3764.  
  3765. openNewTab(urlObj.href);
  3766. }
  3767. });
  3768.  
  3769. $('body').on('click', '.IG_POPUP_DIG_BODY .videoThumbnail', function () {
  3770. let timestamp = new Date().getTime();
  3771.  
  3772. if (USER_SETTING.RENAME_PUBLISH_DATE && $(this).parent().children('a').attr('datetime')) {
  3773. timestamp = $(this).parent().children('a').attr('datetime');
  3774. }
  3775.  
  3776. let postPath = $(this).parent().children('a').attr('data-path') ?? $('#article-id').text();
  3777.  
  3778. saveFiles($(this).parent().children('a').find('img').first().attr('src'), $(this).parent().children('a').attr('data-username'), 'thumbnail', timestamp, 'jpg', postPath);
  3779. });
  3780.  
  3781. // Running if user left-click download icon in stories
  3782. $('body').on('click', '.IG_DWSTORY', function () {
  3783. onStory(true);
  3784. });
  3785.  
  3786. // Running if user left-click all download icon in stories
  3787. $('body').on('click', '.IG_DWSTORY_ALL', function () {
  3788. onStoryAll();
  3789. });
  3790.  
  3791. // Running if user left-click 'open in new tab' icon in stories
  3792. $('body').on('click', '.IG_DWNEWTAB', function (e) {
  3793. e.preventDefault();
  3794. onStory(true, true, true);
  3795. });
  3796.  
  3797. // Running if user left-click download thumbnail icon in stories
  3798. $('body').on('click', '.IG_DWSTORY_THUMBNAIL', function () {
  3799. onStoryThumbnail(true);
  3800. });
  3801.  
  3802. // Running if user left-click download icon in profile
  3803. $('body').on('click', '.IG_DWPROFILE', function (e) {
  3804. e.stopPropagation();
  3805. onProfileAvatar(true);
  3806. });
  3807.  
  3808. // Running if user left-click download icon in highlight stories
  3809. $('body').on('click', '.IG_DWHISTORY', function () {
  3810. onHighlightsStory(true);
  3811. });
  3812.  
  3813. // Running if user left-click all download icon in highlight stories
  3814. $('body').on('click', '.IG_DWHISTORY_ALL', function () {
  3815. onHighlightsStoryAll();
  3816. });
  3817.  
  3818. // Running if user left-click 'open in new tab' icon in highlight stories
  3819. $('body').on('click', '.IG_DWHINEWTAB', function (e) {
  3820. e.preventDefault();
  3821. onHighlightsStory(true, true);
  3822. });
  3823.  
  3824. // Running if user left-click thumbnail download icon in highlight stories
  3825. $('body').on('click', '.IG_DWHISTORY_THUMBNAIL', function () {
  3826. onHighlightsStoryThumbnail(true);
  3827. });
  3828.  
  3829. // Running if user left-click download icon in reels
  3830. $('body').on('click', '.IG_REELS', function () {
  3831. onReels(true, true);
  3832. });
  3833.  
  3834. // Running if user left-click newtab icon in reels
  3835. $('body').on('click', '.IG_REELS_NEWTAB', function () {
  3836. onReels(true, true, true);
  3837. });
  3838.  
  3839. // Running if user left-click download icon in reels
  3840. $('body').on('click', '.IG_REELS_THUMBNAIL', function () {
  3841. onReels(true, false);
  3842. });
  3843.  
  3844. // Running if user right-click profile picture in stories area
  3845. $('body').on('mousedown', 'button[role="menuitem"], div[role="menuitem"], ul > li[tabindex="-1"] > div[role="button"]', function (e) {
  3846. // Right-Click || Middle-Click
  3847. if (e.which === 3 || e.which === 2) {
  3848. if (location.href === 'https://www.instagram.com/' && USER_SETTING.REDIRECT_CLICK_USER_STORY_PICTURE) {
  3849. e.preventDefault();
  3850. if ($(this).find('canvas._aarh, canvas + span > img').length > 0) {
  3851. const targetUrl = 'https://www.instagram.com/' + $(this).children('div').last().text();
  3852. if (e.which === 2) {
  3853. GM_openInTab(targetUrl);
  3854. }
  3855. else {
  3856. location.href = targetUrl;
  3857. }
  3858. }
  3859. }
  3860. }
  3861. });
  3862.  
  3863. $('body').on('change', '.IG_POPUP_DIG_TITLE .checkbox', function () {
  3864. var isChecked = $(this).find('input').prop('checked');
  3865. $('.IG_POPUP_DIG_BODY .inner_box').each(function () {
  3866. $(this).prop('checked', isChecked);
  3867. });
  3868. });
  3869.  
  3870. $('body').on('change', '.IG_POPUP_DIG_BODY .inner_box', function () {
  3871. var checked = $('.IG_POPUP_DIG_BODY .inner_box:checked').length;
  3872. var total = $('.IG_POPUP_DIG_BODY .inner_box').length;
  3873.  
  3874.  
  3875. $('.IG_POPUP_DIG_TITLE .checkbox').find('input').prop('checked', checked == total);
  3876. });
  3877.  
  3878. $('body').on('click', '.IG_POPUP_DIG_TITLE #batch_download_selected', function () {
  3879. let index = 0;
  3880. $('.IG_POPUP_DIG_BODY a[data-needed="direct"]').each(function () {
  3881. if ($(this).prev().children('input').prop('checked')) {
  3882. $(this).trigger("click");
  3883. index++;
  3884. }
  3885. });
  3886.  
  3887. if (index == 0) {
  3888. alert(_i18n('NO_CHECK_RESOURCE'));
  3889. }
  3890. });
  3891.  
  3892. $('body').on('change', '.IG_POPUP_DIG_TITLE #langSelect', function () {
  3893. GM_setValue('lang', $(this).val());
  3894. state.lang = $(this).val();
  3895.  
  3896. if (state.lang?.startsWith('en') || state.locale[state.lang] != null) {
  3897. repaintingTranslations();
  3898. registerMenuCommand();
  3899. }
  3900. else {
  3901. getTranslationText(state.lang).then((res) => {
  3902. state.locale[state.lang] = res;
  3903. repaintingTranslations();
  3904. registerMenuCommand();
  3905. }).catch((err) => {
  3906. console.error('getTranslationText catch error:', err);
  3907. });
  3908. }
  3909. });
  3910.  
  3911. $('body').on('click', '.IG_POPUP_DIG_TITLE #batch_download_direct', function () {
  3912. $('.IG_POPUP_DIG_BODY a[data-needed="direct"]').each(function () {
  3913. $(this).trigger("click");
  3914. });
  3915. });
  3916.  
  3917. const audio_observer = new MutationObserver((mutationsList) => {
  3918. for (const mutation of mutationsList) {
  3919. if (mutation.type === 'childList') {
  3920. mutation.addedNodes.forEach((node) => {
  3921. const $videos = $(node).find('video');
  3922. if ($videos.length > 0) {
  3923. // Modify video volume
  3924. if (USER_SETTING.MODIFY_VIDEO_VOLUME) {
  3925. $videos.each(function () {
  3926. $(this).on('play playing', function () {
  3927. if (!$(this).data('modify')) {
  3928. $(this).attr('data-modify', true);
  3929. this.volume = state.videoVolume;
  3930. logger('(audio_observer) Added video event listener #modify');
  3931. }
  3932. });
  3933. });
  3934. }
  3935.  
  3936. if (location.pathname.match(/^(\/stories\/)/ig)) {
  3937. const isHighlight = location.pathname.match(/^(\/stories\/highlights\/)/ig) != null;
  3938. const storyType = isHighlight ? 'highlight' : 'story';
  3939.  
  3940. $videos.each(function () {
  3941. $(this).on('timeupdate', function () {
  3942. if (!$(this).data('modify-thumbnail')) {
  3943. let $video = $(this);
  3944. if ($video.parents('div[style][class]').filter(function () {
  3945. return $(this).width() == $video.width();
  3946. }).find('.IG_DWSTORY_THUMBNAIL, .IG_DWHISTORY_THUMBNAIL').length === 0) {
  3947. $(this).attr('data-modify-thumbnail', true);
  3948.  
  3949. if (isHighlight) {
  3950. onHighlightsStoryThumbnail(false);
  3951. }
  3952. else {
  3953. onStoryThumbnail(false);
  3954. }
  3955.  
  3956. logger(`(${storyType})`, 'Manually inserting thumbnail button');
  3957. }
  3958. else {
  3959. $(this).attr('data-modify-thumbnail', true);
  3960. logger(`(${storyType})`, 'Thumbnail button already inserted');
  3961. }
  3962. }
  3963. });
  3964.  
  3965. var $video = $(this);
  3966.  
  3967. if (USER_SETTING.HTML5_VIDEO_CONTROL) {
  3968. if (!$video.data('controls')) {
  3969. logger(`(${storyType})`, 'Added video html5 contorller #modify');
  3970.  
  3971. if (USER_SETTING.MODIFY_VIDEO_VOLUME) {
  3972. this.volume = state.videoVolume;
  3973.  
  3974. $video.on('loadstart', function () {
  3975. this.volume = state.videoVolume;
  3976. });
  3977. }
  3978.  
  3979. let $videoParent = $video.parents('div').filter(function () {
  3980. return $(this).attr('class') == null && $(this).attr('style') == null;
  3981. }).first();
  3982.  
  3983. // story bottom bar
  3984. let $bottomBar = $videoParent.next();
  3985. $bottomBar.hide();
  3986.  
  3987. // read more button in center
  3988. let $readMoreButton = $videoParent.find('div[class][role="button"]');
  3989. $readMoreButton.hide();
  3990.  
  3991. const hideContextmenu = function (e) {
  3992. e.preventDefault();
  3993. $video.css('z-index', '2');
  3994. $video.attr('controls', true);
  3995.  
  3996. $readMoreButton.hide();
  3997. $bottomBar.hide();
  3998.  
  3999. toggleVolumeSilder($video, $video.parents('div[style][class]').filter(function () {
  4000. return $(this).width() == $video.width();
  4001. }).first(), storyType, 'vertical');
  4002. };
  4003.  
  4004. // Hide layout to show controller
  4005. $video.parent().find('video + div').on('contextmenu', hideContextmenu);
  4006. $readMoreButton.on('contextmenu', hideContextmenu);
  4007. $bottomBar.on('contextmenu', hideContextmenu);
  4008.  
  4009. // Restore layout to show details interface
  4010. $video.on('contextmenu', function (e) {
  4011. e.preventDefault();
  4012. $video.css('z-index', '-1');
  4013. $video.removeAttr('controls');
  4014.  
  4015. $bottomBar.show();
  4016. $readMoreButton.show();
  4017.  
  4018. toggleVolumeSilder($video, $video.parents('div[style][class]').filter(function () {
  4019. return $(this).width() == $video.width();
  4020. }).first(), storyType, 'vertical');
  4021. });
  4022.  
  4023. $video.on('volumechange', function () {
  4024. // This is mute/unmute's icon
  4025. 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();
  4026.  
  4027. var is_elelment_muted = $element_mute_button.find('svg > path[d^="M16.636"]').length === 0;
  4028.  
  4029. if (this.muted != is_elelment_muted) {
  4030. this.volume = state.videoVolume;
  4031. $element_mute_button?.trigger("click");
  4032. }
  4033.  
  4034. if ($(this).attr('data-completed')) {
  4035. state.videoVolume = this.volume;
  4036. GM_setValue('G_VIDEO_VOLUME', this.volume);
  4037. }
  4038.  
  4039. if (this.volume == state.videoVolume) {
  4040. $(this).attr('data-completed', true);
  4041. }
  4042. });
  4043.  
  4044. $video.css('position', 'absolute');
  4045. $video.css('z-index', '2');
  4046. $video.attr('data-controls', true);
  4047. $video.attr('controls', true);
  4048. }
  4049. }
  4050. else {
  4051. toggleVolumeSilder($video, $video.parents('div[style][class]').filter(function () {
  4052. return $(this).width() == $video.width();
  4053. }).first(), storyType, 'vertical');
  4054. }
  4055. });
  4056. }
  4057. }
  4058. });
  4059. }
  4060. }
  4061. });
  4062.  
  4063. audio_observer.observe($('div[id^="mount"]')[0], {
  4064. childList: true,
  4065. subtree: true,
  4066. });
  4067. });
  4068. })(jQuery);