IG小助手

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

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

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址