IG Helper

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

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