IG小助手

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

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

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