IG小助手

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

目前为 2024-04-05 提交的版本。查看 最新版本

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