IG小助手

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

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

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