IG小助手

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

当前为 2024-09-07 提交的版本,查看 最新版本

  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.29.10
  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_addStyle
  18. // @grant GM_setValue
  19. // @grant GM_getValue
  20. // @grant GM_xmlhttpRequest
  21. // @grant GM_registerMenuCommand
  22. // @grant GM_getResourceText
  23. // @grant GM_openInTab
  24. // @connect i.instagram.com
  25. // @require https://code.jquery.com/jquery-3.7.1.min.js#sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=
  26. // @resource INTERNAL_CSS https://raw.githubusercontent.com/SN-Koarashi/ig-helper/master/style.css
  27. // @resource LOCATE_DATE_LIST_TEXT https://raw.githubusercontent.com/SN-Koarashi/ig-helper/master/date_locate.json
  28. // @resource LOCALE_TEXT https://raw.githubusercontent.com/SN-Koarashi/ig-helper/master/locale.json
  29. // @supportURL https://github.com/SN-Koarashi/ig-helper/
  30. // @contributionURL https://ko-fi.com/snkoarashi
  31. // @icon https://www.google.com/s2/favicons?domain=www.instagram.com
  32. // @compatible firefox >= 100
  33. // @compatible chrome >= 100
  34. // @compatible edge >= 100
  35. // @license GPL-3.0-only
  36. // @run-at document-idle
  37. // ==/UserScript==
  38.  
  39. (function($) {
  40. 'use strict';
  41.  
  42. /******** USER SETTINGS ********/
  43. // !!! DO NOT CHANGE THIS AREA !!!
  44. // PLEASE CHANGE SETTING WITH MENU
  45. const USER_SETTING = {
  46. 'AUTO_RENAME': true,
  47. 'RENAME_PUBLISH_DATE': true,
  48. 'DISABLE_VIDEO_LOOPING': false,
  49. 'HTML5_VIDEO_CONTROL': false,
  50. 'REDIRECT_CLICK_USER_STORY_PICTURE': false,
  51. 'FORCE_FETCH_ALL_RESOURCES': false,
  52. 'DIRECT_DOWNLOAD_VISIBLE_RESOURCE': false,
  53. 'DIRECT_DOWNLOAD_ALL': false,
  54. 'MODIFY_VIDEO_VOLUME': false,
  55. 'SCROLL_BUTTON': true,
  56. 'FORCE_RESOURCE_VIA_MEDIA': false,
  57. 'USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT': false,
  58. 'NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST': false
  59. };
  60. const CHILD_NODES = ['RENAME_PUBLISH_DATE', 'USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT', 'NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST'];
  61. const LOCATE_DATE_LIST = JSON.parse(GM_getResourceText('LOCATE_DATE_LIST_TEXT'));
  62. var VIDEO_VOLUME = (GM_getValue('G_VIDEO_VOLUME'))?GM_getValue('G_VIDEO_VOLUME'):1;
  63. var LOCATE_DATE_FORMAT = (GM_getValue('G_LOCATE_DATE_FORMAT'))? GM_getValue('G_LOCATE_DATE_FORMAT') : GM_getValue('lang') || navigator.language || navigator.userLanguage;
  64. var TEMP_FETCH_RATE_LITMIT = false;
  65. 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%';
  66. /*******************************/
  67.  
  68. // Icon download by https://www.flaticon.com/authors/pixel-perfect
  69. const SVG = {
  70. 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>',
  71. 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>',
  72. 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>',
  73. 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>'
  74. };
  75.  
  76. const checkInterval = 250;
  77. const style = GM_getResourceText("INTERNAL_CSS");
  78. const locale = JSON.parse(GM_getResourceText("LOCALE_TEXT"));
  79.  
  80. var lang = GM_getValue('lang') || navigator.language || navigator.userLanguage;
  81. var currentURL = location.href;
  82. var firstStarted = false;
  83. var pageLoaded = false;
  84.  
  85. var GL_referrer;
  86. var GL_postPath;
  87. var GL_username;
  88. var GL_repeat;
  89. var GL_dataCache = {
  90. stories: {},
  91. highlights: {}
  92. };
  93. var GL_observer = new MutationObserver(function (mutation, owner) {
  94. onReadyMyDW();
  95. });
  96.  
  97. initSettings();
  98. GM_addStyle(style);
  99. GM_registerMenuCommand(_i18n('SETTING'), () => {
  100. showSetting();
  101. },{
  102. accessKey: "w"
  103. });
  104. GM_registerMenuCommand(_i18n('DONATE'), () => {
  105. GM_openInTab("https://ko-fi.com/snkoarashi", {active: true});
  106. },{
  107. accessKey: "d"
  108. });
  109. GM_registerMenuCommand(_i18n('DEBUG'), () => {
  110. showDebugDOM();
  111. },{
  112. accessKey: "z"
  113. });
  114. GM_registerMenuCommand(_i18n('FEEDBACK'), () => {
  115. GM_openInTab("https://greasyfork.org/zh-TW/scripts/404535-ig-helper/feedback", {active: true});
  116. },{
  117. accessKey: "f"
  118. });
  119. GM_registerMenuCommand(_i18n('RELOAD_SCRIPT'), () => {
  120. reloadScript();
  121. },{
  122. accessKey: "r"
  123. });
  124.  
  125. // Main Timer
  126. var timer = setInterval(function(){
  127. // page loading or unnecessary route
  128. if($('div#splash-screen').length > 0 && !$('div#splash-screen').is(':hidden') ||
  129. location.pathname.match(/^\/(explore(\/.*)?|challenge\/?.*|direct\/?.*|qr\/?|accounts\/.*|emails\/.*|language\/?.*?|your_activity\/?.*|settings\/help(\/.*)?$)$/ig) ||
  130. !location.hostname.startsWith('www.')
  131. ){
  132. pageLoaded = false;
  133. return;
  134. }
  135.  
  136. if(currentURL != location.href || !firstStarted || !pageLoaded){
  137. console.log('Main Timer', 'trigging');
  138.  
  139. clearInterval(GL_repeat);
  140. pageLoaded = false;
  141. firstStarted = true;
  142. currentURL = location.href;
  143. GL_observer.disconnect();
  144.  
  145. if(location.href.startsWith("https://www.instagram.com/p/") || location.pathname.match(/^\/(.*?)\/p\//ig) || location.href.startsWith("https://www.instagram.com/reel/")){
  146. GL_dataCache.stories = {};
  147.  
  148. console.log('isDialog');
  149.  
  150. // This is a delayed function call that prevents the dialog element from appearing before the function is called.
  151. var dialogTimer = setInterval(()=>{
  152. // body > div[id^="mount"] section nav + div > article << (mobile page in single post) >>
  153. // 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) >>
  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, section:visible > main > div > div > div > div > div > hr, body > div[id^="mount"] section nav + div > article').length > 0){
  157. clearInterval(dialogTimer);
  158.  
  159. // This is to prevent the detection of the "Modify Video Volume" setting from being too slow.
  160. setTimeout(()=>{
  161. onReadyMyDW(false);
  162. }, 15);
  163. }
  164. },100);
  165.  
  166. pageLoaded = true;
  167. }
  168.  
  169. if(location.href.startsWith("https://www.instagram.com/reels/")){
  170. console.log('isReels');
  171. setTimeout(()=>{
  172. onReels(false);
  173. },150);
  174. pageLoaded = true;
  175. }
  176.  
  177. if(location.href.split("?")[0] == "https://www.instagram.com/"){
  178. GL_dataCache.stories = {};
  179.  
  180. let hasReferrer = GL_referrer?.match(/^\/stories\//ig) != null;
  181.  
  182. console.log('isHomepage', hasReferrer);
  183. setTimeout(()=>{
  184. onReadyMyDW(false, hasReferrer);
  185.  
  186. const element = $('div[id^="mount"] > div > div div > section > main div:not([class]):not([style]) > div > article')?.parent()[0];
  187. if(element){
  188. GL_observer.observe(element, {
  189. childList: true
  190. });
  191. }
  192. },150);
  193.  
  194. pageLoaded = true;
  195. }
  196. if($('header > section:first img[alt]').length && location.pathname.match(/^(\/)([0-9A-Za-z\.\-_]+)\/?(tagged|reels|saved)?\/?$/ig) && !location.pathname.match(/^(\/explore\/?$|\/stories(\/.*)?$|\/p\/)/ig)) {
  197. console.log('isProfile');
  198. setTimeout(()=>{
  199. onProfileAvatar(false);
  200. },150);
  201. pageLoaded = true;
  202. }
  203.  
  204. if(!pageLoaded){
  205. // Call Instagram stories function
  206. if(location.href.match(/^(https:\/\/www\.instagram\.com\/stories\/highlights\/)/ig)){
  207. GL_dataCache.highlights = {};
  208.  
  209. console.log('isHighlightsStory');
  210.  
  211. onHighlightsStory(false);
  212. GL_repeat = setInterval(()=>{
  213. onHighlightsStoryThumbnail(false);
  214. },checkInterval);
  215.  
  216. if($(".IG_DWHISTORY").length) setTimeout(()=>{pageLoaded = true;},150);
  217. }
  218. else if(location.href.match(/^(https:\/\/www\.instagram\.com\/stories\/)/ig)){
  219. console.log('isStory');
  220.  
  221. /*
  222. *
  223. * $('body div[id^="mount"] > div > div > div[class]').length >= 2 &&
  224. * $('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 &&
  225. * $('body div[id^="mount"] > div > div > div[class]').last().find('svg > polyline + line').length > 0
  226. *
  227. */
  228. if($('div[id^="mount"] section > div > a[href="/"]').length > 0){
  229. $('.IG_DWSTORY').remove();
  230. $('.IG_DWNEWTAB').remove();
  231. if($('.IG_DWSTORY_THUMBNAIL').length){
  232. $('.IG_DWSTORY_THUMBNAIL').remove();
  233. }
  234.  
  235. onStory(false);
  236.  
  237. // Prevent buttons from being eaten by black holes sometimes
  238. setTimeout(()=>{
  239. onStory(false);
  240. }, 150);
  241. }
  242.  
  243. if($(".IG_DWSTORY").length) setTimeout(()=>{pageLoaded = true;},150);
  244. }
  245. else{
  246. pageLoaded = false;
  247. // Remove icons
  248. $('.IG_DWSTORY').remove();
  249. $('.IG_DWNEWTAB').remove();
  250. if($('.IG_DWSTORY_THUMBNAIL').length){
  251. $('.IG_DWSTORY_THUMBNAIL').remove();
  252. }
  253. }
  254. }
  255.  
  256. GL_referrer = new URL(location.href).pathname;
  257. }
  258. },checkInterval);
  259.  
  260. /**
  261. * onProfileAvatar
  262. * Trigger user avatar download event or button display event.
  263. *
  264. * @param {Boolean} isDownload - Check if it is a download operation
  265. * @return {void}
  266. */
  267. async function onProfileAvatar(isDownload){
  268. if(isDownload){
  269. updateLoadingBar(true);
  270.  
  271. let date = new Date().getTime();
  272. let timestamp = Math.floor(date / 1000);
  273. let username = location.pathname.replaceAll(/(reels|tagged)\/$/ig,'').split('/').filter(s => s.length > 0).at(-1);
  274. let userInfo = await getUserId(username);
  275.  
  276. try{
  277. let dataURL = await getUserHighSizeProfile(userInfo.user.pk);
  278. saveFiles(dataURL,username,"avatar",timestamp,'jpg');
  279. }
  280. catch(err){
  281. saveFiles(userInfo.user.profile_pic_url,username,"avatar",timestamp,'jpg');
  282. }
  283.  
  284. updateLoadingBar(false);
  285. }
  286. else{
  287. // Add the profile download button
  288. if(!$('.IG_DWPROFILE').length){
  289. let profileTimer = setInterval(()=>{
  290. if($('.IG_DWPROFILE').length){
  291. clearInterval(profileTimer);
  292. return;
  293. }
  294.  
  295. $('header > section:first img[alt][draggable]').parent().parent().append(`<div title="${_i18n("DW")}" class="IG_DWPROFILE">${SVG.DOWNLOAD}</div>`);
  296. $('header > section:first img[alt][draggable]').parent().parent().css('position','relative');
  297. $('header > section:first img[alt]:not([draggable])').parent().parent().parent().append(`<div title="${_i18n("DW")}" class="IG_DWPROFILE">${SVG.DOWNLOAD}</div>`);
  298. $('header > section:first img[alt]:not([draggable])').parent().parent().parent().css('position','relative');
  299. },150);
  300. }
  301. }
  302. }
  303.  
  304. /**
  305. * onHighlightsStory
  306. * Trigger user's highlight download event or button display event.
  307. *
  308. * @param {Boolean} isDownload - Check if it is a download operation
  309. * @param {Boolean} isPreview - Check if it is need to open new tab
  310. * @return {void}
  311. */
  312. async function onHighlightsStory(isDownload, isPreview){
  313. if(isDownload){
  314. let date = new Date().getTime();
  315. let timestamp = Math.floor(date / 1000);
  316. let highlightId = location.href.replace(/\/$/ig,'').split('/').at(-1);
  317. let nowIndex = $("body > div section._ac0a header._ac0k > ._ac3r ._ac3n ._ac3p[style]").length ||
  318. $('body > div section:visible > div > div:not([class]) > div > div div.x1ned7t2.x78zum5 div.x1caxmr6').length ||
  319. $('body > div div:not([hidden]) section:visible > div div[style]:not([class]) > div').find('div div.x1ned7t2.x78zum5 div.x1caxmr6').length;
  320. let username = "";
  321. let target = 0;
  322.  
  323. updateLoadingBar(true);
  324.  
  325. if(GL_dataCache.highlights[highlightId]){
  326. console.log('Fetch from memory cache:', highlightId);
  327.  
  328. let totIndex = GL_dataCache.highlights[highlightId].data.reels_media[0].items.length;
  329. username = GL_dataCache.highlights[highlightId].data.reels_media[0].owner.username;
  330. target = GL_dataCache.highlights[highlightId].data.reels_media[0].items[totIndex-nowIndex];
  331. }
  332. else{
  333. let highStories = await getHighlightStories(highlightId);
  334. let totIndex = highStories.data.reels_media[0].items.length;
  335. username = highStories.data.reels_media[0].owner.username;
  336. target = highStories.data.reels_media[0].items[totIndex-nowIndex];
  337.  
  338. GL_dataCache.highlights[highlightId] = highStories;
  339. }
  340.  
  341. if(USER_SETTING.RENAME_PUBLISH_DATE){
  342. timestamp = target.taken_at_timestamp;
  343. }
  344.  
  345. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LITMIT){
  346. let result = await getMediaInfo(target.id);
  347.  
  348. if(result.status === 'ok'){
  349. if(result.items[0].video_versions){
  350. if(isPreview){
  351. openNewTab(result.items[0].video_versions[0].url);
  352. }
  353. else{
  354. saveFiles(result.items[0].video_versions[0].url, username,"highlights",timestamp,'mp4');
  355. }
  356. }
  357. else{
  358. if(isPreview){
  359. openNewTab(result.items[0].image_versions2.candidates[0].url);
  360. }
  361. else{
  362. saveFiles(result.items[0].image_versions2.candidates[0].url, username,"highlights",timestamp,'jpg');
  363. }
  364. }
  365. }
  366. else{
  367. if(USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT){
  368. delete GL_dataCache.highlights[highlightId];
  369. TEMP_FETCH_RATE_LITMIT = true;
  370.  
  371. onHighlightsStory(true, isPreview);
  372. }
  373. else{
  374. alert('Fetch failed from Media API. API response message: ' + result.message);
  375. }
  376.  
  377. console.log(result);
  378. }
  379. }
  380. else{
  381. if(target.is_video){
  382. if(isPreview){
  383. openNewTab(target.video_resources.at(-1).src,username);
  384. }
  385. else{
  386. saveFiles(target.video_resources.at(-1).src,username,"highlights",timestamp,'mp4', highlightId);
  387. }
  388. }
  389. else{
  390. if(isPreview){
  391. openNewTab(target.display_resources.at(-1).src,username);
  392. }
  393. else{
  394. saveFiles(target.display_resources.at(-1).src,username,"highlights",timestamp,'jpg', highlightId);
  395. }
  396. }
  397.  
  398. TEMP_FETCH_RATE_LITMIT = false;
  399. }
  400.  
  401. updateLoadingBar(false);
  402. }
  403. else{
  404. // Add the stories download button
  405. if(!$('.IG_DWHISTORY').length){
  406. let $element = null;
  407.  
  408. // Default detecter (section layout mode)
  409. if($('body > div section._ac0a').length > 0){
  410. $element = $('body > div section:visible._ac0a');
  411. }
  412. else{
  413. $element = $('body > div section:visible > div > div[style]:not([class])');
  414. $element.css('position','relative');
  415. }
  416.  
  417. // Detecter for div layout mode
  418. if($element.length === 0){
  419. let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
  420. let nowSize = 0;
  421.  
  422. $$element.each(function(){
  423. if($(this).width() > nowSize){
  424. nowSize = $(this).width();
  425. $element = $(this).children('div').first();
  426. }
  427. });
  428. }
  429.  
  430.  
  431. if($element != null){
  432. //$element.css('position','relative');
  433. $element.append(`<div title="${_i18n("DW")}" class="IG_DWHISTORY">${SVG.DOWNLOAD}</div>`);
  434. $element.append(`<div title="${_i18n("NEW_TAB")}" class="IG_DWHINEWTAB">${SVG.NEW_TAB}</div>`);
  435.  
  436. // Modify Video Volume
  437. if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  438. $element.find('video').each(function(){
  439. if(!$(this).data('modify')){
  440. console.log('(highlight) Added video event listener #modify');
  441. this.volume = VIDEO_VOLUME;
  442.  
  443. $(this).on('play',function(){
  444. this.volume = VIDEO_VOLUME;
  445. });
  446. $(this).on('playing',function(){
  447. this.volume = VIDEO_VOLUME;
  448. });
  449.  
  450. $(this).attr('data-modify', true);
  451. }
  452. });
  453. }
  454. }
  455. }
  456. }
  457. }
  458.  
  459. /**
  460. * onHighlightsStoryThumbnail
  461. * Trigger user's highlight video thumbnail download event or button display event.
  462. *
  463. * @param {Boolean} isDownload - Check if it is a download operation
  464. * @return {void}
  465. */
  466. async function onHighlightsStoryThumbnail(isDownload){
  467. if(isDownload){
  468. let date = new Date().getTime();
  469. let timestamp = Math.floor(date / 1000);
  470. let highlightId = location.href.replace(/\/$/ig,'').split('/').at(-1);
  471. let username = "";
  472. let nowIndex = $("body > div section._ac0a header._ac0k > ._ac3r ._ac3n ._ac3p[style]").length ||
  473. $('body > div section:visible > div > div:not([class]) > div > div div.x1ned7t2.x78zum5 div.x1caxmr6').length ||
  474. $('body > div div:not([hidden]) section:visible > div div[style]:not([class]) > div').find('div div.x1ned7t2.x78zum5 div.x1caxmr6').length;
  475. let target = "";
  476.  
  477. updateLoadingBar(true);
  478.  
  479. if(GL_dataCache.highlights[highlightId]){
  480. console.log('Fetch from memory cache:', highlightId);
  481.  
  482. let totIndex = GL_dataCache.highlights[highlightId].data.reels_media[0].items.length;
  483. username = GL_dataCache.highlights[highlightId].data.reels_media[0].owner.username;
  484. target = GL_dataCache.highlights[highlightId].data.reels_media[0].items[totIndex-nowIndex];
  485. }
  486. else{
  487. let highStories = await getHighlightStories(highlightId);
  488. let totIndex = highStories.data.reels_media[0].items.length;
  489. username = highStories.data.reels_media[0].owner.username;
  490. target = highStories.data.reels_media[0].items[totIndex-nowIndex];
  491.  
  492. GL_dataCache.highlights[highlightId] = highStories;
  493. }
  494.  
  495. if(USER_SETTING.RENAME_PUBLISH_DATE){
  496. timestamp = target.taken_at_timestamp;
  497. }
  498.  
  499. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LITMIT){
  500. let result = await getMediaInfo(target.id);
  501.  
  502. if(result.status === 'ok'){
  503. saveFiles(result.items[0].image_versions2.candidates[0].url, username,"highlights",timestamp,'jpg');
  504. }
  505. else{
  506. if(USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT){
  507. delete GL_dataCache.highlights[highlightId];
  508. TEMP_FETCH_RATE_LITMIT = true;
  509.  
  510. onHighlightsStoryThumbnail(true);
  511. }
  512. else{
  513. alert('Fetch failed from Media API. API response message: ' + result.message);
  514. }
  515.  
  516. console.log(result);
  517. }
  518. }
  519. else{
  520. saveFiles(target.display_resources.at(-1).src,username,"highlights",timestamp,'jpg', highlightId);
  521. TEMP_FETCH_RATE_LITMIT= false;
  522. }
  523.  
  524. updateLoadingBar(false);
  525. }
  526. else{
  527. if($('body > div section video.xh8yej3').length){
  528. // Add the stories thumbnail download button
  529. if(!$('.IG_DWHISTORY_THUMBNAIL').length){
  530. let $element = null;
  531.  
  532. // Default detecter (section layout mode)
  533. if($('body > div section._ac0a').length > 0){
  534. $element = $('body > div section:visible._ac0a');
  535. }
  536. else{
  537. $element = $('body > div section:visible > div > div[style]:not([class])');
  538. $element.css('position','relative');
  539. }
  540.  
  541. // Detecter for div layout mode
  542. if($element.length === 0){
  543. let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
  544. let nowSize = 0;
  545.  
  546. $$element.each(function(){
  547. if($(this).width() > nowSize){
  548. nowSize = $(this).width();
  549. $element = $(this).children('div').first();
  550. }
  551. });
  552. }
  553.  
  554. if($element != null){
  555. $element.append(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="IG_DWHISTORY_THUMBNAIL">${SVG.THUMBNAIL}</div>`);
  556. }
  557. }
  558. }
  559. else{
  560. $('.IG_DWHISTORY_THUMBNAIL').remove();
  561. }
  562. }
  563. }
  564.  
  565. /**
  566. * onStory
  567. * Trigger user's story download event or button display event.
  568. *
  569. * @param {Boolean} isDownload - Check if it is a download operation
  570. * @param {Boolean} isForce - Check if downloading directly from API instead of cache
  571. * @param {Boolean} isPreview - Check if it is need to open new tab
  572. * @return {void}
  573. */
  574. async function onStory(isDownload,isForce,isPreview){
  575. if(isDownload){
  576. let date = new Date().getTime();
  577. let timestamp = Math.floor(date / 1000);
  578. let username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split('/').at(2);
  579.  
  580. updateLoadingBar(true);
  581. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LITMIT){
  582. let mediaId = null;
  583.  
  584. let userInfo = await getUserId(username);
  585. let userId = userInfo.user.pk;
  586. let stories = await getStories(userId);
  587.  
  588. // appear in from profile page to story page
  589. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function(index){
  590. if($(this).hasClass('x1lix1fw')){
  591. if($(this).children().length > 0){
  592. mediaId = stories.data.reels_media[0].items[index].id;
  593. }
  594. }
  595. });
  596.  
  597. // appear in from home page to story page
  598. $('body > div section:visible ._ac0k > ._ac3r > div').each(function(index){
  599. if($(this).children().hasClass('_ac3q')){
  600. mediaId = stories.data.reels_media[0].items[index].id;
  601. }
  602. });
  603.  
  604. if(mediaId == null){
  605. mediaId = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
  606. }
  607.  
  608. let result = await getMediaInfo(mediaId);
  609.  
  610. if(USER_SETTING.RENAME_PUBLISH_DATE){
  611. timestamp = result.items[0].taken_at;
  612. }
  613.  
  614. if(result.status === 'ok'){
  615. if(result.items[0].video_versions){
  616. if(isPreview){
  617. openNewTab(result.items[0].video_versions[0].url);
  618. }
  619. else{
  620. saveFiles(result.items[0].video_versions[0].url, username,"stories",timestamp,'mp4');
  621. }
  622. }
  623. else{
  624. if(isPreview){
  625. openNewTab(result.items[0].image_versions2.candidates[0].url);
  626. }
  627. else{
  628. saveFiles(result.items[0].image_versions2.candidates[0].url, username,"stories",timestamp,'jpg');
  629. }
  630. }
  631. }
  632. else{
  633. if(USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT){
  634. TEMP_FETCH_RATE_LITMIT = true;
  635. onStory(isDownload,isForce,isPreview);
  636. }
  637. else{
  638. alert('Fetch failed from Media API. API response message: ' + result.message);
  639. }
  640. console.log(result);
  641. }
  642.  
  643. updateLoadingBar(false);
  644. return;
  645. }
  646.  
  647. if($('body > div section:visible video[playsinline]').length > 0){
  648. // Download stories if it is video
  649. let type = "mp4";
  650. let videoURL = "";
  651. let targetURL = location.pathname.replace(/\/$/ig,'').split("/").at(-1);
  652.  
  653. if(GL_dataCache.stories[username] && !isForce){
  654. console.log('Fetch from memory cache:', username);
  655. GL_dataCache.stories[username].data.reels_media[0].items.forEach(item => {
  656. if(item.id == targetURL){
  657. videoURL = item.video_resources[0].src;
  658. if(USER_SETTING.RENAME_PUBLISH_DATE){
  659. timestamp = item.taken_at_timestamp;
  660. }
  661. }
  662. });
  663.  
  664. if(videoURL.length == 0){
  665. console.log('Memory cache not found, try fetch from API:', username);
  666. onStory(true,true);
  667. return;
  668. }
  669. }
  670. else{
  671. let userInfo = await getUserId(username);
  672. let userId = userInfo.user.pk;
  673. let stories = await getStories(userId);
  674.  
  675. stories.data.reels_media[0].items.forEach(item => {
  676. if(item.id == targetURL){
  677. videoURL = item.video_resources[0].src;
  678. if(USER_SETTING.RENAME_PUBLISH_DATE){
  679. timestamp = item.taken_at_timestamp;
  680. }
  681. }
  682. });
  683.  
  684. // GitHub issue #4: thinkpad4
  685. if(videoURL.length == 0){
  686. // appear in from profile page to story page
  687. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function(index){
  688. if($(this).hasClass('x1lix1fw')){
  689. if($(this).children().length > 0){
  690. videoURL = stories.data.reels_media[0].items[index].video_resources[0].src;
  691. if(USER_SETTING.RENAME_PUBLISH_DATE){
  692. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  693. }
  694. }
  695. }
  696. });
  697.  
  698. // appear in from home page to story page
  699. $('body > div section:visible ._ac0k > ._ac3r > div').each(function(index){
  700. if($(this).children().hasClass('_ac3q')){
  701. videoURL = stories.data.reels_media[0].items[index].video_resources[0].src;
  702. if(USER_SETTING.RENAME_PUBLISH_DATE){
  703. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  704. }
  705. }
  706. });
  707. }
  708.  
  709. GL_dataCache.stories[username] = stories;
  710. }
  711.  
  712. if(videoURL.length == 0){
  713. alert(_i18n("NO_VID_URL"));
  714. }
  715. else{
  716. if(isPreview){
  717. openNewTab(videoURL);
  718. }
  719. else{
  720. saveFiles(videoURL,username,"stories",timestamp,type);
  721. }
  722. }
  723. }
  724. else{
  725. // Download stories if it is image
  726. let srcset = $('body > div section:visible img[referrerpolicy][class], body > div section:visible img[crossorigin][class]:not([alt])').attr('srcset')?.split(',')[0]?.split(' ')[0];
  727. let link = (srcset)?srcset:$('body > div section:visible img[referrerpolicy][class], body > div section:visible img[crossorigin][class]:not([alt])').attr('src');
  728.  
  729. if(!link){
  730. // _aa63 mean stories picture in stories page (not avatar)
  731. let $element = $('body > div section:visible img._aa63');
  732. link = ($element.attr('srcset'))?$element.attr('srcset')?.split(',')[0]?.split(' ')[0]:$element.attr('src');
  733. }
  734.  
  735. if(USER_SETTING.RENAME_PUBLISH_DATE){
  736. timestamp = new Date($('body > div section:visible time[datetime][class]').first().attr('datetime')).getTime();
  737. }
  738.  
  739. let downloadLink = link;
  740. let type = 'jpg';
  741.  
  742. if(isPreview){
  743. openNewTab(downloadLink);
  744. }
  745. else{
  746. saveFiles(downloadLink,username,"stories",timestamp,type);
  747. }
  748. }
  749.  
  750. TEMP_FETCH_RATE_LITMIT = false;
  751. updateLoadingBar(false);
  752. }
  753. else{
  754. // Add the stories download button
  755. let style = "position: absolute;right:-40px;top:15px;padding:5px;line-height:1;background:#fff;border-radius: 5px;cursor:pointer;";
  756. if(!$('.IG_DWSTORY').length){
  757. GL_dataCache.stories = {};
  758. let $element = null;
  759. // Default detecter (section layout mode)
  760. if($('body > div section._ac0a').length > 0){
  761. $element = $('body > div section:visible._ac0a');
  762. }
  763. // detecter (single story layout mode)
  764. else{
  765. $element = $('body > div section:visible > div > div[style]:not([class])');
  766. $element.css('position','relative');
  767. }
  768.  
  769.  
  770. if($element.length === 0){
  771. $element = $('div[id^="mount"] section > div > a[href="/"]').parent().parent().parent().find('section:visible > div > div[style]:not([class])');
  772. $element.css('position','relative');
  773. }
  774.  
  775. if($element.length === 0){
  776. $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"])');
  777. $element.css('position','relative');
  778. }
  779.  
  780.  
  781. // Detecter for div layout mode
  782. if($element.length === 0){
  783. let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
  784. let nowSize = 0;
  785.  
  786. $$element.each(function(){
  787. if($(this).width() > nowSize){
  788. nowSize = $(this).width();
  789. $element = $(this).children('div').first();
  790. }
  791. });
  792. }
  793.  
  794.  
  795. if($element != null){
  796. $element.first().css('position','relative');
  797. $element.first().append(`<div title="${_i18n("DW")}" class="IG_DWSTORY">${SVG.DOWNLOAD}</div>`);
  798. $element.first().append(`<div title="${_i18n("NEW_TAB")}" class="IG_DWNEWTAB">${SVG.NEW_TAB}</div>`);
  799.  
  800. // Modify Video Volume
  801. if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  802. $element.find('video').each(function(){
  803. if(!$(this).data('modify')){
  804. console.log('(story) Added video event listener #modify');
  805. this.volume = VIDEO_VOLUME;
  806.  
  807. $(this).on('play',function(){
  808. this.volume = VIDEO_VOLUME;
  809. });
  810. $(this).on('playing',function(){
  811. this.volume = VIDEO_VOLUME;
  812. });
  813.  
  814. $(this).attr('data-modify', true);
  815. }
  816. });
  817. }
  818.  
  819. onStoryThumbnail(false);
  820. }
  821. }
  822. }
  823. }
  824.  
  825. /**
  826. * onStoryThumbnail
  827. * Trigger user's story video thumbnail download event or button display event.
  828. *
  829. * @param {Boolean} isDownload - Check if it is a download operation
  830. * @param {Boolean} isForce - Check if downloading directly from API instead of cache
  831. * @return {void}
  832. */
  833. async function onStoryThumbnail(isDownload,isForce){
  834. if(isDownload){
  835. // Download stories if it is video
  836. let date = new Date().getTime();
  837. let timestamp = Math.floor(date / 1000);
  838. let type = 'jpg';
  839. let username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split('/').at(2);
  840. 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;';
  841. // Download thumbnail
  842. let targetURL = location.pathname.replace(/\/$/ig,'').split("/").at(-1);
  843. let videoThumbnailURL = "";
  844.  
  845. updateLoadingBar(true);
  846.  
  847. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LITMIT){
  848. let mediaId = null;
  849.  
  850. let userInfo = await getUserId(username);
  851. let userId = userInfo.user.pk;
  852. let stories = await getStories(userId);
  853.  
  854. // appear in from profile page to story page
  855. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function(index){
  856. if($(this).hasClass('x1lix1fw')){
  857. if($(this).children().length > 0){
  858. mediaId = stories.data.reels_media[0].items[index].id;
  859. }
  860. }
  861. });
  862.  
  863. // appear in from home page to story page
  864. $('body > div section:visible ._ac0k > ._ac3r > div').each(function(index){
  865. if($(this).children().hasClass('_ac3q')){
  866. mediaId = stories.data.reels_media[0].items[index].id;
  867. }
  868. });
  869.  
  870. if(mediaId == null){
  871. mediaId = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
  872. }
  873.  
  874. let result = await getMediaInfo(mediaId);
  875.  
  876. if(USER_SETTING.RENAME_PUBLISH_DATE){
  877. timestamp = result.items[0].taken_at;
  878. }
  879.  
  880. if(result.status === 'ok'){
  881. saveFiles(result.items[0].image_versions2.candidates[0].url, username,"stories",timestamp,'jpg');
  882.  
  883. }
  884. else{
  885. if(USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT){
  886. TEMP_FETCH_RATE_LITMIT = true;
  887. onStoryThumbnail(true, isForce);
  888. }
  889. else{
  890. alert('Fetch failed from Media API. API response message: ' + result.message);
  891. }
  892.  
  893. console.log(result);
  894. }
  895.  
  896. updateLoadingBar(false);
  897. return;
  898. }
  899.  
  900. if(GL_dataCache.stories[username] && !isForce){
  901. console.log('Fetch from memory cache:', username);
  902. GL_dataCache.stories[username].data.reels_media[0].items.forEach(item => {
  903. if(item.id == targetURL){
  904. videoThumbnailURL = item.display_url;
  905. if(USER_SETTING.RENAME_PUBLISH_DATE){
  906. timestamp = item.taken_at_timestamp;
  907. }
  908. }
  909. });
  910.  
  911. if(videoThumbnailURL.length == 0){
  912. console.log('Memory cache not found, try fetch from API:', username);
  913. onStoryThumbnail(true,true);
  914. return;
  915. }
  916. }
  917. else{
  918. let userInfo = await getUserId(username);
  919. let userId = userInfo.user.pk;
  920. let stories = await getStories(userId);
  921.  
  922. stories.data.reels_media[0].items.forEach(item => {
  923. if(item.id == targetURL){
  924. videoThumbnailURL = item.display_url;
  925. if(USER_SETTING.RENAME_PUBLISH_DATE){
  926. timestamp = item.taken_at_timestamp;
  927. }
  928. }
  929. });
  930.  
  931. // GitHub issue #4: thinkpad4
  932. if(videoThumbnailURL.length == 0){
  933. // appear in from profile page to story page
  934. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function(index){
  935. if($(this).hasClass('x1lix1fw')){
  936. if($(this).children().length > 0){
  937. videoThumbnailURL = stories.data.reels_media[0].items[index].display_url;
  938. if(USER_SETTING.RENAME_PUBLISH_DATE){
  939. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  940. }
  941. }
  942. }
  943. });
  944.  
  945. // appear in from home page to story page
  946. $('body > div section:visible ._ac0k > ._ac3r > div').each(function(index){
  947. if($(this).children().hasClass('_ac3q')){
  948. videoThumbnailURL = stories.data.reels_media[0].items[index].display_url;
  949. if(USER_SETTING.RENAME_PUBLISH_DATE){
  950. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  951. }
  952. }
  953. });
  954. }
  955. }
  956.  
  957. saveFiles(videoThumbnailURL,username,"thumbnail",timestamp,type);
  958. TEMP_FETCH_RATE_LITMIT= false;
  959. updateLoadingBar(false);
  960. }
  961. else{
  962. if($('body > div div.IG_DWSTORY').parent().find('video[class]').length){
  963. // Add the stories download button
  964. let $element = null;
  965. // Default detecter (section layout mode)
  966. if($('body > div section._ac0a').length > 0){
  967. $element = $('body > div section:visible._ac0a');
  968. }
  969. // detecter (single story layout mode)
  970. else{
  971. $element = $('body > div section:visible > div > div[style]:not([class])');
  972. $element.css('position','relative');
  973. }
  974.  
  975. if($element.length === 0){
  976. $element = $('div[id^="mount"] section > div > a[href="/"]').parent().parent().parent().find('section:visible > div > div[style]:not([class])');
  977. $element.css('position','relative');
  978. }
  979.  
  980. if($element.length === 0){
  981. $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"])');
  982. $element.css('position','relative');
  983. }
  984.  
  985. // Detecter for div layout mode
  986. if($element.length === 0){
  987. let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
  988. let nowSize = 0;
  989.  
  990. $$element.each(function(){
  991. if($(this).width() > nowSize){
  992. nowSize = $(this).width();
  993. $element = $(this).children('div').first();
  994. }
  995. });
  996. }
  997.  
  998.  
  999. if($element != null){
  1000. $element.first().css('position','relative');
  1001. $element.first().append(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="IG_DWSTORY_THUMBNAIL">${SVG.THUMBNAIL}</div>`);
  1002. }
  1003.  
  1004. }
  1005. }
  1006. }
  1007.  
  1008. /**
  1009. * onReels
  1010. * Trigger user's reels download event or button display event.
  1011. *
  1012. * @param {Boolean} isDownload - Check if it is a download operation
  1013. * @param {Boolean} isVideo - Check if reel is a video element
  1014. * @param {Boolean} isPreview - Check if it is need to open new tab
  1015. * @return {void}
  1016. */
  1017. async function onReels(isDownload, isVideo, isPreview){
  1018. if(isDownload){
  1019. updateLoadingBar(true);
  1020.  
  1021. let reelsPath = location.href.split('?').at(0).split('instagram.com/reels/').at(-1).replaceAll('/','');
  1022. let data = await getBlobMedia(reelsPath);
  1023.  
  1024. let timestamp = new Date().getTime();
  1025.  
  1026. if(USER_SETTING.RENAME_PUBLISH_DATE){
  1027. timestamp = data.shortcode_media.taken_at_timestamp;
  1028. }
  1029.  
  1030. if(isVideo && data.shortcode_media.is_video){
  1031. if(isPreview){
  1032. openNewTab(data.shortcode_media.video_url);
  1033. }
  1034. else{
  1035. let type = 'mp4';
  1036. saveFiles(data.shortcode_media.video_url,data.shortcode_media.owner.username,"reels",timestamp,type,reelsPath);
  1037. }
  1038. }
  1039. else{
  1040. if(isPreview){
  1041. openNewTab(data.shortcode_media.display_resources.at(-1).src);
  1042. }
  1043. else{
  1044. let type = 'jpg';
  1045. saveFiles(data.shortcode_media.display_resources.at(-1).src,data.shortcode_media.owner.username,"reels",timestamp,type,reelsPath);
  1046. }
  1047. }
  1048.  
  1049. updateLoadingBar(false);
  1050. }
  1051. else{
  1052. //$('.IG_REELS_THUMBNAIL, .IG_REELS').remove();
  1053. var timer = setInterval(()=>{
  1054. if($('section > main[role="main"] > div div.x1qjc9v5 video').length > 0){
  1055. clearInterval(timer);
  1056.  
  1057. if(USER_SETTING.SCROLL_BUTTON){
  1058. $('#scrollWrapper').remove();
  1059. $('section > main[role="main"]').append('<section id="scrollWrapper"></section>');
  1060. $('section > main[role="main"] > #scrollWrapper').append('<div class="button-up"><div></div></div>');
  1061. $('section > main[role="main"] > #scrollWrapper').append('<div class="button-down"><div></div></div>');
  1062.  
  1063. $('section > main[role="main"] > #scrollWrapper > .button-up').on('click',function(){
  1064. $('section > main[role="main"] > div')[0].scrollBy({top: -30, behavior: "smooth"});
  1065. });
  1066. $('section > main[role="main"] > #scrollWrapper > .button-down').on('click',function(){
  1067. $('section > main[role="main"] > div')[0].scrollBy({top: 30, behavior: "smooth"});
  1068. });
  1069. }
  1070.  
  1071. // reels scroll has [tabindex] but header not.
  1072. $('section > main[role="main"] > div[tabindex]').children('div').each(function(){
  1073. if($(this).children().length > 0){
  1074. if(!$(this).children().find('.IG_REELS').length){
  1075. var $main = $(this);
  1076.  
  1077. $(this).children().css('position','relative');
  1078.  
  1079. $(this).children().append(`<div title="${_i18n("DW")}" class="IG_REELS">${SVG.DOWNLOAD}</div>`);
  1080. $(this).children().append(`<div title="${_i18n("NEW_TAB")}" class="IG_REELS_NEWTAB">${SVG.NEW_TAB}</div>`);
  1081. $(this).children().append(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="IG_REELS_THUMBNAIL">${SVG.THUMBNAIL}</div>`);
  1082.  
  1083. // Disable video autoplay
  1084. if(USER_SETTING.DISABLE_VIDEO_LOOPING){
  1085. $(this).find('video').each(function(){
  1086. if(!$(this).data('loop')){
  1087. console.log('(reel) Added video event listener #loop');
  1088. $(this).on('ended',function(){
  1089. $(this).attr('data-loop', true);
  1090. let $element_play_button = $(this).next().find('div[role="presentation"] > div svg > path[d^="M5.888"]').parents('button[role="button"], div[role="button"]');
  1091. if($element_play_button.length > 0){
  1092. $element_play_button.click();
  1093. console.log('paused click()');
  1094. }
  1095. else{
  1096. $(this).parent().find('.xpgaw4o').removeAttr('style');
  1097. this.pause();
  1098. console.log('paused pause()');
  1099. }
  1100. });
  1101. }
  1102. });
  1103. }
  1104. // Modify Video Volume
  1105. if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  1106. $(this).find('video').each(function(){
  1107. if(!$(this).data('modify')){
  1108. console.log('(reel) Added video event listener #modify');
  1109. this.volume = VIDEO_VOLUME;
  1110.  
  1111. $(this).on('play',function(){
  1112. this.volume = VIDEO_VOLUME;
  1113. });
  1114. $(this).on('playing',function(){
  1115. this.volume = VIDEO_VOLUME;
  1116. });
  1117.  
  1118. $(this).attr('data-modify', true);
  1119. }
  1120. });
  1121. }
  1122.  
  1123. if(USER_SETTING.HTML5_VIDEO_CONTROL){
  1124. $(this).find('video').each(function(){
  1125. if(!$(this).data('controls')){
  1126. let $video = $(this);
  1127.  
  1128. console.log('(reel) Added video html5 contorller #modify');
  1129. this.volume = VIDEO_VOLUME;
  1130.  
  1131. $(this).on('loadstart',function(){
  1132. this.volume = VIDEO_VOLUME;
  1133. });
  1134.  
  1135. // Restore layout to show details interface
  1136. $(this).on('contextmenu',function(e){
  1137. e.preventDefault();
  1138. $video.css('z-index', '-1');
  1139. $video.removeAttr('controls');
  1140. });
  1141.  
  1142. // Hide layout to show controller
  1143. $(this).parent().find('video + div div[role="button"]').filter(function(){
  1144. return $(this).parent('div[role="presentation"]').length > 0 && $(this).css('cursor') === 'pointer' && $(this).attr('style') != null;
  1145. }).first().on('contextmenu',function(e){
  1146. e.preventDefault();
  1147. $video.css('z-index', '2');
  1148. $video.attr('controls', true);
  1149. });
  1150.  
  1151.  
  1152. $(this).on('volumechange',function(){
  1153. let $element_mute_button = $(this).parent().find('video + div > div').find('button[type="button"], div[role="button"]').filter(function(idx){
  1154. // This is mute/unmute's icon
  1155. 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;
  1156. });
  1157.  
  1158. var is_elelment_muted = $element_mute_button.find('svg > path[d^="M16.636"]').length === 0;
  1159.  
  1160. if(this.muted != is_elelment_muted){
  1161. this.volume = VIDEO_VOLUME;
  1162. $element_mute_button?.click();
  1163. }
  1164.  
  1165. if ($(this).attr('data-completed')){
  1166. VIDEO_VOLUME = this.volume;
  1167. GM_setValue('G_VIDEO_VOLUME', this.volume);
  1168. }
  1169.  
  1170. if(this.volume == VIDEO_VOLUME){
  1171. $(this).attr('data-completed', true);
  1172. }
  1173. });
  1174.  
  1175. $(this).css('position', 'absolute');
  1176. $(this).css('z-index', '2');
  1177. $(this).attr('data-controls', true);
  1178. $(this).attr('controls', true);
  1179. }
  1180. });
  1181. }
  1182.  
  1183. var $buttonParent = $(this).find('div[role="presentation"] > div[role="button"] > div').first();
  1184. $buttonParent.append('<div class="volume_slider" />');
  1185. $buttonParent.find('div.volume_slider').append(`<div><input type="range" max="1" min="0" step="0.05" value="${VIDEO_VOLUME}" /></div>`);
  1186. $buttonParent.find('div.volume_slider input').attr('style',`--ig-track-progress: ${(VIDEO_VOLUME * 100) + '%'}`);
  1187. $buttonParent.find('div.volume_slider input').on('input',function(){
  1188. var percent = ($(this).val() * 100) + '%';
  1189.  
  1190. VIDEO_VOLUME = $(this).val();
  1191. GM_setValue('G_VIDEO_VOLUME', $(this).val());
  1192.  
  1193. $(this).attr('style',`--ig-track-progress: ${percent}`);
  1194.  
  1195. $main.find('video').each(function(){
  1196. console.log('(reel) video volume changed #slider');
  1197. this.volume = VIDEO_VOLUME;
  1198. });
  1199. });
  1200.  
  1201. $buttonParent.find('div.volume_slider input').on('mouseenter',function(){
  1202. var percent = (VIDEO_VOLUME * 100) + '%';
  1203. $(this).attr('style',`--ig-track-progress: ${percent}`);
  1204. $(this).val(VIDEO_VOLUME);
  1205. $main.find('video').each(function(){
  1206. console.log('(reel) video volume changed #slider');
  1207. this.volume = VIDEO_VOLUME;
  1208. });
  1209. });
  1210.  
  1211. $buttonParent.find('div.volume_slider').on('click',function(e){
  1212. e.stopPropagation();
  1213. e.preventDefault();
  1214. });
  1215. }
  1216. }
  1217. });
  1218. }
  1219. },250);
  1220. }
  1221. }
  1222.  
  1223. /**
  1224. * getHighlightStories
  1225. * Get a list of all stories in highlight Id.
  1226. *
  1227. * @param {Integer} highlightId
  1228. * @return {Object}
  1229. */
  1230. function getHighlightStories(highlightId){
  1231. return new Promise((resolve,reject)=>{
  1232. 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`;
  1233.  
  1234. GM_xmlhttpRequest({
  1235. method: "GET",
  1236. url: getURL,
  1237. onload: function(response) {
  1238. let obj = JSON.parse(response.response);
  1239. resolve(obj);
  1240. },
  1241. onerror: function(err){
  1242. reject(err);
  1243. }
  1244. });
  1245. });
  1246. }
  1247.  
  1248. /**
  1249. * getStories
  1250. * Get a list of all stories in user Id.
  1251. *
  1252. * @param {Integer} userId
  1253. * @return {Object}
  1254. */
  1255. function getStories(userId){
  1256. return new Promise((resolve,reject)=>{
  1257. 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`;
  1258.  
  1259. GM_xmlhttpRequest({
  1260. method: "GET",
  1261. url: getURL,
  1262. onload: function(response) {
  1263. let obj = JSON.parse(response.response);
  1264. resolve(obj);
  1265. },
  1266. onerror: function(err){
  1267. reject(err);
  1268. }
  1269. });
  1270. });
  1271. }
  1272.  
  1273. /**
  1274. * getUserId
  1275. * Get user's id with username
  1276. *
  1277. * @param {String} username
  1278. * @return {Integer}
  1279. */
  1280. function getUserId(username){
  1281. return new Promise((resolve,reject)=>{
  1282. let getURL = `https://www.instagram.com/web/search/topsearch/?query=${username}`;
  1283.  
  1284. GM_xmlhttpRequest({
  1285. method: "GET",
  1286. url: getURL,
  1287. onload: function(response) {
  1288. // Fix search issue by Discord: sno_w_
  1289. let obj = JSON.parse(response.response);
  1290. let result = null;
  1291. obj.users.forEach(pos => {
  1292. if(pos.user.username?.toLowerCase() === username?.toLowerCase()){
  1293. result = pos;
  1294. }
  1295. });
  1296.  
  1297. if(result != null){
  1298. resolve(result);
  1299. }
  1300. else{
  1301. alert("Can not find user info from getUserId()");
  1302. }
  1303. },
  1304. onerror: function(err){
  1305. reject(err);
  1306. }
  1307. });
  1308. });
  1309. }
  1310.  
  1311. /**
  1312. * getUserHighSizeProfile
  1313. * Get user's high quality avatar image.
  1314. *
  1315. * @param {Integer} userId
  1316. * @return {String}
  1317. */
  1318. function getUserHighSizeProfile(userId){
  1319. return new Promise((resolve,reject)=>{
  1320. let getURL = `https://i.instagram.com/api/v1/users/${userId}/info/`;
  1321.  
  1322. GM_xmlhttpRequest({
  1323. method: "GET",
  1324. url: getURL,
  1325. headers: {
  1326. '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'
  1327. },
  1328. onload: function(response) {
  1329. let obj = JSON.parse(response.response);
  1330. if(obj.status !== 'ok'){
  1331. reject('faild');
  1332. }
  1333. else{
  1334. resolve(obj.user.hd_profile_pic_url_info?.url);
  1335. }
  1336. },
  1337. onerror: function(err){
  1338. reject(err);
  1339. }
  1340. });
  1341. });
  1342. }
  1343.  
  1344. /**
  1345. * getPostOwner
  1346. * Get post's author with post shortcode
  1347. *
  1348. * @param {String} postPath
  1349. * @return {String}
  1350. */
  1351. function getPostOwner(postPath){
  1352. return new Promise((resolve,reject)=>{
  1353. if(!postPath) reject("NOPATH");
  1354. let postShortCode = postPath;
  1355. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  1356.  
  1357. GM_xmlhttpRequest({
  1358. method: "GET",
  1359. url: getURL,
  1360. onload: function(response) {
  1361. let obj = JSON.parse(response.response);
  1362. resolve(obj.data.shortcode_media.owner.username);
  1363. },
  1364. onerror: function(err){
  1365. reject(err);
  1366. }
  1367. });
  1368. });
  1369. }
  1370.  
  1371. /**
  1372. * getBlobMedia
  1373. * Get list of all media files in post with post shortcode
  1374. *
  1375. * @param {String} postPath
  1376. * @return {Object}
  1377. */
  1378. function getBlobMedia(postPath){
  1379. return new Promise((resolve,reject)=>{
  1380. if(!postPath) reject("NOPATH");
  1381. let postShortCode = postPath;
  1382. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  1383.  
  1384. GM_xmlhttpRequest({
  1385. method: "GET",
  1386. url: getURL,
  1387. onload: function(response) {
  1388. let obj = JSON.parse(response.response);
  1389. console.log(obj);
  1390. resolve(obj.data);
  1391. },
  1392. onerror: function(err){
  1393. reject(err);
  1394. }
  1395. });
  1396. });
  1397. }
  1398.  
  1399. /**
  1400. * onReadyMyDW
  1401. * Create an event entry point for the download button for the post
  1402. *
  1403. * @param {Boolean} NoDialog - Check if it not showing the dialog
  1404. * @param {?Boolean} hasReferrer - Check if the source of the previous page is a story page
  1405. * @return {void}
  1406. */
  1407. function onReadyMyDW(NoDialog, hasReferrer){
  1408. if(hasReferrer === true){
  1409. console.log('hasReferrer', 'regenerated');
  1410. $('article[data-snig="canDownload"], div[data-snig="canDownload"]').filter(function(){
  1411. return $(this).find('.SNKMS_IG_DW_MAIN').length === 0
  1412. }).removeAttr('data-snig');
  1413. }
  1414.  
  1415. // Whether is Instagram dialog?
  1416. if(NoDialog == false){
  1417. const maxCall = 100;
  1418. let i = 0;
  1419. var repeat = setInterval(() => {
  1420. // 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) >>
  1421. // section:visible > main > div > div.xdt5ytf[data-snig="canDownload"] << (former CSS selector for single foreground post in page, non-floating) >>
  1422. // <hr> is much more unique element than "div.xdt5ytf"
  1423. 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){
  1424. clearInterval(repeat);
  1425.  
  1426. if(i > maxCall){
  1427. //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.');
  1428. console.warn('onReadyMyDW() Timer', 'maximum number of repetitions reached, terminated');
  1429. }
  1430. }
  1431.  
  1432. console.log('onReadyMyDW() Timer', 'repeating to call detection createDownloadButton()');
  1433. createDownloadButton();
  1434. i++;
  1435. },50);
  1436. }
  1437. else{
  1438. createDownloadButton();
  1439. }
  1440. }
  1441.  
  1442. /**
  1443. * getAppID
  1444. * Get Instagram App ID
  1445. *
  1446. * @return {?integer}
  1447. */
  1448. function getAppID(){
  1449. let result = null;
  1450. $('script[type="application/json"]').each(function(){
  1451. const regexp = /"APP_ID":"([0-9]+)"/ig;
  1452. const matcher = $(this).text().match(regexp);
  1453. if(matcher != null && result == null){
  1454. result = [...$(this).text().matchAll(regexp)];
  1455. }
  1456. })
  1457.  
  1458. return (result)?result.at(0).at(-1):null;
  1459. }
  1460.  
  1461. /**
  1462. * updateLoadingBar
  1463. * Update loading state
  1464. *
  1465. * @param {Boolean} isLoading - Check if loading state
  1466. * @return {void}
  1467. */
  1468. function updateLoadingBar(isLoading){
  1469. if(isLoading){
  1470. $('div[id^="mount"] > div > div > div:first').removeClass('x1s85apg');
  1471. $('div[id^="mount"] > div > div > div:first').css('z-index','20000');
  1472. }
  1473. else{
  1474. $('div[id^="mount"] > div > div > div:first').addClass('x1s85apg');
  1475. $('div[id^="mount"] > div > div > div:first').css('z-index','');
  1476. }
  1477. }
  1478.  
  1479. /**
  1480. * getMediaInfo
  1481. * Get Instagram Media object
  1482. *
  1483. * @param {String} mediaId
  1484. * @return {Object}
  1485. */
  1486. function getMediaInfo(mediaId){
  1487. return new Promise((resolve,reject)=>{
  1488. let getURL = `https://i.instagram.com/api/v1/media/${mediaId}/info/`;
  1489.  
  1490. if(mediaId == null){
  1491. alert("Can not call Media API because of the media id is invalid.");
  1492.  
  1493. updateLoadingBar(false);
  1494. reject(-1);
  1495. return;
  1496. }
  1497. if(getAppID() == null){
  1498. alert("Can not call Media API because of the app id is invalid.");
  1499.  
  1500. updateLoadingBar(false);
  1501. reject(-1);
  1502. return;
  1503. }
  1504.  
  1505. GM_xmlhttpRequest({
  1506. method: "GET",
  1507. url: getURL,
  1508. headers: {
  1509. "User-Agent": window.navigator.userAgent,
  1510. "Accept": "*/*",
  1511. 'X-IG-App-ID': getAppID()
  1512. },
  1513. onload: function(response) {
  1514. if(response.finalUrl == getURL){
  1515. let obj = JSON.parse(response.response);
  1516. resolve(obj);
  1517. }
  1518. else{
  1519. let finalURL = new URL(response.finalUrl);
  1520. if(finalURL.pathname.startsWith('/accounts/login')){
  1521. alert("The account must be logged in to access Media API.");
  1522. }
  1523. else{
  1524. alert('Unable to retrieve content because the API was redirected to "'+response.finalUrl+'"');
  1525. }
  1526. updateLoadingBar(false);
  1527. reject(-1);
  1528. }
  1529. },
  1530. onerror: function(err){
  1531. resolve(err);
  1532. }
  1533. });
  1534. });
  1535. }
  1536.  
  1537. /**
  1538. * getVisibleNodeIndex
  1539. * Get element visible node
  1540. *
  1541. * @param {Object} $main
  1542. * @return {Integer}
  1543. */
  1544. function getVisibleNodeIndex($main){
  1545. var index = 0;
  1546. // homepage classList
  1547. var $dot = $main.find('.x1iyjqo2 > div > div:last-child > div');
  1548.  
  1549. // dialog classList, main top classList
  1550. if($dot == null || !$dot.hasClass('_acnb')){
  1551. $dot = $main.find('._aatk > div > div:last-child').eq(0).children('div');
  1552. }
  1553.  
  1554. $dot.filter('._acnb').each(function(sIndex){
  1555. if($(this).hasClass('_acnf')){
  1556. index = sIndex;
  1557. }
  1558. });
  1559.  
  1560. return index;
  1561. }
  1562.  
  1563. /**
  1564. * initPostVideoFunction
  1565. * Initialize settings related to the video resources in the post
  1566. *
  1567. * @param {Object} $mainElement
  1568. * @return {Void}
  1569. */
  1570. function initPostVideoFunction($mainElement){
  1571. // Disable video autoplay
  1572. if(USER_SETTING.DISABLE_VIDEO_LOOPING){
  1573. $mainElement.find('video').each(function(){
  1574. if(!$(this).data('loop')){
  1575. console.log('(post) Added video event listener #loop');
  1576. $(this).on('ended',function(){
  1577. $(this).attr('data-loop', true);
  1578. this.pause();
  1579. });
  1580. }
  1581. });
  1582. }
  1583.  
  1584. // Modify Video Volume
  1585. if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  1586. $mainElement.find('video').each(function(){
  1587. if(!$(this).data('modify')){
  1588. console.log('(post) Added video event listener #modify');
  1589. this.volume = VIDEO_VOLUME;
  1590.  
  1591. $(this).on('play',function(){
  1592. this.volume = VIDEO_VOLUME;
  1593. });
  1594. $(this).on('playing',function(){
  1595. this.volume = VIDEO_VOLUME;
  1596. });
  1597. $(this).on('timeupdate',function(){
  1598. this.volume = VIDEO_VOLUME;
  1599. });
  1600.  
  1601. $(this).attr('data-modify', true);
  1602. }
  1603. });
  1604. }
  1605.  
  1606. if(USER_SETTING.HTML5_VIDEO_CONTROL){
  1607. $mainElement.find('video').each(function(){
  1608. if(!$(this).data('controls')){
  1609. console.log('(post) Added video html5 contorller #modify');
  1610. this.volume = VIDEO_VOLUME;
  1611.  
  1612. $(this).on('loadstart',function(){
  1613. this.volume = VIDEO_VOLUME;
  1614. });
  1615.  
  1616. $(this).on('volumechange',function(){
  1617. let $element_mute_button = $(this).parent().find('video + div > div').find('button[type="button"], div[role="button"]').filter(function(idx){
  1618. // This is mute/unmute's icon
  1619. 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;
  1620. });
  1621.  
  1622. var is_elelment_muted = $element_mute_button.find('svg > path[d^="M16.636"]').length === 0;
  1623.  
  1624. if(this.muted != is_elelment_muted){
  1625. this.volume = VIDEO_VOLUME;
  1626. $element_mute_button?.click();
  1627. }
  1628.  
  1629. if ($(this).attr('data-completed')){
  1630. VIDEO_VOLUME = this.volume;
  1631. GM_setValue('G_VIDEO_VOLUME', this.volume);
  1632. }
  1633.  
  1634. if(this.volume == VIDEO_VOLUME){
  1635. $(this).attr('data-completed', true);
  1636. }
  1637. });
  1638.  
  1639. $(this).css('position', 'absolute');
  1640. $(this).css('z-index', '2');
  1641. $(this).attr('data-controls', true);
  1642. $(this).attr('controls', true);
  1643. }
  1644. });
  1645. }
  1646.  
  1647.  
  1648. var $buttonParent = $mainElement.find('video + div > div').first();
  1649. $buttonParent.append('<div class="volume_slider bottom" />');
  1650. $buttonParent.find('div.volume_slider').append(`<div><input type="range" max="1" min="0" step="0.05" value="${VIDEO_VOLUME}" /></div>`);
  1651. $buttonParent.find('div.volume_slider input').attr('style',`--ig-track-progress: ${(VIDEO_VOLUME * 100) + '%'}`);
  1652. $buttonParent.find('div.volume_slider input').on('input',function(){
  1653. var percent = ($(this).val() * 100) + '%';
  1654.  
  1655. VIDEO_VOLUME = $(this).val();
  1656. GM_setValue('G_VIDEO_VOLUME', $(this).val());
  1657.  
  1658. $(this).attr('style',`--ig-track-progress: ${percent}`);
  1659.  
  1660. $mainElement.find('video').each(function(){
  1661. console.log('(post) video volume changed #slider');
  1662. this.volume = VIDEO_VOLUME;
  1663. });
  1664. });
  1665.  
  1666. $buttonParent.find('div.volume_slider input').on('mouseenter',function(){
  1667. var percent = (VIDEO_VOLUME * 100) + '%';
  1668. $(this).attr('style',`--ig-track-progress: ${percent}`);
  1669. $(this).val(VIDEO_VOLUME);
  1670. $mainElement.find('video').each(function(){
  1671. console.log('(post) video volume changed #slider');
  1672. this.volume = VIDEO_VOLUME;
  1673. });
  1674. });
  1675.  
  1676. $buttonParent.find('div.volume_slider').on('click',function(e){
  1677. e.stopPropagation();
  1678. e.preventDefault();
  1679. });
  1680. };
  1681.  
  1682. /**
  1683. * createDownloadButton
  1684. * Create a download button in the upper right corner of each post
  1685. *
  1686. * @return {void}
  1687. */
  1688. function createDownloadButton(){
  1689. // Add download icon per each posts
  1690. $('article[class], section:visible > main > div > div > div > div > div > hr').map(function(index){
  1691. return $(this).is('section:visible > main > div > div > div > div > div > hr') ? $(this).parent().parent().parent().parent()[0] : this;
  1692. }).filter(function(){
  1693. return $(this).height() > 0 && $(this).width() > 0
  1694. })
  1695. .each(function(index){
  1696. // If it is have not download icon
  1697. // class x1iyjqo2 mean user profile pages post list container
  1698. if(!$(this).attr('data-snig') && !$(this).hasClass('x1iyjqo2') && !$(this).children('article')?.hasClass('x1iyjqo2') && $(this).parents('div#scrollview').length === 0){
  1699. console.log("Found post container", $(this));
  1700.  
  1701. var rightPos = 15;
  1702. var topPos = 15;
  1703. var $mainElement = $(this);
  1704. var tagName = this.tagName;
  1705.  
  1706. // not loop each in single top post
  1707. if(tagName === "DIV" && index != 0){
  1708. return;
  1709. }
  1710.  
  1711. // New post UI by Discord: ken
  1712. // NOT WORKING
  1713. /*
  1714. if(tagName === "DIV" && $(this).attr('role') === "presentation"){
  1715. rightPos = 28;
  1716. topPos = 75;
  1717. $mainElement = $('div._aap0[role="presentation"]').parents('div._aamm').parent().parent().parent().parent().parent();
  1718. }
  1719. */
  1720.  
  1721. const $childElement = $mainElement.children("div").children("div");
  1722.  
  1723. if($childElement.length === 0) return;
  1724.  
  1725. console.log("Found insert point", $childElement);
  1726.  
  1727. // Modify carousel post counter's position to not interfere with our buttons
  1728. if($mainElement.find('._acay').length > 0){
  1729. if($mainElement.find('._acay + .x24i39r').length > 0){
  1730. $mainElement.find('._acay + .x24i39r').css('top', '37px');
  1731. }
  1732.  
  1733. const observeNode = $mainElement.find('._acay').first().parent()[0];
  1734. var observer = new MutationObserver(function (mutation, owner) {
  1735. $mainElement.find('._acay + .x24i39r').css('top', '37px');
  1736. });
  1737.  
  1738. observer.observe(observeNode, {
  1739. childList: true
  1740. });
  1741. }
  1742.  
  1743. // Add icons
  1744. const DownloadElement = `<div title="${_i18n("DW")}" class="SNKMS_IG_DW_MAIN" style="right:${rightPos}px;top:${topPos}px;">${SVG.DOWNLOAD}</div>`;
  1745. const NewTabElement = `<div title="${_i18n("NEW_TAB")}" class="SNKMS_IG_NEWTAB_MAIN" style="right:${rightPos + 35}px;top:${topPos}px;">${SVG.NEW_TAB}</div>`;
  1746. const ThumbnailElement = `<div title="${_i18n("THUMBNAIL_INTRO")}" class="SNKMS_IG_THUMBNAIL_MAIN" style="right:${rightPos + 70}px;top:${topPos}px;">${SVG.THUMBNAIL}</div>`;
  1747.  
  1748. $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).append(DownloadElement);
  1749. $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).append(NewTabElement);
  1750.  
  1751. setTimeout(()=>{
  1752. // Check if visible post is video
  1753. if($childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).find('div > ul li._acaz').length === 0){
  1754. if($childElement.find('video').length > 0){
  1755. $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).append(ThumbnailElement);
  1756. }
  1757. }
  1758. else{
  1759. const checkVideoNode = function(target){
  1760. if(target){
  1761. var k = $(target).find('li._acaz').length;
  1762. var $targetNode = null;
  1763.  
  1764. if(k == 2){
  1765. var index = getVisibleNodeIndex($mainElement);
  1766. // First node
  1767. if(index === 0){
  1768. $targetNode = $(target).find('li._acaz').first();
  1769. }
  1770. // Last node
  1771. else{
  1772. $targetNode = $(target).find('li._acaz').last();
  1773. }
  1774. }
  1775. // Middle node
  1776. else{
  1777. $targetNode = $(target).find('li._acaz').eq(1);
  1778. }
  1779.  
  1780. // Check if video?
  1781. if($targetNode != null && $targetNode.length > 0 && $targetNode.find('video').length > 0){
  1782. $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).append(ThumbnailElement);
  1783. initPostVideoFunction($mainElement);
  1784. }
  1785. else{
  1786. $childElement.find('.SNKMS_IG_THUMBNAIL_MAIN')?.remove();
  1787. }
  1788. }
  1789. };
  1790.  
  1791. var observer = new MutationObserver(function (mutation, owner) {
  1792. var target = mutation.at(0)?.target;
  1793. checkVideoNode(target);
  1794. });
  1795.  
  1796. const element = $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).find('div > ul li._acaz')?.parent()[0];
  1797. const elementAttr = $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).find('div > ul li._acaz')?.parent().parent()[0];
  1798.  
  1799. if(element){
  1800. checkVideoNode(element);
  1801. observer.observe(element, {
  1802. childList: true
  1803. });
  1804. }
  1805.  
  1806. if(elementAttr){
  1807. observer.observe(elementAttr, {
  1808. attributes: true
  1809. });
  1810. }
  1811. }
  1812. }, 50);
  1813.  
  1814.  
  1815. $childElement.css('position','relative');
  1816.  
  1817. initPostVideoFunction($mainElement);
  1818.  
  1819. $(this).on('click', '.SNKMS_IG_THUMBNAIL_MAIN', function(e){
  1820. updateLoadingBar(true);
  1821.  
  1822. GL_username = $(this).parent().parent().parent().attr('data-username');
  1823. GL_postPath = location.pathname.replace(/\/$/,'').split('/').at(-1) || $(this).parent().parent().parent().find('a[href^="/p/"]').first().attr("href").split("/").at(2) || $(this).parent().parent().children("div:last-child").children("div").children("div:last-child").find('a[href^="/p/"]').last().attr("href").split("/").at(2);
  1824.  
  1825. var $main = $(this).parent().parent().parent();
  1826. var index = getVisibleNodeIndex($main);
  1827.  
  1828. IG_createDM(true, false);
  1829.  
  1830. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", "").then(()=>{
  1831. let checkBlob = setInterval(()=>{
  1832. if($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0){
  1833. clearInterval(checkBlob);
  1834. var $videoThumbnail = $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="'+(index+1)+'"]')?.parent().find('.videoThumbnail')?.first();
  1835.  
  1836. if($videoThumbnail != null && $videoThumbnail.length > 0){
  1837. $videoThumbnail.click();
  1838. }
  1839. else{
  1840. alert('Can not find thumbnail url.');
  1841. }
  1842.  
  1843. updateLoadingBar(false);
  1844. $('.IG_SN_DIG').remove();
  1845. }
  1846. },250);
  1847. });
  1848. });
  1849.  
  1850. $(this).on('click', '.SNKMS_IG_NEWTAB_MAIN', function(e){
  1851. updateLoadingBar(true);
  1852.  
  1853. GL_username = $(this).parent().parent().parent().attr('data-username');
  1854. GL_postPath = location.pathname.replace(/\/$/,'').split('/').at(-1) || $(this).parent().parent().parent().find('a[href^="/p/"]').first().attr("href").split("/").at(2) || $(this).parent().parent().children("div:last-child").children("div").children("div:last-child").find('a[href^="/p/"]').last().attr("href").split("/").at(2);
  1855.  
  1856. var $main = $(this).parent().parent().parent();
  1857. var index = getVisibleNodeIndex($main);
  1858.  
  1859. IG_createDM(true, false);
  1860.  
  1861. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", "").then(()=>{
  1862. let checkBlob = setInterval(()=>{
  1863. if($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0){
  1864. clearInterval(checkBlob);
  1865. var $linkElement = $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="'+(index+1)+'"]');
  1866.  
  1867. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && USER_SETTING.NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST){
  1868. triggerLinkElement( $linkElement.first()[0], true);
  1869. }
  1870. else{
  1871. let href = $linkElement?.attr('data-href');
  1872. if(href){
  1873. // replace https://instagram.ftpe8-2.fna.fbcdn.net/ to https://scontent.cdninstagram.com/ becase of same origin policy (some video)
  1874. var urlObj = new URL(href);
  1875. urlObj.host = 'scontent.cdninstagram.com';
  1876.  
  1877. openNewTab(urlObj.href);
  1878. }
  1879. else{
  1880. alert('Can not find open tab url.');
  1881. }
  1882. }
  1883.  
  1884. updateLoadingBar(false);
  1885. $('.IG_SN_DIG').remove();
  1886. }
  1887. },250);
  1888. });
  1889. });
  1890.  
  1891. // Running if user click the download icon
  1892. $(this).on('click','.SNKMS_IG_DW_MAIN', async function(e){
  1893. GL_username = $(this).parent().parent().parent().attr('data-username');
  1894. GL_postPath = location.pathname.replace(/\/$/,'').split('/').at(-1) || $(this).parent().parent().parent().find('a[href^="/p/"]').first().attr("href").split("/").at(2) || $(this).parent().parent().children("div:last-child").children("div").children("div:last-child").find('a[href^="/p/"]').last().attr("href").split("/").at(2);
  1895.  
  1896. // Create element that download dailog
  1897. IG_createDM(USER_SETTING.DIRECT_DOWNLOAD_ALL, true);
  1898.  
  1899. $("#article-id").html(`<a href="https://www.instagram.com/p/${GL_postPath}">${GL_postPath}</a>`);
  1900.  
  1901. if(USER_SETTING.DIRECT_DOWNLOAD_VISIBLE_RESOURCE){
  1902. updateLoadingBar(true);
  1903. IG_setDM(true);
  1904.  
  1905. var index = getVisibleNodeIndex($(this).parent().parent().parent());
  1906.  
  1907. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", "").then(()=>{
  1908. let checkBlob = setInterval(()=>{
  1909. if($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0){
  1910. clearInterval(checkBlob);
  1911. var href = $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="'+(index+1)+'"]')?.attr('data-href');
  1912.  
  1913. if(href){
  1914. updateLoadingBar(false);
  1915. $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="'+(index+1)+'"]')?.click();
  1916. }
  1917. else{
  1918. alert('Can not find download url.');
  1919. }
  1920.  
  1921. $('.IG_SN_DIG').remove();
  1922. }
  1923. },250);
  1924. });
  1925.  
  1926. return;
  1927. }
  1928.  
  1929. if(!USER_SETTING.DIRECT_DOWNLOAD_ALL){
  1930. // Find video/image element and add the download icon
  1931. var s = 0;
  1932. var multiple = $(this).parent().parent().find('._acay ._acaz').length;
  1933. var pathname = window.location.pathname;
  1934. var fullpathname = "/"+pathname.split('/')[1]+"/"+pathname.split('/')[2]+"/";
  1935. var blob = USER_SETTING.FORCE_FETCH_ALL_RESOURCES;
  1936. var publish_time = new Date($(this).parent().parent().find('a[href^="/p/"] time[datetime]').first().attr('datetime')).getTime();
  1937.  
  1938. // If posts have more than one images or videos.
  1939. if(multiple){
  1940. $(this).parent().find('._acay ._acaz').each(function(){
  1941. let element_videos = $(this).parent().parent().find('video');
  1942. //if(element_videos && element_videos.attr('src') && element_videos.attr('src').match(/^blob:/ig)){
  1943. if(element_videos && element_videos.attr('src')){
  1944. blob = true;
  1945. }
  1946. });
  1947.  
  1948.  
  1949. if(blob || USER_SETTING.FORCE_RESOURCE_VIA_MEDIA){
  1950. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_MULTIPLE"));
  1951. }
  1952. else{
  1953. $(this).parent().find('._acay ._acaz').each(function(){
  1954. s++;
  1955. let element_videos = $(this).find('video');
  1956. let element_images = $(this).find('._aagv img');
  1957. let imgLink = (element_images.attr('srcset'))?element_images.attr('srcset').split(" ")[0]:element_images.attr('src');
  1958.  
  1959. if(element_videos && element_videos.attr('src')){
  1960. blob = true;
  1961. }
  1962. if(element_images && imgLink){
  1963. $('.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/>- ${_i18n("IMG")} ${s} -</a>`);
  1964. }
  1965.  
  1966. });
  1967.  
  1968. if(blob){
  1969. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_RELOAD"));
  1970. }
  1971. }
  1972. }
  1973. else{
  1974. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA){
  1975. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_MULTIPLE"));
  1976. }
  1977. else{
  1978. s++;
  1979. let element_videos = $(this).parent().parent().find('video');
  1980. let element_images = $(this).parent().parent().find('._aagv img');
  1981. let imgLink = (element_images.attr('srcset'))?element_images.attr('srcset').split(" ")[0]:element_images.attr('src');
  1982.  
  1983.  
  1984. if(element_videos && element_videos.attr('src')){
  1985. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_ONE"));
  1986. }
  1987. if(element_images && imgLink){
  1988. $('.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/>- ${_i18n("IMG")} ${s} -</a>`);
  1989. }
  1990. }
  1991. }
  1992. }
  1993.  
  1994. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function(){
  1995. $(this).wrap('<div></div>');
  1996. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  1997. $(this).after(`<div title="${_i18n("NEW_TAB")}" class="newTab">${SVG.NEW_TAB}</div>`);
  1998.  
  1999. if($(this).attr('data-name') == 'video'){
  2000. $(this).after(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="videoThumbnail">${SVG.THUMBNAIL}</div>`);
  2001. }
  2002. });
  2003.  
  2004. if(USER_SETTING.DIRECT_DOWNLOAD_ALL){
  2005. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_MULTIPLE")).then(()=>{
  2006. let checkBlob = setInterval(()=>{
  2007. if($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0){
  2008. clearInterval(checkBlob);
  2009. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function(){
  2010. $(this).click();
  2011. });
  2012.  
  2013. $('.IG_SN_DIG').remove();
  2014. }
  2015. },250);
  2016. });
  2017. }
  2018. });
  2019.  
  2020. // Add the mark that download is ready
  2021. var username = $(this).find("header > div:last-child > div:first-child span a").first().text();
  2022.  
  2023. $(this).attr('data-snig','canDownload');
  2024. $(this).attr('data-username',username);
  2025. }
  2026. });
  2027. }
  2028.  
  2029. /**
  2030. * createMediaListDOM
  2031. * Create a list of media elements from post URLs
  2032. *
  2033. * @param {String} postURL
  2034. * @param {String} selector - Use CSS element selectors to choose where it appears.
  2035. * @param {String} message - i18n display loading message
  2036. * @return {void}
  2037. */
  2038. function createMediaListDOM(postURL,selector,message){
  2039. return new Promise(async (resolve) => {
  2040. $(`${selector} a`).remove();
  2041. $(selector).append('<p id="_SNLOAD">'+ message +'</p>');
  2042. let media = await getBlobMedia(postURL);
  2043.  
  2044. let idx = 1;
  2045. let resource = media.shortcode_media;
  2046.  
  2047. // GraphVideo
  2048. if(resource.__typename == "GraphVideo" && resource.video_url){
  2049. $(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/>- ${_i18n("VID")} ${idx} -</a>`);
  2050. idx++;
  2051. }
  2052. // GraphImage
  2053. if(resource.__typename == "GraphImage"){
  2054. $(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/>- ${_i18n("IMG")} ${idx} -</a>`);
  2055. idx++;
  2056. }
  2057. // GraphSidecar
  2058. if(resource.__typename == "GraphSidecar" && resource.edge_sidecar_to_children){
  2059. for(let e of resource.edge_sidecar_to_children.edges){
  2060. if(e.node.__typename == "GraphVideo"){
  2061. $(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/>- ${_i18n("VID")} ${idx} -</a>`);
  2062. }
  2063.  
  2064. if(e.node.__typename == "GraphImage"){
  2065. $(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/>- ${_i18n("IMG")} ${idx} -</a>`);
  2066. }
  2067. idx++;
  2068. }
  2069. }
  2070.  
  2071. $("#_SNLOAD").remove();
  2072. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function(){
  2073. $(this).wrap('<div></div>');
  2074. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  2075. $(this).after(`<div title="${_i18n("NEW_TAB")}" class="newTab">${SVG.NEW_TAB}</div>`);
  2076.  
  2077. if($(this).attr('data-name') == 'video'){
  2078. $(this).after(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="videoThumbnail">${SVG.THUMBNAIL}</div>`);
  2079. }
  2080. });
  2081.  
  2082. resolve(true);
  2083. });
  2084. }
  2085.  
  2086. /**
  2087. * IG_createDM
  2088. * A dialog showing a list of all media files in the post
  2089. *
  2090. * @param {Boolean} hasHidden
  2091. * @param {Boolean} hasCheckbox
  2092. * @return {void}
  2093. */
  2094. function IG_createDM(hasHidden, hasCheckbox){
  2095. let isHidden = (hasHidden)?"hidden":"";
  2096. $('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>');
  2097. $('.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> [${_i18n("CLOSE")}]</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>`);
  2098.  
  2099. if(hasCheckbox){
  2100. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE').append(`<div style="text-align: center;" id="button_group"></div>`);
  2101. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE > div#button_group').append(`<button id="batch_download_selected">${_i18n('BATCH_DOWNLOAD_SELECTED')}</button>`);
  2102. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE > div#button_group').append(`<button id="batch_download_direct">${_i18n('BATCH_DOWNLOAD_DIRECT')}</button>`);
  2103. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE').append(`<label class="checkbox"><input value="yes" type="checkbox" />${_i18n('ALL_CHECK')}</label>`);
  2104. }
  2105. }
  2106.  
  2107. /**
  2108. * IG_setDM
  2109. * Set a dialog status
  2110. *
  2111. * @param {Boolean} hasHidden
  2112. * @return {void}
  2113. */
  2114. function IG_setDM(hasHidden){
  2115. if($('.IG_SN_DIG').length){
  2116. if(hasHidden){
  2117. $('.IG_SN_DIG').addClass("hidden");
  2118. }
  2119. else{
  2120. $('.IG_SN_DIG').removeClass("hidden");
  2121. }
  2122. }
  2123. }
  2124.  
  2125. /**
  2126. * saveFiles
  2127. * Download the specified media URL to the computer
  2128. *
  2129. * @param {String} downloadLink
  2130. * @param {String} username
  2131. * @param {String} sourceType
  2132. * @param {Integer} timestamp
  2133. * @param {String} filetype
  2134. * @param {String} shortcode
  2135. * @return {void}
  2136. */
  2137. function saveFiles(downloadLink,username,sourceType,timestamp,filetype,shortcode){
  2138. setTimeout(()=>{
  2139. updateLoadingBar(true);
  2140. fetch(downloadLink).then(res => {
  2141. return res.blob().then(dwel => {
  2142. updateLoadingBar(false);
  2143. createSaveFileElement(downloadLink,dwel,username,sourceType,timestamp,filetype,shortcode);
  2144. });
  2145. });
  2146. }, 50);
  2147. }
  2148.  
  2149. /**
  2150. * createSaveFileElement
  2151. * Download the specified media with link element
  2152. *
  2153. * @param {String} downloadLink
  2154. * @param {Object} object
  2155. * @param {String} username
  2156. * @param {String} sourceType
  2157. * @param {Integer} timestamp
  2158. * @param {String} filetype
  2159. * @param {String} shortcode
  2160. * @return {void}
  2161. */
  2162. function createSaveFileElement(downloadLink,object,username,sourceType,timestamp,filetype,shortcode) {
  2163. timestamp = parseInt(timestamp.toString().padEnd(13, '0'));
  2164.  
  2165. if(USER_SETTING.RENAME_PUBLISH_DATE){
  2166. timestamp = parseInt(timestamp.toString().padEnd(13, '0'));
  2167. }
  2168.  
  2169. const date = new Date(timestamp);
  2170.  
  2171. const a = document.createElement("a");
  2172. const original_name = new URL(downloadLink).pathname.split('/').at(-1).split('.').slice(0,-1).join('.');
  2173. const year = date.getFullYear().toString();
  2174. const month = (date.getMonth()+1).toString().padStart(2,'0');
  2175. const day = date.getDate().toString().padStart(2,'0');
  2176. const hour = date.getHours().toString().padStart(2,'0');
  2177. const minute = date.getMinutes().toString().padStart(2,'0');
  2178. const second = date.getSeconds().toString().padStart(2,'0');
  2179.  
  2180. var filename = RENAME_FORMAT.toUpperCase();
  2181. var replacements = {
  2182. '%USERNAME%': username,
  2183. '%SOURCE_TYPE%': sourceType,
  2184. '%SHORTCODE%': (shortcode)?shortcode:'',
  2185. '%YEAR%': year,
  2186. '%2-YEAR%': year.substr(-2),
  2187. '%MONTH%': month,
  2188. '%DAY%': day,
  2189. '%HOUR%': hour,
  2190. '%MINUTE%': minute,
  2191. '%SECOND%': second,
  2192. '%ORIGINAL_NAME%': original_name,
  2193. '%ORIGINAL_NAME_FIRST%': original_name.split('_').at(0)
  2194. };
  2195.  
  2196. filename = filename.replace(/%[\w\-]+%/g, function(str) {
  2197. return replacements[str] || str;
  2198. });
  2199.  
  2200. const originally = username + '_' + original_name + '.' + filetype;
  2201.  
  2202. a.href = URL.createObjectURL(object);
  2203. a.setAttribute("download", (USER_SETTING.AUTO_RENAME)?filename+'.'+filetype:originally);
  2204. a.click();
  2205. a.remove();
  2206. }
  2207.  
  2208. /**
  2209. * triggerLinkElement
  2210. * Trigger the link element to start downloading the resource
  2211. *
  2212. * @param {Object} element
  2213. * @return {void}
  2214. */
  2215. async function triggerLinkElement(element, isPreview) {
  2216. let date = new Date().getTime();
  2217. let timestamp = Math.floor(date / 1000);
  2218. let username = ($(element).attr('data-username')) ? $(element).attr('data-username') : GL_username;
  2219.  
  2220. if(!username && $(element).attr('data-path')){
  2221. console.log('catching owner name from shortcode:',$(element).attr('data-href'));
  2222. username = await getPostOwner($(element).attr('data-path'));
  2223. }
  2224.  
  2225. if(USER_SETTING.RENAME_PUBLISH_DATE && $(element).attr('datetime')){
  2226. timestamp = parseInt($(element).attr('datetime'));
  2227. }
  2228.  
  2229. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA){
  2230. updateLoadingBar(true);
  2231. let result = await getMediaInfo($(element).attr('media-id'));
  2232. updateLoadingBar(false);
  2233.  
  2234. if(result.status === 'ok'){
  2235. var resource_url = null;
  2236. if(result.items[0].video_versions){
  2237. resource_url = result.items[0].video_versions[0].url;
  2238. }
  2239. else{
  2240. resource_url = result.items[0].image_versions2.candidates[0].url;
  2241. }
  2242.  
  2243. if(isPreview){
  2244. let urlObj = new URL(resource_url);
  2245. urlObj.host = 'scontent.cdninstagram.com';
  2246.  
  2247. openNewTab(urlObj.href);
  2248. }
  2249. else{
  2250. saveFiles(resource_url, username, $(element).attr('data-name'),timestamp, $(element).attr('data-type'), $(element).attr('data-path'));
  2251. }
  2252. }
  2253. else{
  2254. if(USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT){
  2255. if(isPreview){
  2256. let urlObj = new URL($(element).attr('data-href'));
  2257. urlObj.host = 'scontent.cdninstagram.com';
  2258.  
  2259. openNewTab(urlObj.href);
  2260. }
  2261. else{
  2262. saveFiles($(element).attr('data-href'),username,$(element).attr('data-name'),timestamp,$(element).attr('data-type'), $(element).attr('data-path'));
  2263. }
  2264. }
  2265. else{
  2266. alert('Fetch failed from Media API. API response message: ' + result.message);
  2267. }
  2268. console.log(result);
  2269. }
  2270. }
  2271. else{
  2272. saveFiles($(element).attr('data-href'),username,$(element).attr('data-name'),timestamp,$(element).attr('data-type'), $(element).attr('data-path'));
  2273. }
  2274. }
  2275.  
  2276. /**
  2277. * translateText
  2278. * i18n translation text
  2279. *
  2280. * @param {String} lang
  2281. * @return {void}
  2282. */
  2283. function translateText(lang){
  2284. var eLocale = {
  2285. "en-US": {
  2286. "SELECT_LANG": "English",
  2287. "RELOAD_SCRIPT": "Reload Script",
  2288. "DONATE": "Donate",
  2289. "FEEDBACK": "Feedback",
  2290. "NEW_TAB": "Open in New Tab",
  2291. "SHOW_DOM_TREE": "Show DOM Tree",
  2292. "SELECT_AND_COPY": "Select All and Copy from the Input Box",
  2293. "DOWNLOAD_DOM_TREE": "Download DOM Tree as a Text File",
  2294. "REPORT_GITHUB": "Report an Issue on GitHub",
  2295. "REPORT_DISCORD": "Report an Issue on Discord Support Server",
  2296. "DEBUG": "Debug Window",
  2297. "CLOSE": "Close",
  2298. "ALL_CHECK": "Select All",
  2299. "BATCH_DOWNLOAD_SELECTED": "Download Selected Resources",
  2300. "BATCH_DOWNLOAD_DIRECT": "Download All Resources",
  2301. "IMG": "Image",
  2302. "VID": "Video",
  2303. "DW": "Download",
  2304. "THUMBNAIL_INTRO": "Download Video Thumbnail",
  2305. "LOAD_BLOB_ONE": "Loading Blob Media...",
  2306. "LOAD_BLOB_MULTIPLE": "Loading Blob Media and Others...",
  2307. "LOAD_BLOB_RELOAD": "Detecting Blob Media, reloading...",
  2308. "NO_CHECK_RESOURCE": "You need to select a resource to download.",
  2309. "NO_VID_URL": "Cannot find video URL.",
  2310. "SETTING": "Settings",
  2311. "AUTO_RENAME": "Automatically Rename Files (Right-Click to Set)",
  2312. "RENAME_SHORTCODE": "Rename the File and Include Shortcode",
  2313. "RENAME_PUBLISH_DATE": "Set Renamed File Timestamp to Resource Publish Date",
  2314. "RENAME_LOCATE_DATE": "Modify Renamed File Timestamp Date Format (Right-Click to Set)",
  2315. "DISABLE_VIDEO_LOOPING": "Disable Video Auto-looping",
  2316. "HTML5_VIDEO_CONTROL": "Display HTML5 Video Controller",
  2317. "REDIRECT_CLICK_USER_STORY_PICTURE": "Redirect When Clicking on User's Story Picture",
  2318. "FORCE_FETCH_ALL_RESOURCES": "Force Fetch All Resources in the Post",
  2319. "DIRECT_DOWNLOAD_VISIBLE_RESOURCE": "Directly Download the Visible Resources in the Post",
  2320. "DIRECT_DOWNLOAD_ALL": "Directly Download All Resources in the Post",
  2321. "MODIFY_VIDEO_VOLUME": "Modify Video Volume (Right-Click to Set)",
  2322. "SCROLL_BUTTON": "Enable Scroll Buttons for Reels Page",
  2323. "FORCE_RESOURCE_VIA_MEDIA": "Force Fetch Resource via Media API",
  2324. "USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT": "Use Alternative Methods to Download When the Media API is Not Accessible",
  2325. "NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST": "Always Use Media API for 'Open in New Tab' in Posts",
  2326. "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",
  2327. "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.",
  2328. "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.",
  2329. "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.",
  2330. "DISABLE_VIDEO_LOOPING_INTRO": "Disable video auto-looping in Reels and posts.",
  2331. "HTML5_VIDEO_CONTROL_INTRO": "Display the HTML5 video controller in posts and Reels.\n\nThis will hide the custom video volume slider and replace it with the HTML5 controller. In Reels pages, the HTML5 controller can be hidden by right-clicking on the video to reveal the original details.",
  2332. "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.",
  2333. "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.",
  2334. "DIRECT_DOWNLOAD_VISIBLE_RESOURCE_INTRO": "Directly download the current resources available in the post.",
  2335. "DIRECT_DOWNLOAD_ALL_INTRO": "When you click the download button, all resources in the post will be forcibly fetched and downloaded.",
  2336. "MODIFY_VIDEO_VOLUME_INTRO": "Modify the video playback volume in Reels and posts (right-click to open the volume setting slider).",
  2337. "SCROLL_BUTTON_INTRO": "Enable scroll buttons for the lower right corner of the Reels page.",
  2338. "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.",
  2339. "USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT_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).",
  2340. "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."
  2341. }
  2342. };
  2343.  
  2344. var resultUnsorted = Object.assign({}, eLocale, locale);
  2345. var resultSorted = Object.keys(resultUnsorted).sort().reduce(
  2346. (obj, key) => {
  2347. obj[key] = resultUnsorted[key];
  2348. return obj;
  2349. }, {}
  2350. );
  2351.  
  2352. return resultSorted;
  2353. }
  2354.  
  2355. /**
  2356. * _i18n
  2357. * Perform i18n translation
  2358. *
  2359. * @param {String} text
  2360. * @return {void}
  2361. */
  2362. function _i18n(text){
  2363. const translate = translateText();
  2364.  
  2365. if(translate[lang] != undefined && translate[lang][text] != undefined){
  2366. return translate[lang][text];
  2367. }
  2368. else{
  2369. return translate["en-US"][text];
  2370. }
  2371. }
  2372.  
  2373. /**
  2374. * showSetting
  2375. * Show script settings window
  2376. *
  2377. * @return {void}
  2378. */
  2379. function showSetting(){
  2380. $('.IG_SN_DIG').remove();
  2381. IG_createDM();
  2382. $('.IG_SN_DIG #post_info').text('Preference Settings');
  2383.  
  2384. $('.IG_SN_DIG .IG_SN_DIG_TITLE > div').append('<select id="langSelect"></select><div style="font-size: 12px;">The newly selected language will be applied after refreshing the page.</div>');
  2385.  
  2386. for(let o in translateText()){
  2387. $('.IG_SN_DIG .IG_SN_DIG_TITLE > div #langSelect').append(`<option value="${o}" ${(lang == o)?'selected':''}>${translateText()[o].SELECT_LANG}</option>`);
  2388. }
  2389.  
  2390. for(let name in USER_SETTING){
  2391. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<label class="globalSettings${(CHILD_NODES.includes(name))?' child':''}" title="${_i18n(name+'_INTRO')}"><span>${_i18n(name)}</span> <input id="${name}" value="box" type="checkbox" ${(USER_SETTING[name] === true)?'checked':''}><div class="chbtn"><div class="rounds"></div></div></label>`);
  2392.  
  2393. if(name === 'MODIFY_VIDEO_VOLUME'){
  2394. $('.IG_SN_DIG .IG_SN_DIG_BODY input[id="'+name+'"]').parent('label').on('contextmenu', function(e){
  2395. e.preventDefault();
  2396. if($(this).find('#tempWrapper').length === 0){
  2397. $(this).append('<div id="tempWrapper"></div>');
  2398. $(this).children('#tempWrapper').append('<input value="' + VIDEO_VOLUME + '" type="range" min="0" max="1" step="0.05" />');
  2399. $(this).children('#tempWrapper').append('<input value="' + VIDEO_VOLUME + '" step="0.05" type="number" />');
  2400. $(this).children('#tempWrapper').append(`<div class="IG_SN_DIG_BTN">${SVG.CLOSE}</div>`);
  2401. }
  2402. });
  2403. }
  2404.  
  2405. if(name === 'AUTO_RENAME'){
  2406. $('.IG_SN_DIG .IG_SN_DIG_BODY input[id="'+name+'"]').parent('label').on('contextmenu', function(e){
  2407. e.preventDefault();
  2408. if($(this).find('#tempWrapper').length === 0){
  2409. $(this).append('<div id="tempWrapper"></div>');
  2410.  
  2411. $(this).children('#tempWrapper').append('<input id="date_format" value="' + RENAME_FORMAT + '" />');
  2412. $(this).children('#tempWrapper').append(`<div class="IG_SN_DIG_BTN">${SVG.CLOSE}</div>`);
  2413. }
  2414. });
  2415. }
  2416. }
  2417. }
  2418.  
  2419. /**
  2420. * showDebugDOM
  2421. * Show full DOM tree
  2422. *
  2423. * @return {void}
  2424. */
  2425. function showDebugDOM(){
  2426. $('.IG_SN_DIG').remove();
  2427. IG_createDM();
  2428. $('.IG_SN_DIG #post_info').text('IG Debug DOM Tree');
  2429.  
  2430. $('.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>`);
  2431. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<span style="display:block;text-align:center;">`);
  2432. $('.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>`);
  2433. $('.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>`);
  2434. $('.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/>`);
  2435. $('.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>`);
  2436. $('.IG_SN_DIG .IG_SN_DIG_BODY span').append(`<button style="margin: 3px;" class="IG_REPORT_DISCORD"><a href="https://discord.gg/Sh8HJ4d" target="_blank">${_i18n('REPORT_DISCORD')}</a></button>`);
  2437. }
  2438.  
  2439. /**
  2440. * openNewTab
  2441. * Open url in new tab
  2442. *
  2443. * @param {String} link
  2444. * @return {void}
  2445. */
  2446. function openNewTab(link){
  2447. var a = document.createElement('a');
  2448. a.href = link;
  2449. a.target = '_blank';
  2450.  
  2451. document.body.appendChild(a);
  2452. a.click();
  2453. a.remove();
  2454. }
  2455.  
  2456. /**
  2457. * reloadScript
  2458. * Re-register main timer
  2459. *
  2460. * @return {void}
  2461. */
  2462. function reloadScript(){
  2463. clearInterval(GL_repeat);
  2464. pageLoaded = false;
  2465. firstStarted = false;
  2466. currentURL = location.href;
  2467. GL_observer.disconnect();
  2468.  
  2469. console.log('main timer re-register completed');
  2470. }
  2471.  
  2472. /**
  2473. * initSettings
  2474. * Initialize preferences
  2475. *
  2476. * @return {void}
  2477. */
  2478. function initSettings(){
  2479. for(let name in USER_SETTING){
  2480. if(GM_getValue(name) != null && typeof GM_getValue(name) === 'boolean'){
  2481. USER_SETTING[name] = GM_getValue(name);
  2482. }
  2483. }
  2484. }
  2485.  
  2486. // Running if document is ready
  2487. $(function(){
  2488. $('body').on('click','.IG_SN_DIG .IG_SN_DIG_BODY .IG_DISPLAY_DOM_TREE',function(){
  2489. let text = $('div[id^="mount"]')[0];
  2490. $('.IG_SN_DIG .IG_SN_DIG_BODY textarea').text("Location: " + location.pathname + "\nDOM Tree:\n" + text.innerHTML);
  2491. });
  2492.  
  2493. $('body').on('click','.IG_SN_DIG .IG_SN_DIG_BODY .IG_SELECT_DOM_TREE',function(){
  2494. $('.IG_SN_DIG .IG_SN_DIG_BODY textarea').select();
  2495. document.execCommand('copy');
  2496. });
  2497.  
  2498. $('body').on('click','.IG_SN_DIG .IG_SN_DIG_BODY .IG_DOWNLOAD_DOM_TREE',function(){
  2499. var text = ($('.IG_SN_DIG .IG_SN_DIG_BODY textarea').text().length > 0)?$('.IG_SN_DIG .IG_SN_DIG_BODY textarea').text():"Location: " + location.pathname + "\nDOM Tree:\n" +$('div[id^="mount"]')[0].innerHTML;
  2500. var a = document.createElement("a");
  2501. var file = new Blob([text], {type: "text/plain"});
  2502. a.href = URL.createObjectURL(file);
  2503. a.download = "DOMTree.txt";
  2504.  
  2505. document.body.appendChild(a);
  2506. a.click();
  2507. a.remove();
  2508. });
  2509.  
  2510. // Close the download dialog if user click the close icon
  2511. $('body').on('click','.IG_SN_DIG_BTN, .IG_SN_DIG_BG',function(){
  2512. if($(this).parent('#tempWrapper').length > 0){
  2513. $(this).parent('#tempWrapper').fadeOut(250, function(){
  2514. $(this).remove();
  2515. });
  2516. }
  2517. else{
  2518. $('.IG_SN_DIG').remove();
  2519. }
  2520. });
  2521.  
  2522. $(window).keydown(function(e){
  2523. // Hot key [Alt+Q] to close the download dialog
  2524. if (e.keyCode == '81' && e.altKey){
  2525. $('.IG_SN_DIG').remove();
  2526. e.preventDefault();
  2527. }
  2528. // Hot key [Alt+W] to open the settings dialog
  2529. if (e.keyCode == '87' && e.altKey){
  2530. showSetting();
  2531. e.preventDefault();
  2532. }
  2533.  
  2534. // Hot key [Alt+Z] to open the settings dialog
  2535. if (e.keyCode == '90' && e.altKey){
  2536. showDebugDOM();
  2537. e.preventDefault();
  2538. }
  2539.  
  2540. // Hot key [Alt+R] to open the settings dialog
  2541. if (e.keyCode == '82' && e.altKey){
  2542. reloadScript();
  2543. e.preventDefault();
  2544. }
  2545. });
  2546.  
  2547. $('body').on('change', '.IG_SN_DIG input',function(e){
  2548. var name = $(this).attr('id');
  2549.  
  2550. if(name && USER_SETTING[name] !== undefined){
  2551. let isChecked = $(this).prop('checked');
  2552. GM_setValue(name, isChecked);
  2553. USER_SETTING[name] = isChecked;
  2554.  
  2555. console.log('user settings', name, isChecked);
  2556. }
  2557. });
  2558.  
  2559. $('body').on('click', '.IG_SN_DIG .globalSettings',function(e){
  2560. if($(this).find('#tempWrapper').length > 0){
  2561. e.preventDefault();
  2562. }
  2563. });
  2564.  
  2565. $('body').on('change', '.IG_SN_DIG #tempWrapper input:not(#date_format)',function(){
  2566. let value = $(this).val();
  2567.  
  2568. if($(this).attr('type') == 'range'){
  2569. $(this).next().val(value);
  2570. }
  2571. else{
  2572. $(this).prev().val(value);
  2573. }
  2574.  
  2575. if(value >= 0 && value <= 1){
  2576. VIDEO_VOLUME = value;
  2577. GM_setValue('G_VIDEO_VOLUME', value);
  2578. }
  2579. });
  2580.  
  2581. $('body').on('input', '.IG_SN_DIG #tempWrapper input:not(#date_format)',function(e){
  2582. if($(this).attr('type') == 'range'){
  2583. let value = $(this).val();
  2584. $(this).next().val(value);
  2585. }
  2586. else{
  2587. let value = $(this).val();
  2588. if(value >= 0 && value <= 1){
  2589. $(this).prev().val(value);
  2590. }
  2591. else{
  2592. if(value < 0){
  2593. $(this).val(0);
  2594. }
  2595. else{
  2596. $(this).val(1);
  2597. }
  2598. }
  2599. }
  2600. });
  2601.  
  2602. $('body').on('input', '.IG_SN_DIG #tempWrapper input#date_format',function(e){
  2603. GM_setValue('G_RENAME_FORMAT', $(this).val());
  2604. RENAME_FORMAT = $(this).val();
  2605. });
  2606.  
  2607. $('body').on('click','a[data-needed="direct"]', function(e){
  2608. e.preventDefault();
  2609. triggerLinkElement(this);
  2610. });
  2611.  
  2612. $('body').on('click','.IG_SN_DIG_BODY .newTab', function(){
  2613. // replace https://instagram.ftpe8-2.fna.fbcdn.net/ to https://scontent.cdninstagram.com/ becase of same origin policy (some video)
  2614.  
  2615. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && USER_SETTING.NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST){
  2616. triggerLinkElement( $(this).parent().children('a').first()[0], true);
  2617. }
  2618. else{
  2619. var urlObj = new URL($(this).parent().children('a').attr('data-href'));
  2620. urlObj.host = 'scontent.cdninstagram.com';
  2621.  
  2622. openNewTab(urlObj.href);
  2623. }
  2624. });
  2625.  
  2626. $('body').on('click','.IG_SN_DIG_BODY .videoThumbnail', function(){
  2627. saveFiles($(this).parent().children('a').find('img').first().attr('src'), $(this).parent().children('a').attr('data-username'), 'thumbnail', new Date().getTime(), 'jpg', $('#article-id').text());
  2628. });
  2629.  
  2630. // Running if user left-click download icon in stories
  2631. $('body').on('click','.IG_DWSTORY',function(){
  2632. onStory(true);
  2633. });
  2634.  
  2635. // Running if user left-click 'open in new tab' icon in stories
  2636. $('body').on('click','.IG_DWNEWTAB',function(e){
  2637. e.preventDefault();
  2638. onStory(true, true, true);
  2639. });
  2640.  
  2641. // Running if user left-click download thumbnail icon in stories
  2642. $('body').on('click','.IG_DWSTORY_THUMBNAIL',function(){
  2643. onStoryThumbnail(true);
  2644. });
  2645.  
  2646. // Running if user left-click download icon in profile
  2647. $('body').on('click','.IG_DWPROFILE',function(e){
  2648. e.stopPropagation();
  2649. onProfileAvatar(true);
  2650. });
  2651.  
  2652. // Running if user left-click download icon in highlight stories
  2653. $('body').on('click','.IG_DWHISTORY',function(){
  2654. onHighlightsStory(true);
  2655. });
  2656.  
  2657. // Running if user left-click 'open in new tab' icon in highlight stories
  2658. $('body').on('click','.IG_DWHINEWTAB',function(e){
  2659. e.preventDefault();
  2660. onHighlightsStory(true, true);
  2661. });
  2662.  
  2663. // Running if user left-click thumbnail download icon in highlight stories
  2664. $('body').on('click','.IG_DWHISTORY_THUMBNAIL',function(){
  2665. onHighlightsStoryThumbnail(true);
  2666. });
  2667.  
  2668. // Running if user left-click download icon in reels
  2669. $('body').on('click','.IG_REELS',function(){
  2670. onReels(true,true);
  2671. });
  2672.  
  2673. // Running if user left-click newtab icon in reels
  2674. $('body').on('click','.IG_REELS_NEWTAB',function(){
  2675. onReels(true,true,true);
  2676. });
  2677.  
  2678. // Running if user left-click download icon in reels
  2679. $('body').on('click','.IG_REELS_THUMBNAIL',function(){
  2680. onReels(true,false);
  2681. });
  2682.  
  2683. // Running if user right-click profile picture in stories area
  2684. $('body').on('mousedown','button[role="menuitem"]',function(e){
  2685. // Right-Click || Middle-Click
  2686. if(e.which === 3 || e.which === 2){
  2687. if(location.href === 'https://www.instagram.com/' && USER_SETTING.REDIRECT_CLICK_USER_STORY_PICTURE){
  2688. e.preventDefault();
  2689. if($(this).find('canvas._aarh').length > 0){
  2690. const targetUrl = 'https://www.instagram.com/'+$(this).children('div').last().text();
  2691. if(e.which === 2){
  2692. GM_openInTab(targetUrl);
  2693. }
  2694. else{
  2695. location.href = targetUrl;
  2696. }
  2697. }
  2698. }
  2699. }
  2700. });
  2701.  
  2702. $('body').on('change', '.IG_SN_DIG_TITLE .checkbox', function(){
  2703. var isChecked = $(this).find('input').prop('checked');
  2704. $('.IG_SN_DIG_BODY .inner_box').each(function(){
  2705. $(this).prop('checked', isChecked);
  2706. });
  2707. });
  2708.  
  2709. $('body').on('change', '.IG_SN_DIG_BODY .inner_box', function(){
  2710. var checked = $('.IG_SN_DIG_BODY .inner_box:checked').length;
  2711. var total = $('.IG_SN_DIG_BODY .inner_box').length;
  2712.  
  2713.  
  2714. $('.IG_SN_DIG_TITLE .checkbox').find('input').prop('checked', checked == total);
  2715. });
  2716.  
  2717. $('body').on('click', '.IG_SN_DIG_TITLE #batch_download_selected', function(){
  2718. let index = 0;
  2719. $('.IG_SN_DIG_BODY a[data-needed="direct"]').each(function(){
  2720. if($(this).prev().children('input').prop('checked')){
  2721. $(this).click();
  2722. index++;
  2723. }
  2724. });
  2725.  
  2726. if(index == 0){
  2727. alert(_i18n('NO_CHECK_RESOURCE'));
  2728. }
  2729. });
  2730.  
  2731. $('body').on('change', '.IG_SN_DIG_TITLE #langSelect', function(){
  2732. GM_setValue('lang', $(this).val());
  2733. lang = $(this).val();
  2734.  
  2735. showSetting();
  2736. });
  2737.  
  2738. $('body').on('change', '.IG_SN_DIG_BODY #locateSelect', function(){
  2739. $('#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('/','-')}`);
  2740. LOCATE_DATE_FORMAT = $(this).val();
  2741. GM_setValue('G_LOCATE_DATE_FORMAT', $(this).val());
  2742. });
  2743.  
  2744. $('body').on('click', '.IG_SN_DIG_TITLE #batch_download_direct', function(){
  2745. $('.IG_SN_DIG_BODY a[data-needed="direct"]').each(function(){
  2746. $(this).click();
  2747. });
  2748. });
  2749. });
  2750. })(jQuery);