IG小助手

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

当前为 2025-02-15 提交的版本,查看 最新版本

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址