IG小助手

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

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

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