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