IG小助手

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

当前为 2024-03-14 提交的版本,查看 最新版本

  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.7.1
  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.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').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').parent().append(`<div title="${_i18n("DW")}" class="IG_DWPROFILE">${SVG.DOWNLOAD}</div>`);
  259. $('body > div main canvas._aarh, body > div main div._aadm').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. $('section > main[role="main"] > div').children('div').each(function(){
  980. if($(this).children().length > 0){
  981. if(!$(this).children().find('.IG_REELS').length){
  982. $(this).children().css('position','relative');
  983.  
  984. $(this).children().append(`<div title="${_i18n("DW")}" class="IG_REELS">${SVG.DOWNLOAD}</div>`);
  985. $(this).children().append(`<div title="${_i18n("NEW_TAB")}" class="IG_REELSNEWTAB">${SVG.NEW_TAB}</div>`);
  986. $(this).children().append(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="IG_REELS_THUMBNAIL">${SVG.THUMBNAIL}</div>`);
  987.  
  988. // Disable video autoplay
  989. if(USER_SETTING.DISABLE_VIDEO_LOOPING){
  990. $(this).find('video').each(function(){
  991. if(!$(this).data('loop')){
  992. console.log('(reel) Added video event listener #loop');
  993. $(this).on('ended',function(){
  994. $(this).attr('data-loop', true);
  995. let $element = $(this).next().find('div[role="presentation"] > div > div:last-child');
  996.  
  997. if($element.length > 0){
  998. $element.click();
  999. console.log('paused click()');
  1000. }
  1001. else{
  1002. $(this).parent().find('.xpgaw4o').removeAttr('style');
  1003. this.pause();
  1004. console.log('paused pause()');
  1005. }
  1006. });
  1007. }
  1008. });
  1009. }
  1010. // Modify Video Volume
  1011. if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  1012. $(this).find('video').each(function(){
  1013. if(!$(this).data('modify')){
  1014. console.log('(reel) Added video event listener #modify');
  1015. this.volume = VIDEO_VOLUME;
  1016.  
  1017. $(this).on('play',function(){
  1018. this.volume = VIDEO_VOLUME;
  1019. });
  1020. $(this).on('playing',function(){
  1021. this.volume = VIDEO_VOLUME;
  1022. });
  1023.  
  1024. $(this).attr('data-modify', true);
  1025. }
  1026. });
  1027. }
  1028. }
  1029. }
  1030. });
  1031. }
  1032. },250);
  1033. }
  1034. }
  1035.  
  1036. /**
  1037. * getHighlightStories
  1038. * Get a list of all stories in highlight Id.
  1039. *
  1040. * @param {Integer} highlightId
  1041. * @return {Object}
  1042. */
  1043. function getHighlightStories(highlightId){
  1044. return new Promise((resolve,reject)=>{
  1045. 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`;
  1046.  
  1047. GM_xmlhttpRequest({
  1048. method: "GET",
  1049. url: getURL,
  1050. onload: function(response) {
  1051. let obj = JSON.parse(response.response);
  1052. resolve(obj);
  1053. },
  1054. onerror: function(err){
  1055. reject(err);
  1056. }
  1057. });
  1058. });
  1059. }
  1060.  
  1061. /**
  1062. * getStories
  1063. * Get a list of all stories in user Id.
  1064. *
  1065. * @param {Integer} userId
  1066. * @return {Object}
  1067. */
  1068. function getStories(userId){
  1069. return new Promise((resolve,reject)=>{
  1070. 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`;
  1071.  
  1072. GM_xmlhttpRequest({
  1073. method: "GET",
  1074. url: getURL,
  1075. onload: function(response) {
  1076. let obj = JSON.parse(response.response);
  1077. resolve(obj);
  1078. },
  1079. onerror: function(err){
  1080. reject(err);
  1081. }
  1082. });
  1083. });
  1084. }
  1085.  
  1086. /**
  1087. * getUserId
  1088. * Get user's id with username
  1089. *
  1090. * @param {String} username
  1091. * @return {Integer}
  1092. */
  1093. function getUserId(username){
  1094. return new Promise((resolve,reject)=>{
  1095. let getURL = `https://www.instagram.com/web/search/topsearch/?query=${username}`;
  1096.  
  1097. GM_xmlhttpRequest({
  1098. method: "GET",
  1099. url: getURL,
  1100. onload: function(response) {
  1101. // Fix search issue by Discord: sno_w_
  1102. let obj = JSON.parse(response.response);
  1103. let result = null;
  1104. obj.users.forEach(pos => {
  1105. if(pos.user.username === username){
  1106. result = pos;
  1107. }
  1108. });
  1109.  
  1110. if(result != null){
  1111. resolve(result);
  1112. }
  1113. else{
  1114. alert("Can not find user info from getUserId()");
  1115. }
  1116. },
  1117. onerror: function(err){
  1118. reject(err);
  1119. }
  1120. });
  1121. });
  1122. }
  1123.  
  1124. /**
  1125. * getUserHighSizeProfile
  1126. * Get user's high quality avatar image.
  1127. *
  1128. * @param {Integer} userId
  1129. * @return {String}
  1130. */
  1131. function getUserHighSizeProfile(userId){
  1132. return new Promise((resolve,reject)=>{
  1133. let getURL = `https://i.instagram.com/api/v1/users/${userId}/info/`;
  1134.  
  1135. GM_xmlhttpRequest({
  1136. method: "GET",
  1137. url: getURL,
  1138. headers: {
  1139. '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'
  1140. },
  1141. onload: function(response) {
  1142. let obj = JSON.parse(response.response);
  1143. if(obj.status !== 'ok'){
  1144. reject('faild');
  1145. }
  1146. else{
  1147. resolve(obj.user.hd_profile_pic_url_info?.url);
  1148. }
  1149. },
  1150. onerror: function(err){
  1151. reject(err);
  1152. }
  1153. });
  1154. });
  1155. }
  1156.  
  1157. /**
  1158. * getPostOwner
  1159. * Get post's author with post shortcode
  1160. *
  1161. * @param {String} postPath
  1162. * @return {String}
  1163. */
  1164. function getPostOwner(postPath){
  1165. return new Promise((resolve,reject)=>{
  1166. if(!postPath) reject("NOPATH");
  1167. let postShortCode = postPath;
  1168. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  1169.  
  1170. GM_xmlhttpRequest({
  1171. method: "GET",
  1172. url: getURL,
  1173. onload: function(response) {
  1174. let obj = JSON.parse(response.response);
  1175. resolve(obj.data.shortcode_media.owner.username);
  1176. },
  1177. onerror: function(err){
  1178. reject(err);
  1179. }
  1180. });
  1181. });
  1182. }
  1183.  
  1184. /**
  1185. * getBlobMedia
  1186. * Get list of all media files in post with post shortcode
  1187. *
  1188. * @param {String} postPath
  1189. * @return {Object}
  1190. */
  1191. function getBlobMedia(postPath){
  1192. return new Promise((resolve,reject)=>{
  1193. if(!postPath) reject("NOPATH");
  1194. let postShortCode = postPath;
  1195. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  1196.  
  1197. GM_xmlhttpRequest({
  1198. method: "GET",
  1199. url: getURL,
  1200. onload: function(response) {
  1201. let obj = JSON.parse(response.response);
  1202. console.log(obj);
  1203. resolve(obj.data);
  1204. },
  1205. onerror: function(err){
  1206. reject(err);
  1207. }
  1208. });
  1209. });
  1210. }
  1211.  
  1212. /**
  1213. * onReadyMyDW
  1214. * Create an event entry point for the download button for the post
  1215. *
  1216. * @param {Boolean} NoDialog - Check if it not showing the dialog
  1217. * @return {void}
  1218. */
  1219. function onReadyMyDW(NoDialog){
  1220. // Whether is Instagram dialog?
  1221. if(NoDialog == false){
  1222. const maxCall = 100;
  1223. let i = 0;
  1224. var repeat = setInterval(() => {
  1225. // div.xdt5ytf << (sigle post in top, not floating) >>
  1226. 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){
  1227. clearInterval(repeat);
  1228.  
  1229. if(i > maxCall){
  1230. //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.');
  1231. console.warn('onReadyMyDW() Timer', 'maximum number of repetitions reached, terminated');
  1232. }
  1233. }
  1234.  
  1235. console.log('onReadyMyDW() Timer', 'repeating to call detection createDownloadButton()');
  1236. createDownloadButton();
  1237. i++;
  1238. },50);
  1239. }
  1240. else{
  1241. createDownloadButton();
  1242. }
  1243. }
  1244.  
  1245. /**
  1246. * getAppID
  1247. * Get Instagram App ID
  1248. *
  1249. * @return {?integer}
  1250. */
  1251. function getAppID(){
  1252. let result = null;
  1253. $('script[type="application/json"]').each(function(){
  1254. const regexp = /"APP_ID":"([0-9]+)"/ig;
  1255. const matcher = $(this).text().match(regexp);
  1256. if(matcher != null && result == null){
  1257. result = [...$(this).text().matchAll(regexp)];
  1258. }
  1259. })
  1260.  
  1261. return (result)?result.at(0).at(-1):null;
  1262. }
  1263.  
  1264. /**
  1265. * updateLoadingBar
  1266. * Update loading state
  1267. *
  1268. * @param {Boolean} isLoading - Check if loading state
  1269. * @return {void}
  1270. */
  1271. function updateLoadingBar(isLoading){
  1272. if(isLoading){
  1273. $('div[id^="mount"] > div > div > div:first').removeClass('x1s85apg');
  1274. $('div[id^="mount"] > div > div > div:first').css('z-index','20000');
  1275. }
  1276. else{
  1277. $('div[id^="mount"] > div > div > div:first').addClass('x1s85apg');
  1278. $('div[id^="mount"] > div > div > div:first').css('z-index','');
  1279. }
  1280. }
  1281.  
  1282. /**
  1283. * getMediaInfo
  1284. * Get Instagram Media object
  1285. *
  1286. * @param {String} mediaId
  1287. * @return {Object}
  1288. */
  1289. function getMediaInfo(mediaId){
  1290. return new Promise((resolve,reject)=>{
  1291. let getURL = `https://i.instagram.com/api/v1/media/${mediaId}/info/`;
  1292.  
  1293. if(mediaId == null){
  1294. alert("Can not call Media API because of the media id is invalid.");
  1295.  
  1296. updateLoadingBar(false);
  1297. reject(-1);
  1298. return;
  1299. }
  1300. if(getAppID() == null){
  1301. alert("Can not call Media API because of the app id is invalid.");
  1302.  
  1303. updateLoadingBar(false);
  1304. reject(-1);
  1305. return;
  1306. }
  1307.  
  1308. GM_xmlhttpRequest({
  1309. method: "GET",
  1310. url: getURL,
  1311. headers: {
  1312. "User-Agent": window.navigator.userAgent,
  1313. "Accept": "*/*",
  1314. 'X-IG-App-ID': getAppID()
  1315. },
  1316. onload: function(response) {
  1317. let obj = JSON.parse(response.response);
  1318. resolve(obj);
  1319. },
  1320. onerror: function(err){
  1321. resolve(err);
  1322. }
  1323. });
  1324. });
  1325. }
  1326.  
  1327. /**
  1328. * getVisibleNodeIndex
  1329. * Get element visible node
  1330. *
  1331. * @param {Object} $main
  1332. * @return {Integer}
  1333. */
  1334. function getVisibleNodeIndex($main){
  1335. var index = 0;
  1336. // homepage classList
  1337. var $dot = $main.find('.x1iyjqo2 > div > div:last-child > div');
  1338.  
  1339. // dialog classList, main top classList
  1340. if($dot == null || !$dot.hasClass('_acnb')){
  1341. $dot = $main.find('._aatk > div > div:last-child').eq(0).children('div');
  1342. }
  1343.  
  1344. $dot.filter('._acnb').each(function(sIndex){
  1345. if($(this).hasClass('_acnf')){
  1346. index = sIndex;
  1347. }
  1348. });
  1349.  
  1350. return index;
  1351. }
  1352.  
  1353. /**
  1354. * createDownloadButton
  1355. * Create a download button in the upper right corner of each post
  1356. *
  1357. * @return {void}
  1358. */
  1359. function createDownloadButton(){
  1360. // Add download icon per each posts
  1361. $('article, section:visible > main > div > div.xdt5ytf, div._aap0[role="presentation"]').each(function(index){
  1362. // If it is have not download icon
  1363. // class x1iyjqo2 mean user profile pages post list container
  1364. if(!$(this).attr('data-snig') && !$(this).hasClass('x1iyjqo2') && !$(this).children('article')?.hasClass('x1iyjqo2')){
  1365. console.log("Found post container", $(this));
  1366.  
  1367. var rightPos = 15;
  1368. var topPos = 15;
  1369. var $mainElement = $(this);
  1370. var tagName = this.tagName;
  1371.  
  1372. // not loop each in single top post
  1373. if(tagName === "DIV" && index != 0){
  1374. return;
  1375. }
  1376.  
  1377. // New post UI by Discord: ken
  1378. // NOT WORKING
  1379. /*
  1380. if(tagName === "DIV" && $(this).attr('role') === "presentation"){
  1381. rightPos = 28;
  1382. topPos = 75;
  1383. $mainElement = $('div._aap0[role="presentation"]').parents('div._aamm').parent().parent().parent().parent().parent();
  1384. }
  1385. */
  1386.  
  1387. const $childElement = $mainElement.children("div").children("div");
  1388.  
  1389. if($childElement.length === 0) return;
  1390.  
  1391. console.log("Found insert point", $childElement);
  1392.  
  1393. // Has counter?!
  1394. if($mainElement.find('._aao_ + div.x6s0dn4').length > 0){
  1395. $mainElement.find('._aao_ + div.x6s0dn4').css('top', '35px');
  1396.  
  1397. const observeNode = $mainElement.find('._aao_ + div.x6s0dn4').first().parent()[0];
  1398. var observer = new MutationObserver(function (mutation, owner) {
  1399. $mainElement.find('._aao_ + div.x6s0dn4').css('top', '35px');
  1400. });
  1401.  
  1402. observer.observe(observeNode, {
  1403. childList: true
  1404. });
  1405. }
  1406.  
  1407. // Add icons
  1408. const DownloadElement = `<div title="${_i18n("DW")}" class="SNKMS_IG_DW_MAIN" style="right:${rightPos}px;top:${topPos}px;">${SVG.DOWNLOAD}</div>`;
  1409. const NewTabElement = `<div title="${_i18n("NEW_TAB")}" class="SNKMS_IG_NEWTAB_MAIN" style="right:${rightPos + 35}px;top:${topPos}px;">${SVG.NEW_TAB}</div>`;
  1410. const ThumbnailElement = `<div title="${_i18n("THUMBNAIL_INTRO")}" class="SNKMS_IG_THUMBNAIL_MAIN" style="right:${rightPos + 70}px;top:${topPos}px;">${SVG.THUMBNAIL}</div>`;
  1411.  
  1412. $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).append(DownloadElement);
  1413. $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).append(NewTabElement);
  1414.  
  1415. setTimeout(()=>{
  1416. // Check if visible post is video
  1417. if($childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).find('div > ul li._acaz').length === 0){
  1418. if($childElement.find('video').length > 0){
  1419. $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).append(ThumbnailElement);
  1420. }
  1421. }
  1422. else{
  1423. const checkVideoNode = function(target){
  1424. if(target){
  1425. var k = $(target).find('li._acaz').length;
  1426. var $targetNode = null;
  1427.  
  1428. if(k == 2){
  1429. var index = getVisibleNodeIndex($mainElement);
  1430. // First node
  1431. if(index === 0){
  1432. $targetNode = $(target).find('li._acaz').first();
  1433. }
  1434. // Last node
  1435. else{
  1436. $targetNode = $(target).find('li._acaz').last();
  1437. }
  1438. }
  1439. // Middle node
  1440. else{
  1441. $targetNode = $(target).find('li._acaz').eq(1);
  1442. }
  1443.  
  1444. // Check if video?
  1445. if($targetNode != null && $targetNode.length > 0 && $targetNode.find('video').length > 0){
  1446. $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).append(ThumbnailElement);
  1447. }
  1448. else{
  1449. $childElement.find('.SNKMS_IG_THUMBNAIL_MAIN')?.remove();
  1450. }
  1451. }
  1452. };
  1453.  
  1454. var observer = new MutationObserver(function (mutation, owner) {
  1455. var target = mutation.at(0)?.target;
  1456. checkVideoNode(target);
  1457. });
  1458.  
  1459. const element = $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).find('div > ul li._acaz')?.parent()[0];
  1460. const elementAttr = $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).find('div > ul li._acaz')?.parent().parent()[0];
  1461.  
  1462. if(element){
  1463. checkVideoNode(element);
  1464. observer.observe(element, {
  1465. childList: true
  1466. });
  1467. }
  1468.  
  1469. if(elementAttr){
  1470. observer.observe(elementAttr, {
  1471. attributes: true
  1472. });
  1473. }
  1474. }
  1475. }, 50);
  1476.  
  1477.  
  1478. $childElement.css('position','relative');
  1479.  
  1480. // Disable video autoplay
  1481. if(USER_SETTING.DISABLE_VIDEO_LOOPING){
  1482. $(this).find('video').each(function(){
  1483. if(!$(this).data('loop')){
  1484. console.log('(post) Added video event listener #loop');
  1485. $(this).on('ended',function(){
  1486. $(this).attr('data-loop', true);
  1487. this.pause();
  1488. });
  1489. }
  1490. });
  1491. }
  1492.  
  1493. // Modify Video Volume
  1494. if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  1495. $(this).find('video').each(function(){
  1496. if(!$(this).data('modify')){
  1497. console.log('(post) Added video event listener #modify');
  1498. this.volume = VIDEO_VOLUME;
  1499.  
  1500. $(this).on('play',function(){
  1501. this.volume = VIDEO_VOLUME;
  1502. });
  1503. $(this).on('playing',function(){
  1504. this.volume = VIDEO_VOLUME;
  1505. });
  1506.  
  1507. $(this).attr('data-modify', true);
  1508. }
  1509. });
  1510. }
  1511.  
  1512. $(this).on('click', '.SNKMS_IG_THUMBNAIL_MAIN', function(e){
  1513. updateLoadingBar(true);
  1514.  
  1515. GL_username = $(this).parent().parent().parent().attr('data-username');
  1516. 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);
  1517.  
  1518. var $main = $(this).parent().parent().parent();
  1519. var index = getVisibleNodeIndex($main);
  1520.  
  1521. IG_createDM(true, false);
  1522.  
  1523. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", "").then(()=>{
  1524. let checkBlob = setInterval(()=>{
  1525. if($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0){
  1526. clearInterval(checkBlob);
  1527. var $videoThumbnail = $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="'+(index+1)+'"]')?.parent().find('.videoThumbnail')?.first();
  1528.  
  1529. if($videoThumbnail != null && $videoThumbnail.length > 0){
  1530. $videoThumbnail.click();
  1531. }
  1532. else{
  1533. alert('Can not find thumbnail url.');
  1534. }
  1535.  
  1536. updateLoadingBar(false);
  1537. $('.IG_SN_DIG').remove();
  1538. }
  1539. },250);
  1540. });
  1541. });
  1542.  
  1543. $(this).on('click', '.SNKMS_IG_NEWTAB_MAIN', function(e){
  1544. updateLoadingBar(true);
  1545.  
  1546. GL_username = $(this).parent().parent().parent().attr('data-username');
  1547. 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);
  1548.  
  1549. var $main = $(this).parent().parent().parent();
  1550. var index = getVisibleNodeIndex($main);
  1551.  
  1552. IG_createDM(true, false);
  1553.  
  1554. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", "").then(()=>{
  1555. let checkBlob = setInterval(()=>{
  1556. if($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0){
  1557. clearInterval(checkBlob);
  1558. var $linkElement = $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="'+(index+1)+'"]');
  1559.  
  1560. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && USER_SETTING.NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST){
  1561. triggerLinkElement( $linkElement.first()[0], true);
  1562. }
  1563. else{
  1564. let href = $linkElement?.attr('data-href');
  1565. if(href){
  1566. // replace https://instagram.ftpe8-2.fna.fbcdn.net/ to https://scontent.cdninstagram.com/ becase of same origin policy (some video)
  1567. var urlObj = new URL(href);
  1568. urlObj.host = 'scontent.cdninstagram.com';
  1569.  
  1570. openNewTab(urlObj.href);
  1571. }
  1572. else{
  1573. alert('Can not find open tab url.');
  1574. }
  1575. }
  1576.  
  1577. updateLoadingBar(false);
  1578. $('.IG_SN_DIG').remove();
  1579. }
  1580. },250);
  1581. });
  1582. });
  1583.  
  1584. // Running if user click the download icon
  1585. $(this).on('click','.SNKMS_IG_DW_MAIN', async function(e){
  1586. GL_username = $(this).parent().parent().parent().attr('data-username');
  1587. 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);
  1588.  
  1589. // Create element that download dailog
  1590. IG_createDM(USER_SETTING.DIRECT_DOWNLOAD_ALL, true);
  1591.  
  1592. $("#article-id").html(`<a href="https://www.instagram.com/p/${GL_postPath}">${GL_postPath}</a>`);
  1593.  
  1594. if(USER_SETTING.DIRECT_DOWNLOAD_VISABLE_RESOURCE){
  1595. updateLoadingBar(true);
  1596. IG_setDM(true);
  1597.  
  1598. var index = getVisibleNodeIndex($(this).parent().parent().parent());
  1599.  
  1600. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", "").then(()=>{
  1601. let checkBlob = setInterval(()=>{
  1602. if($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0){
  1603. clearInterval(checkBlob);
  1604. var href = $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="'+(index+1)+'"]')?.attr('data-href');
  1605.  
  1606. if(href){
  1607. updateLoadingBar(false);
  1608. $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="'+(index+1)+'"]')?.click();
  1609. }
  1610. else{
  1611. alert('Can not find download url.');
  1612. }
  1613.  
  1614. $('.IG_SN_DIG').remove();
  1615. }
  1616. },250);
  1617. });
  1618.  
  1619. return;
  1620. }
  1621.  
  1622. if(!USER_SETTING.DIRECT_DOWNLOAD_ALL){
  1623. // Find video/image element and add the download icon
  1624. var s = 0;
  1625. var multiple = $(this).parent().parent().find('._aap0 ._acaz').length;
  1626. var pathname = window.location.pathname;
  1627. var fullpathname = "/"+pathname.split('/')[1]+"/"+pathname.split('/')[2]+"/";
  1628. var blob = USER_SETTING.FORCE_FETCH_ALL_RESOURCES;
  1629. var publish_time = new Date($(this).parent().parent().find('a[href^="/p/"] time[datetime]').first().attr('datetime')).getTime();
  1630.  
  1631. // If posts have more than one images or videos.
  1632. if(multiple){
  1633. $(this).parent().find('._aap0 ._acaz').each(function(){
  1634. let element_videos = $(this).parent().parent().find('video');
  1635. //if(element_videos && element_videos.attr('src') && element_videos.attr('src').match(/^blob:/ig)){
  1636. if(element_videos && element_videos.attr('src')){
  1637. blob = true;
  1638. }
  1639. });
  1640.  
  1641.  
  1642. if(blob || USER_SETTING.FORCE_RESOURCE_VIA_MEDIA){
  1643. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_MULTIPLE"));
  1644. }
  1645. else{
  1646. $(this).parent().find('._aap0 ._acaz').each(function(){
  1647. s++;
  1648. let element_videos = $(this).find('video');
  1649. let element_images = $(this).find('._aagv img');
  1650. let imgLink = (element_images.attr('srcset'))?element_images.attr('srcset').split(" ")[0]:element_images.attr('src');
  1651.  
  1652. if(element_videos && element_videos.attr('src')){
  1653. blob = true;
  1654. }
  1655. if(element_images && imgLink){
  1656. $('.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>`);
  1657. }
  1658.  
  1659. });
  1660.  
  1661. if(blob){
  1662. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_RELOAD"));
  1663. }
  1664. }
  1665. }
  1666. else{
  1667. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA){
  1668. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_MULTIPLE"));
  1669. }
  1670. else{
  1671. s++;
  1672. let element_videos = $(this).parent().parent().find('video');
  1673. let element_images = $(this).parent().parent().find('._aagv img');
  1674. let imgLink = (element_images.attr('srcset'))?element_images.attr('srcset').split(" ")[0]:element_images.attr('src');
  1675.  
  1676.  
  1677. if(element_videos && element_videos.attr('src')){
  1678. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_ONE"));
  1679. }
  1680. if(element_images && imgLink){
  1681. $('.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>`);
  1682. }
  1683. }
  1684. }
  1685. }
  1686.  
  1687. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function(){
  1688. $(this).wrap('<div></div>');
  1689. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  1690. $(this).after(`<div title="${_i18n("NEW_TAB")}" class="newTab">${SVG.NEW_TAB}</div>`);
  1691.  
  1692. if($(this).attr('data-name') == 'video'){
  1693. $(this).after(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="videoThumbnail">${SVG.THUMBNAIL}</div>`);
  1694. }
  1695. });
  1696.  
  1697. if(USER_SETTING.DIRECT_DOWNLOAD_ALL){
  1698. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_MULTIPLE")).then(()=>{
  1699. let checkBlob = setInterval(()=>{
  1700. if($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0){
  1701. clearInterval(checkBlob);
  1702. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function(){
  1703. $(this).click();
  1704. });
  1705.  
  1706. $('.IG_SN_DIG').remove();
  1707. }
  1708. },250);
  1709. });
  1710. }
  1711. });
  1712.  
  1713. // Add the mark that download is ready
  1714. var username = $(this).find("header > div:last-child > div:first-child span a").first().text();
  1715.  
  1716. $(this).attr('data-snig','canDownload');
  1717. $(this).attr('data-username',username);
  1718. }
  1719. });
  1720. }
  1721.  
  1722. /**
  1723. * createMediaListDOM
  1724. * Create a list of media elements from post URLs
  1725. *
  1726. * @param {String} postURL
  1727. * @param {String} selector - Use CSS element selectors to choose where it appears.
  1728. * @param {String} message - i18n display loading message
  1729. * @return {void}
  1730. */
  1731. function createMediaListDOM(postURL,selector,message){
  1732. return new Promise(async (resolve) => {
  1733. $(`${selector} a`).remove();
  1734. $(selector).append('<p id="_SNLOAD">'+ message +'</p>');
  1735. let media = await getBlobMedia(postURL);
  1736.  
  1737. let idx = 1;
  1738. let resource = media.shortcode_media;
  1739.  
  1740. // GraphVideo
  1741. if(resource.__typename == "GraphVideo" && resource.video_url){
  1742. $(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>`);
  1743. idx++;
  1744. }
  1745. // GraphImage
  1746. if(resource.__typename == "GraphImage"){
  1747. $(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>`);
  1748. idx++;
  1749. }
  1750. // GraphSidecar
  1751. if(resource.__typename == "GraphSidecar" && resource.edge_sidecar_to_children){
  1752. for(let e of resource.edge_sidecar_to_children.edges){
  1753. if(e.node.__typename == "GraphVideo"){
  1754. $(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>`);
  1755. }
  1756.  
  1757. if(e.node.__typename == "GraphImage"){
  1758. $(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>`);
  1759. }
  1760. idx++;
  1761. }
  1762. }
  1763.  
  1764. $("#_SNLOAD").remove();
  1765. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function(){
  1766. $(this).wrap('<div></div>');
  1767. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  1768. $(this).after(`<div title="${_i18n("NEW_TAB")}" class="newTab">${SVG.NEW_TAB}</div>`);
  1769.  
  1770. if($(this).attr('data-name') == 'video'){
  1771. $(this).after(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="videoThumbnail">${SVG.THUMBNAIL}</div>`);
  1772. }
  1773. });
  1774.  
  1775. resolve(true);
  1776. });
  1777. }
  1778.  
  1779. /**
  1780. * IG_createDM
  1781. * A dialog showing a list of all media files in the post
  1782. *
  1783. * @param {Boolean} hasHidden
  1784. * @param {Boolean} hasCheckbox
  1785. * @return {void}
  1786. */
  1787. function IG_createDM(hasHidden, hasCheckbox){
  1788. let isHidden = (hasHidden)?"hidden":"";
  1789. $('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>');
  1790. $('.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>`);
  1791.  
  1792. if(hasCheckbox){
  1793. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE').append(`<div style="text-align: center;" id="button_group"></div>`);
  1794. $('.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>`);
  1795. $('.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>`);
  1796. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE').append(`<label class="checkbox"><input value="yes" type="checkbox" />${_i18n('ALL_CHECK')}</label>`);
  1797. }
  1798. }
  1799.  
  1800. /**
  1801. * IG_setDM
  1802. * Set a dialog status
  1803. *
  1804. * @param {Boolean} hasHidden
  1805. * @return {void}
  1806. */
  1807. function IG_setDM(hasHidden){
  1808. if($('.IG_SN_DIG').length){
  1809. if(hasHidden){
  1810. $('.IG_SN_DIG').addClass("hidden");
  1811. }
  1812. else{
  1813. $('.IG_SN_DIG').removeClass("hidden");
  1814. }
  1815. }
  1816. }
  1817.  
  1818. /**
  1819. * saveFiles
  1820. * Download the specified media URL to the computer
  1821. *
  1822. * @param {String} downloadLink
  1823. * @param {String} username
  1824. * @param {String} sourceType
  1825. * @param {Integer} timestamp
  1826. * @param {String} filetype
  1827. * @param {String} shortcode
  1828. * @return {void}
  1829. */
  1830. function saveFiles(downloadLink,username,sourceType,timestamp,filetype,shortcode){
  1831. setTimeout(()=>{
  1832. updateLoadingBar(true);
  1833. fetch(downloadLink).then(res => {
  1834. return res.blob().then(dwel => {
  1835. updateLoadingBar(false);
  1836. createSaveFileElement(downloadLink,dwel,username,sourceType,timestamp,filetype,shortcode);
  1837. });
  1838. });
  1839. }, 50);
  1840. }
  1841.  
  1842. /**
  1843. * createSaveFileElement
  1844. * Download the specified media with link element
  1845. *
  1846. * @param {String} downloadLink
  1847. * @param {Object} object
  1848. * @param {String} username
  1849. * @param {String} sourceType
  1850. * @param {Integer} timestamp
  1851. * @param {String} filetype
  1852. * @param {String} shortcode
  1853. * @return {void}
  1854. */
  1855. function createSaveFileElement(downloadLink,object,username,sourceType,timestamp,filetype,shortcode) {
  1856. timestamp = parseInt(timestamp.toString().padEnd(13, '0')) / 1000;
  1857.  
  1858. if(USER_SETTING.RENAME_PUBLISH_DATE){
  1859. timestamp = new Date(timestamp * 1000).toISOString();
  1860. }
  1861.  
  1862. if(USER_SETTING.RENAME_LOCATE_DATE){
  1863. timestamp = (new Date(timestamp).toLocaleString(LOCATE_DATE_FORMAT, {hour12: false})).replaceAll('/', '-');
  1864. }
  1865.  
  1866. const a = document.createElement("a");
  1867. const name = username+'-'+sourceType+'-'+((USER_SETTING.RENAME_SHORTCODE && shortcode)?shortcode+'-':'')+timestamp+'.'+filetype;
  1868. const originally = username + '_' + new URL(downloadLink).pathname.split('/').at(-1).split('.').slice(0,-1).join('.') + '.' + filetype;
  1869.  
  1870. a.href = URL.createObjectURL(object);
  1871. a.setAttribute("download", (USER_SETTING.AUTO_RENAME)?name:originally);
  1872. a.click();
  1873. a.remove();
  1874. }
  1875.  
  1876. /**
  1877. * triggerLinkElement
  1878. * Trigger the link element to start downloading the resource
  1879. *
  1880. * @param {Object} element
  1881. * @return {void}
  1882. */
  1883. async function triggerLinkElement(element, isPreview) {
  1884. let date = new Date().getTime();
  1885. let timestamp = Math.floor(date / 1000);
  1886. let username = ($(element).attr('data-username')) ? $(element).attr('data-username') : GL_username;
  1887.  
  1888. if(!username && $(element).attr('data-path')){
  1889. console.log('catching owner name from shortcode:',$(element).attr('data-href'));
  1890. username = await getPostOwner($(element).attr('data-path'));
  1891. }
  1892.  
  1893. if(USER_SETTING.RENAME_PUBLISH_DATE && $(element).attr('datetime')){
  1894. timestamp = parseInt($(element).attr('datetime'));
  1895. }
  1896.  
  1897. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA){
  1898. updateLoadingBar(true);
  1899. let result = await getMediaInfo($(element).attr('media-id'));
  1900. updateLoadingBar(false);
  1901.  
  1902. if(result.status === 'ok'){
  1903. var resource_url = null;
  1904. if(result.items[0].video_versions){
  1905. resource_url = result.items[0].video_versions[0].url;
  1906. }
  1907. else{
  1908. resource_url = result.items[0].image_versions2.candidates[0].url;
  1909. }
  1910.  
  1911. if(isPreview){
  1912. let urlObj = new URL(resource_url);
  1913. urlObj.host = 'scontent.cdninstagram.com';
  1914.  
  1915. openNewTab(urlObj.href);
  1916. }
  1917. else{
  1918. saveFiles(resource_url, username, $(element).attr('data-name'),timestamp, $(element).attr('data-type'), $(element).attr('data-path'));
  1919. }
  1920. }
  1921. else{
  1922. if(USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT){
  1923. if(isPreview){
  1924. let urlObj = new URL($(element).attr('data-href'));
  1925. urlObj.host = 'scontent.cdninstagram.com';
  1926.  
  1927. openNewTab(urlObj.href);
  1928. }
  1929. else{
  1930. saveFiles($(element).attr('data-href'),username,$(element).attr('data-name'),timestamp,$(element).attr('data-type'), $(element).attr('data-path'));
  1931. }
  1932. }
  1933. else{
  1934. alert('Fetch failed from Media API. API response message: ' + result.message);
  1935. }
  1936. console.log(result);
  1937. }
  1938. }
  1939. else{
  1940. saveFiles($(element).attr('data-href'),username,$(element).attr('data-name'),timestamp,$(element).attr('data-type'), $(element).attr('data-path'));
  1941. }
  1942. }
  1943.  
  1944. /**
  1945. * translateText
  1946. * i18n translation text
  1947. *
  1948. * @param {String} lang
  1949. * @return {void}
  1950. */
  1951. function translateText(lang){
  1952. var eLocale = {
  1953. "en-US": {
  1954. "SELECT_LANG": "English",
  1955. "RELOAD_SCRIPT": "Reload Script",
  1956. "DONATE": "Donate",
  1957. "FEEDBACK": "Feedback",
  1958. "NEW_TAB": "Open in new tab",
  1959. "SHOW_DOM_TREE": "Show DOM Tree",
  1960. "SELECT_AND_COPY": "Select All and Copy of the Input Box",
  1961. "DOWNLOAD_DOM_TREE": "Download DOM Tree as Text File",
  1962. "REPORT_GITHUB": "Report Issue On GitHub",
  1963. "REPORT_DISCORD": "Report Issue On Discord Support Server",
  1964. "DEBUG": "Debug Window",
  1965. "CLOSE": "Close",
  1966. "ALL_CHECK": "Select All",
  1967. "BATCH_DOWNLOAD_SELECTED": "Download Selected Resources",
  1968. "BATCH_DOWNLOAD_DIRECT": "Download All Resources",
  1969. "IMG": "Image",
  1970. "VID": "Video",
  1971. "DW": "Download",
  1972. "THUMBNAIL_INTRO": "Download video thumbnail",
  1973. "LOAD_BLOB_ONE": "Loading Blob Media...",
  1974. "LOAD_BLOB_MULTIPLE": "Loading Blob Media and others...",
  1975. "LOAD_BLOB_RELOAD": "Detect Blob Media, now reloading...",
  1976. "NO_CHECK_RESOURCE": "You need to check resource to download.",
  1977. "NO_VID_URL": "Can not find video url.",
  1978. "SETTING": "Settings",
  1979. "AUTO_RENAME": "Automatically Rename Files",
  1980. "RENAME_SHORTCODE": "Rename The File and Include Shortcode",
  1981. "RENAME_PUBLISH_DATE": "Set Rename File Timestamp to Resource Publish Date",
  1982. "RENAME_LOCATE_DATE": "Modify Renamed File Timestamp Date Format (Right-Click To Set)",
  1983. "DISABLE_VIDEO_LOOPING": "Disable Video Auto-looping",
  1984. "REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE": "Redirect When Right-Clicking User Story Picture",
  1985. "FORCE_FETCH_ALL_RESOURCES": "Forcing Fetch All Resources In the Post",
  1986. "DIRECT_DOWNLOAD_VISABLE_RESOURCE": "Directly Download the Visible Resources In the Post",
  1987. "DIRECT_DOWNLOAD_ALL": "Directly Download All Resources In the Post",
  1988. "MODIFY_VIDEO_VOLUME": "Modify Video Volume (Right-Click To Set)",
  1989. "SCROLL_BUTTON": "Enable Scroll Buttons For Reels Page",
  1990. "FORCE_RESOURCE_VIA_MEDIA": "Force Fetch Resource via Media API",
  1991. "USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT": "Use Other Methods to Download When the Media API is Not Accessible",
  1992. "NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST": '"Open in new tab" in posts always uses Media API',
  1993. "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",
  1994. "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.",
  1995. "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.",
  1996. "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.",
  1997. "DISABLE_VIDEO_LOOPING_INTRO": "Disable video auto-looping in reels and posts.",
  1998. "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.",
  1999. "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.",
  2000. "DIRECT_DOWNLOAD_VISABLE_RESOURCE_INTRO": "Directly download the current resources in the post.",
  2001. "DIRECT_DOWNLOAD_ALL_INTRO": "When you click the download button, all resources in the post will be directly forced to be fetched and downloaded.",
  2002. "MODIFY_VIDEO_VOLUME_INTRO": "Modify the video playback volume in Reels and Posts (right-click to open the volume setting slider).",
  2003. "SCROLL_BUTTON_INTRO": "Enable scroll buttons for the lower right corner of Reels page.",
  2004. "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.",
  2005. "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).",
  2006. "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."
  2007. }
  2008. };
  2009.  
  2010. var resultUnsorted = Object.assign({}, eLocale, locale);
  2011. var resultSorted = Object.keys(resultUnsorted).sort().reduce(
  2012. (obj, key) => {
  2013. obj[key] = resultUnsorted[key];
  2014. return obj;
  2015. }, {}
  2016. );
  2017.  
  2018. return resultSorted;
  2019. }
  2020.  
  2021. /**
  2022. * _i18n
  2023. * Perform i18n translation
  2024. *
  2025. * @param {String} text
  2026. * @return {void}
  2027. */
  2028. function _i18n(text){
  2029. const translate = translateText();
  2030.  
  2031. if(translate[lang] != undefined && translate[lang][text] != undefined){
  2032. return translate[lang][text];
  2033. }
  2034. else{
  2035. return translate["en-US"][text];
  2036. }
  2037. }
  2038.  
  2039. /**
  2040. * showSetting
  2041. * Show script settings window
  2042. *
  2043. * @return {void}
  2044. */
  2045. function showSetting(){
  2046. $('.IG_SN_DIG').remove();
  2047. IG_createDM();
  2048. $('.IG_SN_DIG #post_info').text('Preference Settings');
  2049.  
  2050. $('.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>');
  2051.  
  2052. for(let o in translateText()){
  2053. $('.IG_SN_DIG .IG_SN_DIG_TITLE > div #langSelect').append(`<option value="${o}" ${(lang == o)?'selected':''}>${translateText()[o].SELECT_LANG}</option>`);
  2054. }
  2055.  
  2056. for(let name in USER_SETTING){
  2057. $('.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>`);
  2058.  
  2059. if(name === 'MODIFY_VIDEO_VOLUME'){
  2060. $('.IG_SN_DIG .IG_SN_DIG_BODY input[id="'+name+'"]').parent('label').on('contextmenu', function(e){
  2061. e.preventDefault();
  2062. if($(this).find('#tempWrapper').length === 0){
  2063. $(this).append('<div id="tempWrapper"></div>');
  2064. $(this).children('#tempWrapper').append('<input value="' + VIDEO_VOLUME + '" type="range" min="0" max="1" step="0.05" />');
  2065. $(this).children('#tempWrapper').append('<input value="' + VIDEO_VOLUME + '" step="0.05" type="number" />');
  2066. $(this).children('#tempWrapper').append(`<div class="IG_SN_DIG_BTN">${SVG.CLOSE}</div>`);
  2067. }
  2068. });
  2069. }
  2070.  
  2071. if(name === 'RENAME_LOCATE_DATE'){
  2072. $('.IG_SN_DIG .IG_SN_DIG_BODY input[id="'+name+'"]').parent('label').on('contextmenu', function(e){
  2073. e.preventDefault();
  2074. if($(this).find('#tempWrapper').length === 0){
  2075. $(this).append('<div id="tempWrapper"></div>');
  2076.  
  2077. $(this).children('#tempWrapper').append('<select id="locateSelect"></select>');
  2078. $(this).children('#tempWrapper').append(`<span id="locatePreview">-</span>`);
  2079. $(this).children('#tempWrapper').append(`<div class="IG_SN_DIG_BTN">${SVG.CLOSE}</div>`);
  2080.  
  2081.  
  2082. LOCATE_DATE_LIST.forEach( locate => {
  2083. $('#tempWrapper').find('#locateSelect').first().append(`<option value="${locate.code}" ${(LOCATE_DATE_FORMAT.toLowerCase() == locate.code.toLowerCase()?'selected':'')}>${locate.name}</option>`);
  2084. });
  2085.  
  2086. $('#locatePreview').text(`${(new Date().toLocaleString($('#locateSelect').val(), {hour12: false})).replaceAll('/','-')}`);
  2087. }
  2088. });
  2089. }
  2090. }
  2091. }
  2092.  
  2093. /**
  2094. * showDebugDOM
  2095. * Show full DOM tree
  2096. *
  2097. * @return {void}
  2098. */
  2099. function showDebugDOM(){
  2100. $('.IG_SN_DIG').remove();
  2101. IG_createDM();
  2102. $('.IG_SN_DIG #post_info').text('IG Debug DOM Tree');
  2103.  
  2104. $('.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>`);
  2105. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<span style="display:block;text-align:center;">`);
  2106. $('.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>`);
  2107. $('.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>`);
  2108. $('.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/>`);
  2109. $('.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>`);
  2110. $('.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>`);
  2111. }
  2112.  
  2113. /**
  2114. * openNewTab
  2115. * Open url in new tab
  2116. *
  2117. * @param {String} link
  2118. * @return {void}
  2119. */
  2120. function openNewTab(link){
  2121. var a = document.createElement('a');
  2122. a.href = link;
  2123. a.target = '_blank';
  2124.  
  2125. document.body.appendChild(a);
  2126. a.click();
  2127. a.remove();
  2128. }
  2129.  
  2130. /**
  2131. * reloadScript
  2132. * Re-register main timer
  2133. *
  2134. * @return {void}
  2135. */
  2136. function reloadScript(){
  2137. clearInterval(GL_repeat);
  2138. pageLoaded = false;
  2139. firstStarted = false;
  2140. currentURL = location.href;
  2141. GL_observer.disconnect();
  2142.  
  2143. console.log('main timer re-register completed');
  2144. }
  2145.  
  2146. /**
  2147. * initSettings
  2148. * Initialize preferences
  2149. *
  2150. * @return {void}
  2151. */
  2152. function initSettings(){
  2153. for(let name in USER_SETTING){
  2154. if(GM_getValue(name) != null && typeof GM_getValue(name) === 'boolean'){
  2155. USER_SETTING[name] = GM_getValue(name);
  2156. }
  2157. }
  2158. }
  2159.  
  2160. // Running if document is ready
  2161. $(function(){
  2162. $('body').on('click','.IG_SN_DIG .IG_SN_DIG_BODY .IG_DISPLAY_DOM_TREE',function(){
  2163. let text = $('div[id^="mount"]')[0];
  2164. $('.IG_SN_DIG .IG_SN_DIG_BODY textarea').text("Location: " + location.pathname + "\nDOM Tree:\n" + text.innerHTML);
  2165. });
  2166.  
  2167. $('body').on('click','.IG_SN_DIG .IG_SN_DIG_BODY .IG_SELECT_DOM_TREE',function(){
  2168. $('.IG_SN_DIG .IG_SN_DIG_BODY textarea').select();
  2169. document.execCommand('copy');
  2170. });
  2171.  
  2172. $('body').on('click','.IG_SN_DIG .IG_SN_DIG_BODY .IG_DOWNLOAD_DOM_TREE',function(){
  2173. 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;
  2174. var a = document.createElement("a");
  2175. var file = new Blob([text], {type: "text/plain"});
  2176. a.href = URL.createObjectURL(file);
  2177. a.download = "DOMTree.txt";
  2178.  
  2179. document.body.appendChild(a);
  2180. a.click();
  2181. a.remove();
  2182. });
  2183.  
  2184. // Close the download dialog if user click the close icon
  2185. $('body').on('click','.IG_SN_DIG_BTN, .IG_SN_DIG_BG',function(){
  2186. if($(this).parent('#tempWrapper').length > 0){
  2187. $(this).parent('#tempWrapper').fadeOut(250, function(){
  2188. $(this).remove();
  2189. });
  2190. }
  2191. else{
  2192. $('.IG_SN_DIG').remove();
  2193. }
  2194. });
  2195.  
  2196. $(window).keydown(function(e){
  2197. // Hot key [Alt+Q] to close the download dialog
  2198. if (e.keyCode == '81' && e.altKey){
  2199. $('.IG_SN_DIG').remove();
  2200. e.preventDefault();
  2201. }
  2202. // Hot key [Alt+W] to open the settings dialog
  2203. if (e.keyCode == '87' && e.altKey){
  2204. showSetting();
  2205. e.preventDefault();
  2206. }
  2207.  
  2208. // Hot key [Alt+Z] to open the settings dialog
  2209. if (e.keyCode == '90' && e.altKey){
  2210. showDebugDOM();
  2211. e.preventDefault();
  2212. }
  2213.  
  2214. // Hot key [Alt+R] to open the settings dialog
  2215. if (e.keyCode == '82' && e.altKey){
  2216. reloadScript();
  2217. e.preventDefault();
  2218. }
  2219. });
  2220.  
  2221. $('body').on('change', '.IG_SN_DIG input',function(e){
  2222. var name = $(this).attr('id');
  2223.  
  2224. if(name && USER_SETTING[name] !== undefined){
  2225. let isChecked = $(this).prop('checked');
  2226. GM_setValue(name, isChecked);
  2227. USER_SETTING[name] = isChecked;
  2228.  
  2229. console.log('user settings', name, isChecked);
  2230. }
  2231. });
  2232.  
  2233. $('body').on('click', '.IG_SN_DIG .globalSettings',function(e){
  2234. if($(this).find('#tempWrapper').length > 0){
  2235. e.preventDefault();
  2236. }
  2237. });
  2238.  
  2239. $('body').on('change', '.IG_SN_DIG #tempWrapper input',function(){
  2240. let value = $(this).val();
  2241.  
  2242. if($(this).attr('type') == 'range'){
  2243. $(this).next().val(value);
  2244. }
  2245. else{
  2246. $(this).prev().val(value);
  2247. }
  2248.  
  2249. if(value >= 0 && value <= 1){
  2250. VIDEO_VOLUME = value;
  2251. GM_setValue('G_VIDEO_VOLUME', value);
  2252. }
  2253. });
  2254.  
  2255. $('body').on('input', '.IG_SN_DIG #tempWrapper input',function(e){
  2256. if($(this).attr('type') == 'range'){
  2257. let value = $(this).val();
  2258. $(this).next().val(value);
  2259. }
  2260. else{
  2261. let value = $(this).val();
  2262. if(value >= 0 && value <= 1){
  2263. $(this).prev().val(value);
  2264. }
  2265. else{
  2266. if(value < 0){
  2267. $(this).val(0);
  2268. }
  2269. else{
  2270. $(this).val(1);
  2271. }
  2272. }
  2273. }
  2274. });
  2275.  
  2276.  
  2277. $('body').on('click','a[data-needed="direct"]', function(e){
  2278. e.preventDefault();
  2279. triggerLinkElement(this);
  2280. });
  2281.  
  2282. $('body').on('click','.IG_SN_DIG_BODY .newTab', function(){
  2283. // replace https://instagram.ftpe8-2.fna.fbcdn.net/ to https://scontent.cdninstagram.com/ becase of same origin policy (some video)
  2284.  
  2285. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && USER_SETTING.NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST){
  2286. triggerLinkElement( $(this).parent().children('a').first()[0], true);
  2287. }
  2288. else{
  2289. var urlObj = new URL($(this).parent().children('a').attr('data-href'));
  2290. urlObj.host = 'scontent.cdninstagram.com';
  2291.  
  2292. openNewTab(urlObj.href);
  2293. }
  2294. });
  2295.  
  2296. $('body').on('click','.IG_SN_DIG_BODY .videoThumbnail', function(){
  2297. 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());
  2298. });
  2299.  
  2300. // Running if user left-click download icon in stories
  2301. $('body').on('click','.IG_DWSTORY',function(){
  2302. onStory(true);
  2303. });
  2304. $('body').on('click','.IG_DWNEWTAB',function(e){
  2305. e.preventDefault();
  2306. onStory(true, true, true);
  2307. });
  2308.  
  2309. // Running if user left-click download icon in stories
  2310. $('body').on('click','.IG_DWSTORY_THUMBNAIL',function(){
  2311. onStoryThumbnail(true);
  2312. });
  2313.  
  2314. // Running if user left-click download icon in profile
  2315. $('body').on('click','.IG_DWPROFILE',function(e){
  2316. e.stopPropagation();
  2317. onProfileAvatar(true);
  2318. });
  2319.  
  2320. // Running if user left-click download icon in highlight stories
  2321. $('body').on('click','.IG_DWHISTORY',function(){
  2322. onHighlightsStory(true);
  2323. });
  2324. $('body').on('click','.IG_DWHINEWTAB',function(e){
  2325. e.preventDefault();
  2326. onHighlightsStory(true, true);
  2327. });
  2328.  
  2329. // Running if user left-click download icon in highlight stories
  2330. $('body').on('click','.IG_DWHISTORY_THUMBNAIL',function(){
  2331. onHighlightsStoryThumbnail(true);
  2332. });
  2333.  
  2334. // Running if user left-click download icon in reels
  2335. $('body').on('click','.IG_REELS',function(){
  2336. onReels(true,true);
  2337. });
  2338.  
  2339. // Running if user left-click newtab icon in reels
  2340. $('body').on('click','.IG_REELSNEWTAB',function(){
  2341. onReels(true,true,true);
  2342. });
  2343.  
  2344. // Running if user left-click download icon in reels
  2345. $('body').on('click','.IG_REELS_THUMBNAIL',function(){
  2346. onReels(true,false);
  2347. });
  2348.  
  2349. // Running if user right-click profile picture in stories area
  2350. $('body').on('contextmenu','button[role="menuitem"]',function(){
  2351. if(location.href === 'https://www.instagram.com/' && USER_SETTING.REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE){
  2352. if($(this).find('canvas._aarh').length > 0){
  2353. location.href = 'https://www.instagram.com/'+$(this).children('div').last().text();
  2354. }
  2355. }
  2356. });
  2357.  
  2358. $('body').on('change', '.IG_SN_DIG_TITLE .checkbox', function(){
  2359. var isChecked = $(this).find('input').prop('checked');
  2360. $('.IG_SN_DIG_BODY .inner_box').each(function(){
  2361. $(this).prop('checked', isChecked);
  2362. });
  2363. });
  2364.  
  2365. $('body').on('change', '.IG_SN_DIG_BODY .inner_box', function(){
  2366. var checked = $('.IG_SN_DIG_BODY .inner_box:checked').length;
  2367. var total = $('.IG_SN_DIG_BODY .inner_box').length;
  2368.  
  2369.  
  2370. $('.IG_SN_DIG_TITLE .checkbox').find('input').prop('checked', checked == total);
  2371. });
  2372.  
  2373. $('body').on('click', '.IG_SN_DIG_TITLE #batch_download_selected', function(){
  2374. let index = 0;
  2375. $('.IG_SN_DIG_BODY a[data-needed="direct"]').each(function(){
  2376. if($(this).prev().children('input').prop('checked')){
  2377. $(this).click();
  2378. index++;
  2379. }
  2380. });
  2381.  
  2382. if(index == 0){
  2383. alert(_i18n('NO_CHECK_RESOURCE'));
  2384. }
  2385. });
  2386.  
  2387. $('body').on('change', '.IG_SN_DIG_TITLE #langSelect', function(){
  2388. GM_setValue('lang', $(this).val());
  2389. lang = $(this).val();
  2390.  
  2391. showSetting();
  2392. });
  2393.  
  2394. $('body').on('change', '.IG_SN_DIG_BODY #locateSelect', function(){
  2395. $('#locatePreview').text(`${(new Date().toLocaleString($(this).val(), {hour12: false})).replaceAll('/','-')}`);
  2396. LOCATE_DATE_FORMAT = $(this).val();
  2397. GM_setValue('G_LOCATE_DATE_FORMAT', $(this).val());
  2398. });
  2399.  
  2400. $('body').on('click', '.IG_SN_DIG_TITLE #batch_download_direct', function(){
  2401. $('.IG_SN_DIG_BODY a[data-needed="direct"]').each(function(){
  2402. $(this).click();
  2403. });
  2404. });
  2405. });
  2406. })(jQuery);