IG小助手

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

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

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