IG小助手

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

当前为 2024-08-02 提交的版本,查看 最新版本

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