IG小助手

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

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

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