IG조수

게시물의 사진과 동영상뿐만 아니라 스토리, 릴 또는 프로필 사진도 다운로드할 수 있습니다.

2025-02-08 기준 버전입니다. 최신 버전을 확인하세요.

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