IG小助手

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

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

  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.29.1
  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. // Modify Video Volume
  434. if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  435. $element.find('video').each(function(){
  436. if(!$(this).data('modify')){
  437. console.log('(highlight) Added video event listener #modify');
  438. this.volume = VIDEO_VOLUME;
  439.  
  440. $(this).on('play',function(){
  441. this.volume = VIDEO_VOLUME;
  442. });
  443. $(this).on('playing',function(){
  444. this.volume = VIDEO_VOLUME;
  445. });
  446.  
  447. $(this).attr('data-modify', true);
  448. }
  449. });
  450. }
  451. }
  452. }
  453. }
  454. }
  455.  
  456. /**
  457. * onHighlightsStoryThumbnail
  458. * Trigger user's highlight video thumbnail download event or button display event.
  459. *
  460. * @param {Boolean} isDownload - Check if it is a download operation
  461. * @return {void}
  462. */
  463. async function onHighlightsStoryThumbnail(isDownload){
  464. if(isDownload){
  465. let date = new Date().getTime();
  466. let timestamp = Math.floor(date / 1000);
  467. let highlightId = location.href.replace(/\/$/ig,'').split('/').at(-1);
  468. let username = "";
  469. let nowIndex = $("body > div section._ac0a header._ac0k > ._ac3r ._ac3n ._ac3p[style]").length ||
  470. $('body > div section:visible > div > div:not([class]) > div > div div.x1ned7t2.x78zum5 div.x1caxmr6').length ||
  471. $('body > div div:not([hidden]) section:visible > div div[style]:not([class]) > div').find('div div.x1ned7t2.x78zum5 div.x1caxmr6').length;
  472. let target = "";
  473.  
  474. updateLoadingBar(true);
  475.  
  476. if(GL_dataCache.highlights[highlightId]){
  477. console.log('Fetch from memory cache:', highlightId);
  478.  
  479. let totIndex = GL_dataCache.highlights[highlightId].data.reels_media[0].items.length;
  480. username = GL_dataCache.highlights[highlightId].data.reels_media[0].owner.username;
  481. target = GL_dataCache.highlights[highlightId].data.reels_media[0].items[totIndex-nowIndex];
  482. }
  483. else{
  484. let highStories = await getHighlightStories(highlightId);
  485. let totIndex = highStories.data.reels_media[0].items.length;
  486. username = highStories.data.reels_media[0].owner.username;
  487. target = highStories.data.reels_media[0].items[totIndex-nowIndex];
  488.  
  489. GL_dataCache.highlights[highlightId] = highStories;
  490. }
  491.  
  492. if(USER_SETTING.RENAME_PUBLISH_DATE){
  493. timestamp = target.taken_at_timestamp;
  494. }
  495.  
  496. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LITMIT){
  497. let result = await getMediaInfo(target.id);
  498.  
  499. if(result.status === 'ok'){
  500. saveFiles(result.items[0].image_versions2.candidates[0].url, username,"highlights",timestamp,'jpg');
  501. }
  502. else{
  503. if(USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT){
  504. delete GL_dataCache.highlights[highlightId];
  505. TEMP_FETCH_RATE_LITMIT = true;
  506.  
  507. onHighlightsStoryThumbnail(true);
  508. }
  509. else{
  510. alert('Fetch failed from Media API. API response message: ' + result.message);
  511. }
  512.  
  513. console.log(result);
  514. }
  515. }
  516. else{
  517. saveFiles(target.display_resources.at(-1).src,username,"highlights",timestamp,'jpg', highlightId);
  518. TEMP_FETCH_RATE_LITMIT= false;
  519. }
  520.  
  521. updateLoadingBar(false);
  522. }
  523. else{
  524. if($('body > div section video.xh8yej3').length){
  525. // Add the stories thumbnail download button
  526. if(!$('.IG_DWHISTORY_THUMBNAIL').length){
  527. let $element = null;
  528.  
  529. // Default detecter (section layout mode)
  530. if($('body > div section._ac0a').length > 0){
  531. $element = $('body > div section:visible._ac0a');
  532. }
  533. else{
  534. $element = $('body > div section:visible > div > div[style]:not([class])');
  535. $element.css('position','relative');
  536. }
  537.  
  538. // Detecter for div layout mode
  539. if($element.length === 0){
  540. let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
  541. let nowSize = 0;
  542.  
  543. $$element.each(function(){
  544. if($(this).width() > nowSize){
  545. nowSize = $(this).width();
  546. $element = $(this).children('div').first();
  547. }
  548. });
  549. }
  550.  
  551. if($element != null){
  552. $element.append(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="IG_DWHISTORY_THUMBNAIL">${SVG.THUMBNAIL}</div>`);
  553. }
  554. }
  555. }
  556. else{
  557. $('.IG_DWHISTORY_THUMBNAIL').remove();
  558. }
  559. }
  560. }
  561.  
  562. /**
  563. * onStory
  564. * Trigger user's story download event or button display event.
  565. *
  566. * @param {Boolean} isDownload - Check if it is a download operation
  567. * @param {Boolean} isForce - Check if downloading directly from API instead of cache
  568. * @param {Boolean} isPreview - Check if it is need to open new tab
  569. * @return {void}
  570. */
  571. async function onStory(isDownload,isForce,isPreview){
  572. if(isDownload){
  573. let date = new Date().getTime();
  574. let timestamp = Math.floor(date / 1000);
  575. let username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split('/').at(2);
  576.  
  577. updateLoadingBar(true);
  578. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LITMIT){
  579. let mediaId = null;
  580.  
  581. let userInfo = await getUserId(username);
  582. let userId = userInfo.user.pk;
  583. let stories = await getStories(userId);
  584.  
  585. // appear in from profile page to story page
  586. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function(index){
  587. if($(this).hasClass('x1lix1fw')){
  588. if($(this).children().length > 0){
  589. mediaId = stories.data.reels_media[0].items[index].id;
  590. }
  591. }
  592. });
  593.  
  594. // appear in from home page to story page
  595. $('body > div section:visible ._ac0k > ._ac3r > div').each(function(index){
  596. if($(this).children().hasClass('_ac3q')){
  597. mediaId = stories.data.reels_media[0].items[index].id;
  598. }
  599. });
  600.  
  601. if(mediaId == null){
  602. mediaId = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
  603. }
  604.  
  605. let result = await getMediaInfo(mediaId);
  606.  
  607. if(USER_SETTING.RENAME_PUBLISH_DATE){
  608. timestamp = result.items[0].taken_at;
  609. }
  610.  
  611. if(result.status === 'ok'){
  612. if(result.items[0].video_versions){
  613. if(isPreview){
  614. openNewTab(result.items[0].video_versions[0].url);
  615. }
  616. else{
  617. saveFiles(result.items[0].video_versions[0].url, username,"stories",timestamp,'mp4');
  618. }
  619. }
  620. else{
  621. if(isPreview){
  622. openNewTab(result.items[0].image_versions2.candidates[0].url);
  623. }
  624. else{
  625. saveFiles(result.items[0].image_versions2.candidates[0].url, username,"stories",timestamp,'jpg');
  626. }
  627. }
  628. }
  629. else{
  630. if(USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT){
  631. TEMP_FETCH_RATE_LITMIT = true;
  632. onStory(isDownload,isForce,isPreview);
  633. }
  634. else{
  635. alert('Fetch failed from Media API. API response message: ' + result.message);
  636. }
  637. console.log(result);
  638. }
  639.  
  640. updateLoadingBar(false);
  641. return;
  642. }
  643.  
  644. if($('body > div section:visible video[playsinline]').length > 0){
  645. // Download stories if it is video
  646. let type = "mp4";
  647. let videoURL = "";
  648. let targetURL = location.pathname.replace(/\/$/ig,'').split("/").at(-1);
  649.  
  650. if(GL_dataCache.stories[username] && !isForce){
  651. console.log('Fetch from memory cache:', username);
  652. GL_dataCache.stories[username].data.reels_media[0].items.forEach(item => {
  653. if(item.id == targetURL){
  654. videoURL = item.video_resources[0].src;
  655. if(USER_SETTING.RENAME_PUBLISH_DATE){
  656. timestamp = item.taken_at_timestamp;
  657. }
  658. }
  659. });
  660.  
  661. if(videoURL.length == 0){
  662. console.log('Memory cache not found, try fetch from API:', username);
  663. onStory(true,true);
  664. return;
  665. }
  666. }
  667. else{
  668. let userInfo = await getUserId(username);
  669. let userId = userInfo.user.pk;
  670. let stories = await getStories(userId);
  671.  
  672. stories.data.reels_media[0].items.forEach(item => {
  673. if(item.id == targetURL){
  674. videoURL = item.video_resources[0].src;
  675. if(USER_SETTING.RENAME_PUBLISH_DATE){
  676. timestamp = item.taken_at_timestamp;
  677. }
  678. }
  679. });
  680.  
  681. // GitHub issue #4: thinkpad4
  682. if(videoURL.length == 0){
  683. // appear in from profile page to story page
  684. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function(index){
  685. if($(this).hasClass('x1lix1fw')){
  686. if($(this).children().length > 0){
  687. videoURL = stories.data.reels_media[0].items[index].video_resources[0].src;
  688. if(USER_SETTING.RENAME_PUBLISH_DATE){
  689. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  690. }
  691. }
  692. }
  693. });
  694.  
  695. // appear in from home page to story page
  696. $('body > div section:visible ._ac0k > ._ac3r > div').each(function(index){
  697. if($(this).children().hasClass('_ac3q')){
  698. videoURL = stories.data.reels_media[0].items[index].video_resources[0].src;
  699. if(USER_SETTING.RENAME_PUBLISH_DATE){
  700. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  701. }
  702. }
  703. });
  704. }
  705.  
  706. GL_dataCache.stories[username] = stories;
  707. }
  708.  
  709. if(videoURL.length == 0){
  710. alert(_i18n("NO_VID_URL"));
  711. }
  712. else{
  713. if(isPreview){
  714. openNewTab(videoURL);
  715. }
  716. else{
  717. saveFiles(videoURL,username,"stories",timestamp,type);
  718. }
  719. }
  720. }
  721. else{
  722. // Download stories if it is image
  723. let srcset = $('body > div section:visible img[referrerpolicy][class], body > div section:visible img[crossorigin][class]:not([alt])').attr('srcset')?.split(',')[0]?.split(' ')[0];
  724. let link = (srcset)?srcset:$('body > div section:visible img[referrerpolicy][class], body > div section:visible img[crossorigin][class]:not([alt])').attr('src');
  725.  
  726. if(!link){
  727. // _aa63 mean stories picture in stories page (not avatar)
  728. let $element = $('body > div section:visible img._aa63');
  729. link = ($element.attr('srcset'))?$element.attr('srcset')?.split(',')[0]?.split(' ')[0]:$element.attr('src');
  730. }
  731.  
  732. if(USER_SETTING.RENAME_PUBLISH_DATE){
  733. timestamp = new Date($('body > div section:visible time[datetime][class]').first().attr('datetime')).getTime();
  734. }
  735.  
  736. let downloadLink = link;
  737. let type = 'jpg';
  738.  
  739. if(isPreview){
  740. openNewTab(downloadLink);
  741. }
  742. else{
  743. saveFiles(downloadLink,username,"stories",timestamp,type);
  744. }
  745. }
  746.  
  747. TEMP_FETCH_RATE_LITMIT = false;
  748. updateLoadingBar(false);
  749. }
  750. else{
  751. // Add the stories download button
  752. let style = "position: absolute;right:-40px;top:15px;padding:5px;line-height:1;background:#fff;border-radius: 5px;cursor:pointer;";
  753. if(!$('.IG_DWSTORY').length){
  754. GL_dataCache.stories = {};
  755. let $element = null;
  756. // Default detecter (section layout mode)
  757. if($('body > div section._ac0a').length > 0){
  758. $element = $('body > div section:visible._ac0a');
  759. }
  760. // detecter (single story layout mode)
  761. else{
  762. $element = $('body > div section:visible > div > div[style]:not([class])');
  763. $element.css('position','relative');
  764. }
  765.  
  766.  
  767. if($element.length === 0){
  768. $element = $('div[id^="mount"] > div > div > div > div > div > div > div > section').parent().find('section:visible > div > div[style]:not([class])');
  769. $element.css('position','relative');
  770. }
  771.  
  772. if($element.length === 0){
  773. $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"])');
  774. $element.css('position','relative');
  775. }
  776.  
  777.  
  778. // Detecter for div layout mode
  779. if($element.length === 0){
  780. let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
  781. let nowSize = 0;
  782.  
  783. $$element.each(function(){
  784. if($(this).width() > nowSize){
  785. nowSize = $(this).width();
  786. $element = $(this).children('div').first();
  787. }
  788. });
  789. }
  790.  
  791.  
  792. if($element != null){
  793. $element.first().css('position','relative');
  794. $element.first().append(`<div title="${_i18n("DW")}" class="IG_DWSTORY">${SVG.DOWNLOAD}</div>`);
  795. $element.first().append(`<div title="${_i18n("NEW_TAB")}" class="IG_DWNEWTAB">${SVG.NEW_TAB}</div>`);
  796.  
  797. // Modify Video Volume
  798. if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  799. $element.find('video').each(function(){
  800. if(!$(this).data('modify')){
  801. console.log('(story) Added video event listener #modify');
  802. this.volume = VIDEO_VOLUME;
  803.  
  804. $(this).on('play',function(){
  805. this.volume = VIDEO_VOLUME;
  806. });
  807. $(this).on('playing',function(){
  808. this.volume = VIDEO_VOLUME;
  809. });
  810.  
  811. $(this).attr('data-modify', true);
  812. }
  813. });
  814. }
  815.  
  816. onStoryThumbnail(false);
  817. }
  818. }
  819. }
  820. }
  821.  
  822. /**
  823. * onStoryThumbnail
  824. * Trigger user's story video thumbnail download event or button display event.
  825. *
  826. * @param {Boolean} isDownload - Check if it is a download operation
  827. * @param {Boolean} isForce - Check if downloading directly from API instead of cache
  828. * @return {void}
  829. */
  830. async function onStoryThumbnail(isDownload,isForce){
  831. if(isDownload){
  832. // Download stories if it is video
  833. let date = new Date().getTime();
  834. let timestamp = Math.floor(date / 1000);
  835. let type = 'jpg';
  836. let username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split('/').at(2);
  837. 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;';
  838. // Download thumbnail
  839. let targetURL = location.pathname.replace(/\/$/ig,'').split("/").at(-1);
  840. let videoThumbnailURL = "";
  841.  
  842. updateLoadingBar(true);
  843.  
  844. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && !TEMP_FETCH_RATE_LITMIT){
  845. let mediaId = null;
  846.  
  847. let userInfo = await getUserId(username);
  848. let userId = userInfo.user.pk;
  849. let stories = await getStories(userId);
  850.  
  851. // appear in from profile page to story page
  852. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function(index){
  853. if($(this).hasClass('x1lix1fw')){
  854. if($(this).children().length > 0){
  855. mediaId = stories.data.reels_media[0].items[index].id;
  856. }
  857. }
  858. });
  859.  
  860. // appear in from home page to story page
  861. $('body > div section:visible ._ac0k > ._ac3r > div').each(function(index){
  862. if($(this).children().hasClass('_ac3q')){
  863. mediaId = stories.data.reels_media[0].items[index].id;
  864. }
  865. });
  866.  
  867. if(mediaId == null){
  868. mediaId = location.pathname.split('/').filter(s => s.length > 0 && s.match(/^([0-9]{10,})$/)).at(-1);
  869. }
  870.  
  871. let result = await getMediaInfo(mediaId);
  872.  
  873. if(USER_SETTING.RENAME_PUBLISH_DATE){
  874. timestamp = result.items[0].taken_at;
  875. }
  876.  
  877. if(result.status === 'ok'){
  878. saveFiles(result.items[0].image_versions2.candidates[0].url, username,"stories",timestamp,'jpg');
  879.  
  880. }
  881. else{
  882. if(USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT){
  883. TEMP_FETCH_RATE_LITMIT = true;
  884. onStoryThumbnail(true, isForce);
  885. }
  886. else{
  887. alert('Fetch failed from Media API. API response message: ' + result.message);
  888. }
  889.  
  890. console.log(result);
  891. }
  892.  
  893. updateLoadingBar(false);
  894. return;
  895. }
  896.  
  897. if(GL_dataCache.stories[username] && !isForce){
  898. console.log('Fetch from memory cache:', username);
  899. GL_dataCache.stories[username].data.reels_media[0].items.forEach(item => {
  900. if(item.id == targetURL){
  901. videoThumbnailURL = item.display_url;
  902. if(USER_SETTING.RENAME_PUBLISH_DATE){
  903. timestamp = item.taken_at_timestamp;
  904. }
  905. }
  906. });
  907.  
  908. if(videoThumbnailURL.length == 0){
  909. console.log('Memory cache not found, try fetch from API:', username);
  910. onStoryThumbnail(true,true);
  911. return;
  912. }
  913. }
  914. else{
  915. let userInfo = await getUserId(username);
  916. let userId = userInfo.user.pk;
  917. let stories = await getStories(userId);
  918.  
  919. stories.data.reels_media[0].items.forEach(item => {
  920. if(item.id == targetURL){
  921. videoThumbnailURL = item.display_url;
  922. if(USER_SETTING.RENAME_PUBLISH_DATE){
  923. timestamp = item.taken_at_timestamp;
  924. }
  925. }
  926. });
  927.  
  928. // GitHub issue #4: thinkpad4
  929. if(videoThumbnailURL.length == 0){
  930. // appear in from profile page to story page
  931. $('body > div section:visible div.x1ned7t2.x78zum5 > div').each(function(index){
  932. if($(this).hasClass('x1lix1fw')){
  933. if($(this).children().length > 0){
  934. videoThumbnailURL = stories.data.reels_media[0].items[index].display_url;
  935. if(USER_SETTING.RENAME_PUBLISH_DATE){
  936. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  937. }
  938. }
  939. }
  940. });
  941.  
  942. // appear in from home page to story page
  943. $('body > div section:visible ._ac0k > ._ac3r > div').each(function(index){
  944. if($(this).children().hasClass('_ac3q')){
  945. videoThumbnailURL = stories.data.reels_media[0].items[index].display_url;
  946. if(USER_SETTING.RENAME_PUBLISH_DATE){
  947. timestamp = stories.data.reels_media[0].items[index].taken_at_timestamp;
  948. }
  949. }
  950. });
  951. }
  952. }
  953.  
  954. saveFiles(videoThumbnailURL,username,"thumbnail",timestamp,type);
  955. TEMP_FETCH_RATE_LITMIT= false;
  956. updateLoadingBar(false);
  957. }
  958. else{
  959. if($('body > div div.IG_DWSTORY').parent().find('video[class]').length){
  960. // Add the stories download button
  961. let $element = null;
  962. // Default detecter (section layout mode)
  963. if($('body > div section._ac0a').length > 0){
  964. $element = $('body > div section:visible._ac0a');
  965. }
  966. // detecter (single story layout mode)
  967. else{
  968. $element = $('body > div section:visible > div > div[style]:not([class])');
  969. $element.css('position','relative');
  970. }
  971.  
  972. if($element.length === 0){
  973. $element = $('div[id^="mount"] > div > div > div > div > div > div > div > section').parent().find('section:visible > div > div[style]:not([class])');
  974. $element.css('position','relative');
  975. }
  976.  
  977. if($element.length === 0){
  978. $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"])');
  979. $element.css('position','relative');
  980. }
  981.  
  982. // Detecter for div layout mode
  983. if($element.length === 0){
  984. let $$element = $('body > div div:not([hidden]) section:visible > div div[class][style] > div[style]:not([class])');
  985. let nowSize = 0;
  986.  
  987. $$element.each(function(){
  988. if($(this).width() > nowSize){
  989. nowSize = $(this).width();
  990. $element = $(this).children('div').first();
  991. }
  992. });
  993. }
  994.  
  995.  
  996. if($element != null){
  997. $element.first().css('position','relative');
  998. $element.first().append(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="IG_DWSTORY_THUMBNAIL">${SVG.THUMBNAIL}</div>`);
  999. }
  1000.  
  1001. }
  1002. }
  1003. }
  1004.  
  1005. /**
  1006. * onReels
  1007. * Trigger user's reels download event or button display event.
  1008. *
  1009. * @param {Boolean} isDownload - Check if it is a download operation
  1010. * @param {Boolean} isVideo - Check if reel is a video element
  1011. * @param {Boolean} isPreview - Check if it is need to open new tab
  1012. * @return {void}
  1013. */
  1014. async function onReels(isDownload, isVideo, isPreview){
  1015. if(isDownload){
  1016. updateLoadingBar(true);
  1017.  
  1018. let reelsPath = location.href.split('?').at(0).split('instagram.com/reels/').at(-1).replaceAll('/','');
  1019. let data = await getBlobMedia(reelsPath);
  1020.  
  1021. let timestamp = new Date().getTime();
  1022.  
  1023. if(USER_SETTING.RENAME_PUBLISH_DATE){
  1024. timestamp = data.shortcode_media.taken_at_timestamp;
  1025. }
  1026.  
  1027. if(isVideo && data.shortcode_media.is_video){
  1028. if(isPreview){
  1029. openNewTab(data.shortcode_media.video_url);
  1030. }
  1031. else{
  1032. let type = 'mp4';
  1033. saveFiles(data.shortcode_media.video_url,data.shortcode_media.owner.username,"reels",timestamp,type,reelsPath);
  1034. }
  1035. }
  1036. else{
  1037. if(isPreview){
  1038. openNewTab(data.shortcode_media.display_resources.at(-1).src);
  1039. }
  1040. else{
  1041. let type = 'jpg';
  1042. saveFiles(data.shortcode_media.display_resources.at(-1).src,data.shortcode_media.owner.username,"reels",timestamp,type,reelsPath);
  1043. }
  1044. }
  1045.  
  1046. updateLoadingBar(false);
  1047. }
  1048. else{
  1049. //$('.IG_REELS_THUMBNAIL, .IG_REELS').remove();
  1050. var timer = setInterval(()=>{
  1051. if($('section > main[role="main"] > div div.x1qjc9v5 video').length > 0){
  1052. clearInterval(timer);
  1053.  
  1054. if(USER_SETTING.SCROLL_BUTTON){
  1055. $('#scrollWrapper').remove();
  1056. $('section > main[role="main"]').append('<section id="scrollWrapper"></section>');
  1057. $('section > main[role="main"] > #scrollWrapper').append('<div class="button-up"><div></div></div>');
  1058. $('section > main[role="main"] > #scrollWrapper').append('<div class="button-down"><div></div></div>');
  1059.  
  1060. $('section > main[role="main"] > #scrollWrapper > .button-up').on('click',function(){
  1061. $('section > main[role="main"] > div')[0].scrollBy({top: -30, behavior: "smooth"});
  1062. });
  1063. $('section > main[role="main"] > #scrollWrapper > .button-down').on('click',function(){
  1064. $('section > main[role="main"] > div')[0].scrollBy({top: 30, behavior: "smooth"});
  1065. });
  1066. }
  1067.  
  1068. // reels scroll has [tabindex] but header not.
  1069. $('section > main[role="main"] > div[tabindex]').children('div').each(function(){
  1070. if($(this).children().length > 0){
  1071. if(!$(this).children().find('.IG_REELS').length){
  1072. var $main = $(this);
  1073.  
  1074. $(this).children().css('position','relative');
  1075.  
  1076. $(this).children().append(`<div title="${_i18n("DW")}" class="IG_REELS">${SVG.DOWNLOAD}</div>`);
  1077. $(this).children().append(`<div title="${_i18n("NEW_TAB")}" class="IG_REELS_NEWTAB">${SVG.NEW_TAB}</div>`);
  1078. $(this).children().append(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="IG_REELS_THUMBNAIL">${SVG.THUMBNAIL}</div>`);
  1079.  
  1080. // Disable video autoplay
  1081. if(USER_SETTING.DISABLE_VIDEO_LOOPING){
  1082. $(this).find('video').each(function(){
  1083. if(!$(this).data('loop')){
  1084. console.log('(reel) Added video event listener #loop');
  1085. $(this).on('ended',function(){
  1086. $(this).attr('data-loop', true);
  1087. let $element = $(this).next().find('div[role="presentation"] > div > div:last-child');
  1088.  
  1089. if($element.length > 0){
  1090. $element.click();
  1091. console.log('paused click()');
  1092. }
  1093. else{
  1094. $(this).parent().find('.xpgaw4o').removeAttr('style');
  1095. this.pause();
  1096. console.log('paused pause()');
  1097. }
  1098. });
  1099. }
  1100. });
  1101. }
  1102. // Modify Video Volume
  1103. if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  1104. $(this).find('video').each(function(){
  1105. if(!$(this).data('modify')){
  1106. console.log('(reel) Added video event listener #modify');
  1107. this.volume = VIDEO_VOLUME;
  1108.  
  1109. $(this).on('play',function(){
  1110. this.volume = VIDEO_VOLUME;
  1111. });
  1112. $(this).on('playing',function(){
  1113. this.volume = VIDEO_VOLUME;
  1114. });
  1115.  
  1116. $(this).attr('data-modify', true);
  1117. }
  1118. });
  1119. }
  1120.  
  1121. if(USER_SETTING.HTML5_VIDEO_CONTROL){
  1122. $(this).find('video').each(function(){
  1123. if(!$(this).data('controls')){
  1124. let $video = $(this);
  1125.  
  1126. console.log('(reel) Added video html5 contorller #modify');
  1127. this.volume = VIDEO_VOLUME;
  1128.  
  1129. $(this).on('loadstart',function(){
  1130. this.volume = VIDEO_VOLUME;
  1131. });
  1132.  
  1133. // Restore layout to show details interface
  1134. $(this).on('contextmenu',function(e){
  1135. e.preventDefault();
  1136. $video.css('z-index', '-1');
  1137. $video.removeAttr('controls');
  1138. });
  1139.  
  1140. // Hide layout to show controller
  1141. $(this).parent().find('video + div div[role="button"]').filter(function(){
  1142. return $(this).parent('div[role="presentation"]').length > 0 && $(this).css('cursor') === 'pointer' && $(this).attr('style') != null;
  1143. }).first().on('contextmenu',function(e){
  1144. e.preventDefault();
  1145. $video.css('z-index', '2');
  1146. $video.attr('controls', true);
  1147. });
  1148.  
  1149.  
  1150. $(this).on('volumechange',function(){
  1151. let $element_mute_button = $(this).parent().find('video + div > div').find('button[type="button"], div[role="button"]').filter(function(idx){
  1152. // This is mention others' icon
  1153. return $(this).find('svg > path[d^="M21.334"]').length === 0;
  1154. });
  1155.  
  1156. var is_elelment_muted = $element_mute_button.find('svg > path[d^="M16.636"]').length === 0;
  1157.  
  1158. if(this.muted != is_elelment_muted){
  1159. this.volume = VIDEO_VOLUME;
  1160. $element_mute_button?.click();
  1161. }
  1162.  
  1163. if ($(this).attr('data-completed')){
  1164. VIDEO_VOLUME = this.volume;
  1165. GM_setValue('G_VIDEO_VOLUME', this.volume);
  1166. }
  1167.  
  1168. if(this.volume == VIDEO_VOLUME){
  1169. $(this).attr('data-completed', true);
  1170. }
  1171. });
  1172.  
  1173. $(this).css('position', 'absolute');
  1174. $(this).css('z-index', '2');
  1175. $(this).attr('data-controls', true);
  1176. $(this).attr('controls', true);
  1177. }
  1178. });
  1179. }
  1180.  
  1181. var $buttonParent = $(this).find('div[role="presentation"] > div[role="button"] > div').first();
  1182. $buttonParent.append('<div class="volume_slider" />');
  1183. $buttonParent.find('div.volume_slider').append(`<div><input type="range" max="1" min="0" step="0.05" value="${VIDEO_VOLUME}" /></div>`);
  1184. $buttonParent.find('div.volume_slider input').attr('style',`--ig-track-progress: ${(VIDEO_VOLUME * 100) + '%'}`);
  1185. $buttonParent.find('div.volume_slider input').on('input',function(){
  1186. var percent = ($(this).val() * 100) + '%';
  1187.  
  1188. VIDEO_VOLUME = $(this).val();
  1189. GM_setValue('G_VIDEO_VOLUME', $(this).val());
  1190.  
  1191. $(this).attr('style',`--ig-track-progress: ${percent}`);
  1192.  
  1193. $main.find('video').each(function(){
  1194. console.log('(reel) video volume changed #slider');
  1195. this.volume = VIDEO_VOLUME;
  1196. });
  1197. });
  1198.  
  1199. $buttonParent.find('div.volume_slider input').on('mouseenter',function(){
  1200. var percent = (VIDEO_VOLUME * 100) + '%';
  1201. $(this).attr('style',`--ig-track-progress: ${percent}`);
  1202. $(this).val(VIDEO_VOLUME);
  1203. $main.find('video').each(function(){
  1204. console.log('(reel) video volume changed #slider');
  1205. this.volume = VIDEO_VOLUME;
  1206. });
  1207. });
  1208.  
  1209. $buttonParent.find('div.volume_slider').on('click',function(e){
  1210. e.stopPropagation();
  1211. e.preventDefault();
  1212. });
  1213. }
  1214. }
  1215. });
  1216. }
  1217. },250);
  1218. }
  1219. }
  1220.  
  1221. /**
  1222. * getHighlightStories
  1223. * Get a list of all stories in highlight Id.
  1224. *
  1225. * @param {Integer} highlightId
  1226. * @return {Object}
  1227. */
  1228. function getHighlightStories(highlightId){
  1229. return new Promise((resolve,reject)=>{
  1230. 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`;
  1231.  
  1232. GM_xmlhttpRequest({
  1233. method: "GET",
  1234. url: getURL,
  1235. onload: function(response) {
  1236. let obj = JSON.parse(response.response);
  1237. resolve(obj);
  1238. },
  1239. onerror: function(err){
  1240. reject(err);
  1241. }
  1242. });
  1243. });
  1244. }
  1245.  
  1246. /**
  1247. * getStories
  1248. * Get a list of all stories in user Id.
  1249. *
  1250. * @param {Integer} userId
  1251. * @return {Object}
  1252. */
  1253. function getStories(userId){
  1254. return new Promise((resolve,reject)=>{
  1255. 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`;
  1256.  
  1257. GM_xmlhttpRequest({
  1258. method: "GET",
  1259. url: getURL,
  1260. onload: function(response) {
  1261. let obj = JSON.parse(response.response);
  1262. resolve(obj);
  1263. },
  1264. onerror: function(err){
  1265. reject(err);
  1266. }
  1267. });
  1268. });
  1269. }
  1270.  
  1271. /**
  1272. * getUserId
  1273. * Get user's id with username
  1274. *
  1275. * @param {String} username
  1276. * @return {Integer}
  1277. */
  1278. function getUserId(username){
  1279. return new Promise((resolve,reject)=>{
  1280. let getURL = `https://www.instagram.com/web/search/topsearch/?query=${username}`;
  1281.  
  1282. GM_xmlhttpRequest({
  1283. method: "GET",
  1284. url: getURL,
  1285. onload: function(response) {
  1286. // Fix search issue by Discord: sno_w_
  1287. let obj = JSON.parse(response.response);
  1288. let result = null;
  1289. obj.users.forEach(pos => {
  1290. if(pos.user.username === username){
  1291. result = pos;
  1292. }
  1293. });
  1294.  
  1295. if(result != null){
  1296. resolve(result);
  1297. }
  1298. else{
  1299. alert("Can not find user info from getUserId()");
  1300. }
  1301. },
  1302. onerror: function(err){
  1303. reject(err);
  1304. }
  1305. });
  1306. });
  1307. }
  1308.  
  1309. /**
  1310. * getUserHighSizeProfile
  1311. * Get user's high quality avatar image.
  1312. *
  1313. * @param {Integer} userId
  1314. * @return {String}
  1315. */
  1316. function getUserHighSizeProfile(userId){
  1317. return new Promise((resolve,reject)=>{
  1318. let getURL = `https://i.instagram.com/api/v1/users/${userId}/info/`;
  1319.  
  1320. GM_xmlhttpRequest({
  1321. method: "GET",
  1322. url: getURL,
  1323. headers: {
  1324. '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'
  1325. },
  1326. onload: function(response) {
  1327. let obj = JSON.parse(response.response);
  1328. if(obj.status !== 'ok'){
  1329. reject('faild');
  1330. }
  1331. else{
  1332. resolve(obj.user.hd_profile_pic_url_info?.url);
  1333. }
  1334. },
  1335. onerror: function(err){
  1336. reject(err);
  1337. }
  1338. });
  1339. });
  1340. }
  1341.  
  1342. /**
  1343. * getPostOwner
  1344. * Get post's author with post shortcode
  1345. *
  1346. * @param {String} postPath
  1347. * @return {String}
  1348. */
  1349. function getPostOwner(postPath){
  1350. return new Promise((resolve,reject)=>{
  1351. if(!postPath) reject("NOPATH");
  1352. let postShortCode = postPath;
  1353. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  1354.  
  1355. GM_xmlhttpRequest({
  1356. method: "GET",
  1357. url: getURL,
  1358. onload: function(response) {
  1359. let obj = JSON.parse(response.response);
  1360. resolve(obj.data.shortcode_media.owner.username);
  1361. },
  1362. onerror: function(err){
  1363. reject(err);
  1364. }
  1365. });
  1366. });
  1367. }
  1368.  
  1369. /**
  1370. * getBlobMedia
  1371. * Get list of all media files in post with post shortcode
  1372. *
  1373. * @param {String} postPath
  1374. * @return {Object}
  1375. */
  1376. function getBlobMedia(postPath){
  1377. return new Promise((resolve,reject)=>{
  1378. if(!postPath) reject("NOPATH");
  1379. let postShortCode = postPath;
  1380. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  1381.  
  1382. GM_xmlhttpRequest({
  1383. method: "GET",
  1384. url: getURL,
  1385. onload: function(response) {
  1386. let obj = JSON.parse(response.response);
  1387. console.log(obj);
  1388. resolve(obj.data);
  1389. },
  1390. onerror: function(err){
  1391. reject(err);
  1392. }
  1393. });
  1394. });
  1395. }
  1396.  
  1397. /**
  1398. * onReadyMyDW
  1399. * Create an event entry point for the download button for the post
  1400. *
  1401. * @param {Boolean} NoDialog - Check if it not showing the dialog
  1402. * @param {?Boolean} hasReferrer - Check if the source of the previous page is a story page
  1403. * @return {void}
  1404. */
  1405. function onReadyMyDW(NoDialog, hasReferrer){
  1406. if(hasReferrer === true){
  1407. console.log('hasReferrer', 'regenerated');
  1408. $('article[data-snig="canDownload"], div[data-snig="canDownload"]').removeAttr('data-snig');
  1409. }
  1410.  
  1411. // Whether is Instagram dialog?
  1412. if(NoDialog == false){
  1413. const maxCall = 100;
  1414. let i = 0;
  1415. var repeat = setInterval(() => {
  1416. // div.xdt5ytf << (sigle post in top, not floating) >>
  1417. 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){
  1418. clearInterval(repeat);
  1419.  
  1420. if(i > maxCall){
  1421. //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.');
  1422. console.warn('onReadyMyDW() Timer', 'maximum number of repetitions reached, terminated');
  1423. }
  1424. }
  1425.  
  1426. console.log('onReadyMyDW() Timer', 'repeating to call detection createDownloadButton()');
  1427. createDownloadButton();
  1428. i++;
  1429. },50);
  1430. }
  1431. else{
  1432. createDownloadButton();
  1433. }
  1434. }
  1435.  
  1436. /**
  1437. * getAppID
  1438. * Get Instagram App ID
  1439. *
  1440. * @return {?integer}
  1441. */
  1442. function getAppID(){
  1443. let result = null;
  1444. $('script[type="application/json"]').each(function(){
  1445. const regexp = /"APP_ID":"([0-9]+)"/ig;
  1446. const matcher = $(this).text().match(regexp);
  1447. if(matcher != null && result == null){
  1448. result = [...$(this).text().matchAll(regexp)];
  1449. }
  1450. })
  1451.  
  1452. return (result)?result.at(0).at(-1):null;
  1453. }
  1454.  
  1455. /**
  1456. * updateLoadingBar
  1457. * Update loading state
  1458. *
  1459. * @param {Boolean} isLoading - Check if loading state
  1460. * @return {void}
  1461. */
  1462. function updateLoadingBar(isLoading){
  1463. if(isLoading){
  1464. $('div[id^="mount"] > div > div > div:first').removeClass('x1s85apg');
  1465. $('div[id^="mount"] > div > div > div:first').css('z-index','20000');
  1466. }
  1467. else{
  1468. $('div[id^="mount"] > div > div > div:first').addClass('x1s85apg');
  1469. $('div[id^="mount"] > div > div > div:first').css('z-index','');
  1470. }
  1471. }
  1472.  
  1473. /**
  1474. * getMediaInfo
  1475. * Get Instagram Media object
  1476. *
  1477. * @param {String} mediaId
  1478. * @return {Object}
  1479. */
  1480. function getMediaInfo(mediaId){
  1481. return new Promise((resolve,reject)=>{
  1482. let getURL = `https://i.instagram.com/api/v1/media/${mediaId}/info/`;
  1483.  
  1484. if(mediaId == null){
  1485. alert("Can not call Media API because of the media id is invalid.");
  1486.  
  1487. updateLoadingBar(false);
  1488. reject(-1);
  1489. return;
  1490. }
  1491. if(getAppID() == null){
  1492. alert("Can not call Media API because of the app id is invalid.");
  1493.  
  1494. updateLoadingBar(false);
  1495. reject(-1);
  1496. return;
  1497. }
  1498.  
  1499. GM_xmlhttpRequest({
  1500. method: "GET",
  1501. url: getURL,
  1502. headers: {
  1503. "User-Agent": window.navigator.userAgent,
  1504. "Accept": "*/*",
  1505. 'X-IG-App-ID': getAppID()
  1506. },
  1507. onload: function(response) {
  1508. if(response.finalUrl == getURL){
  1509. let obj = JSON.parse(response.response);
  1510. resolve(obj);
  1511. }
  1512. else{
  1513. let finalURL = new URL(response.finalUrl);
  1514. if(finalURL.pathname.startsWith('/accounts/login')){
  1515. alert("The account must be logged in to access Media API.");
  1516. }
  1517. else{
  1518. alert('Unable to retrieve content because the API was redirected to "'+response.finalUrl+'"');
  1519. }
  1520. updateLoadingBar(false);
  1521. reject(-1);
  1522. }
  1523. },
  1524. onerror: function(err){
  1525. resolve(err);
  1526. }
  1527. });
  1528. });
  1529. }
  1530.  
  1531. /**
  1532. * getVisibleNodeIndex
  1533. * Get element visible node
  1534. *
  1535. * @param {Object} $main
  1536. * @return {Integer}
  1537. */
  1538. function getVisibleNodeIndex($main){
  1539. var index = 0;
  1540. // homepage classList
  1541. var $dot = $main.find('.x1iyjqo2 > div > div:last-child > div');
  1542.  
  1543. // dialog classList, main top classList
  1544. if($dot == null || !$dot.hasClass('_acnb')){
  1545. $dot = $main.find('._aatk > div > div:last-child').eq(0).children('div');
  1546. }
  1547.  
  1548. $dot.filter('._acnb').each(function(sIndex){
  1549. if($(this).hasClass('_acnf')){
  1550. index = sIndex;
  1551. }
  1552. });
  1553.  
  1554. return index;
  1555. }
  1556.  
  1557. /**
  1558. * createDownloadButton
  1559. * Create a download button in the upper right corner of each post
  1560. *
  1561. * @return {void}
  1562. */
  1563. function createDownloadButton(){
  1564. // Add download icon per each posts
  1565. $('article[class], section:visible > main > div > div > div > div > div > hr').map(function(index){
  1566. return $(this).is('section:visible > main > div > div > div > div > div > hr') ? $(this).parent().parent().parent().parent()[0] : this;
  1567. })
  1568. .each(function(index){
  1569. // If it is have not download icon
  1570. // class x1iyjqo2 mean user profile pages post list container
  1571. if(!$(this).attr('data-snig') && !$(this).hasClass('x1iyjqo2') && !$(this).children('article')?.hasClass('x1iyjqo2') && $(this).parents('div#scrollview').length === 0){
  1572. console.log("Found post container", $(this));
  1573.  
  1574. var rightPos = 15;
  1575. var topPos = 15;
  1576. var $mainElement = $(this);
  1577. var tagName = this.tagName;
  1578.  
  1579. // not loop each in single top post
  1580. if(tagName === "DIV" && index != 0){
  1581. return;
  1582. }
  1583.  
  1584. // New post UI by Discord: ken
  1585. // NOT WORKING
  1586. /*
  1587. if(tagName === "DIV" && $(this).attr('role') === "presentation"){
  1588. rightPos = 28;
  1589. topPos = 75;
  1590. $mainElement = $('div._aap0[role="presentation"]').parents('div._aamm').parent().parent().parent().parent().parent();
  1591. }
  1592. */
  1593.  
  1594. const $childElement = $mainElement.children("div").children("div");
  1595.  
  1596. if($childElement.length === 0) return;
  1597.  
  1598. console.log("Found insert point", $childElement);
  1599.  
  1600. // Modify carousel post counter's position to not interfere with our buttons
  1601. if($mainElement.find('._acay').length > 0){
  1602. if($mainElement.find('._acay + .x24i39r').length > 0){
  1603. $mainElement.find('._acay + .x24i39r').css('top', '37px');
  1604. }
  1605.  
  1606. const observeNode = $mainElement.find('._acay').first().parent()[0];
  1607. var observer = new MutationObserver(function (mutation, owner) {
  1608. $mainElement.find('._acay + .x24i39r').css('top', '37px');
  1609. });
  1610.  
  1611. observer.observe(observeNode, {
  1612. childList: true
  1613. });
  1614. }
  1615.  
  1616. // Add icons
  1617. const DownloadElement = `<div title="${_i18n("DW")}" class="SNKMS_IG_DW_MAIN" style="right:${rightPos}px;top:${topPos}px;">${SVG.DOWNLOAD}</div>`;
  1618. const NewTabElement = `<div title="${_i18n("NEW_TAB")}" class="SNKMS_IG_NEWTAB_MAIN" style="right:${rightPos + 35}px;top:${topPos}px;">${SVG.NEW_TAB}</div>`;
  1619. const ThumbnailElement = `<div title="${_i18n("THUMBNAIL_INTRO")}" class="SNKMS_IG_THUMBNAIL_MAIN" style="right:${rightPos + 70}px;top:${topPos}px;">${SVG.THUMBNAIL}</div>`;
  1620.  
  1621. $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).append(DownloadElement);
  1622. $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).append(NewTabElement);
  1623.  
  1624. setTimeout(()=>{
  1625. // Check if visible post is video
  1626. if($childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).find('div > ul li._acaz').length === 0){
  1627. if($childElement.find('video').length > 0){
  1628. $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).append(ThumbnailElement);
  1629. }
  1630. }
  1631. else{
  1632. const checkVideoNode = function(target){
  1633. if(target){
  1634. var k = $(target).find('li._acaz').length;
  1635. var $targetNode = null;
  1636.  
  1637. if(k == 2){
  1638. var index = getVisibleNodeIndex($mainElement);
  1639. // First node
  1640. if(index === 0){
  1641. $targetNode = $(target).find('li._acaz').first();
  1642. }
  1643. // Last node
  1644. else{
  1645. $targetNode = $(target).find('li._acaz').last();
  1646. }
  1647. }
  1648. // Middle node
  1649. else{
  1650. $targetNode = $(target).find('li._acaz').eq(1);
  1651. }
  1652.  
  1653. // Check if video?
  1654. if($targetNode != null && $targetNode.length > 0 && $targetNode.find('video').length > 0){
  1655. $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).append(ThumbnailElement);
  1656. }
  1657. else{
  1658. $childElement.find('.SNKMS_IG_THUMBNAIL_MAIN')?.remove();
  1659. }
  1660. }
  1661. };
  1662.  
  1663. var observer = new MutationObserver(function (mutation, owner) {
  1664. var target = mutation.at(0)?.target;
  1665. checkVideoNode(target);
  1666. });
  1667.  
  1668. const element = $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).find('div > ul li._acaz')?.parent()[0];
  1669. const elementAttr = $childElement.eq((tagName === "DIV")? 0 : $childElement.length - 2).find('div > ul li._acaz')?.parent().parent()[0];
  1670.  
  1671. if(element){
  1672. checkVideoNode(element);
  1673. observer.observe(element, {
  1674. childList: true
  1675. });
  1676. }
  1677.  
  1678. if(elementAttr){
  1679. observer.observe(elementAttr, {
  1680. attributes: true
  1681. });
  1682. }
  1683. }
  1684. }, 50);
  1685.  
  1686.  
  1687. $childElement.css('position','relative');
  1688.  
  1689. // Disable video autoplay
  1690. if(USER_SETTING.DISABLE_VIDEO_LOOPING){
  1691. $(this).find('video').each(function(){
  1692. if(!$(this).data('loop')){
  1693. console.log('(post) Added video event listener #loop');
  1694. $(this).on('ended',function(){
  1695. $(this).attr('data-loop', true);
  1696. this.pause();
  1697. });
  1698. }
  1699. });
  1700. }
  1701.  
  1702. // Modify Video Volume
  1703. if(USER_SETTING.MODIFY_VIDEO_VOLUME){
  1704. $(this).find('video').each(function(){
  1705. if(!$(this).data('modify')){
  1706. console.log('(post) Added video event listener #modify');
  1707. this.volume = VIDEO_VOLUME;
  1708.  
  1709. $(this).on('play',function(){
  1710. this.volume = VIDEO_VOLUME;
  1711. });
  1712. $(this).on('playing',function(){
  1713. this.volume = VIDEO_VOLUME;
  1714. });
  1715. $(this).on('timeupdate',function(){
  1716. this.volume = VIDEO_VOLUME;
  1717. });
  1718.  
  1719. $(this).attr('data-modify', true);
  1720. }
  1721. });
  1722. }
  1723.  
  1724. if(USER_SETTING.HTML5_VIDEO_CONTROL){
  1725. $(this).find('video').each(function(){
  1726. if(!$(this).data('controls')){
  1727. console.log('(post) Added video html5 contorller #modify');
  1728. this.volume = VIDEO_VOLUME;
  1729.  
  1730. $(this).on('loadstart',function(){
  1731. this.volume = VIDEO_VOLUME;
  1732. });
  1733.  
  1734. $(this).on('volumechange',function(){
  1735. let $element_mute_button = $(this).parent().find('video + div > div').find('button[type="button"], div[role="button"]').filter(function(idx){
  1736. // This is mention others' icon
  1737. return $(this).find('svg > path[d^="M21.334"]').length === 0;
  1738. });
  1739.  
  1740. var is_elelment_muted = $element_mute_button.find('svg > path[d^="M16.636"]').length === 0;
  1741.  
  1742. if(this.muted != is_elelment_muted){
  1743. this.volume = VIDEO_VOLUME;
  1744. $element_mute_button?.click();
  1745. }
  1746.  
  1747. if ($(this).attr('data-completed')){
  1748. VIDEO_VOLUME = this.volume;
  1749. GM_setValue('G_VIDEO_VOLUME', this.volume);
  1750. }
  1751.  
  1752. if(this.volume == VIDEO_VOLUME){
  1753. $(this).attr('data-completed', true);
  1754. }
  1755. });
  1756.  
  1757. $(this).css('position', 'absolute');
  1758. $(this).css('z-index', '2');
  1759. $(this).attr('data-controls', true);
  1760. $(this).attr('controls', true);
  1761. }
  1762. });
  1763. }
  1764.  
  1765.  
  1766. var $buttonParent = $(this).find('video + div > div').first();
  1767. $buttonParent.append('<div class="volume_slider bottom" />');
  1768. $buttonParent.find('div.volume_slider').append(`<div><input type="range" max="1" min="0" step="0.05" value="${VIDEO_VOLUME}" /></div>`);
  1769. $buttonParent.find('div.volume_slider input').attr('style',`--ig-track-progress: ${(VIDEO_VOLUME * 100) + '%'}`);
  1770. $buttonParent.find('div.volume_slider input').on('input',function(){
  1771. var percent = ($(this).val() * 100) + '%';
  1772.  
  1773. VIDEO_VOLUME = $(this).val();
  1774. GM_setValue('G_VIDEO_VOLUME', $(this).val());
  1775.  
  1776. $(this).attr('style',`--ig-track-progress: ${percent}`);
  1777.  
  1778. $mainElement.find('video').each(function(){
  1779. console.log('(post) video volume changed #slider');
  1780. this.volume = VIDEO_VOLUME;
  1781. });
  1782. });
  1783.  
  1784. $buttonParent.find('div.volume_slider input').on('mouseenter',function(){
  1785. var percent = (VIDEO_VOLUME * 100) + '%';
  1786. $(this).attr('style',`--ig-track-progress: ${percent}`);
  1787. $(this).val(VIDEO_VOLUME);
  1788. $mainElement.find('video').each(function(){
  1789. console.log('(post) video volume changed #slider');
  1790. this.volume = VIDEO_VOLUME;
  1791. });
  1792. });
  1793.  
  1794. $buttonParent.find('div.volume_slider').on('click',function(e){
  1795. e.stopPropagation();
  1796. e.preventDefault();
  1797. });
  1798.  
  1799.  
  1800. $(this).on('click', '.SNKMS_IG_THUMBNAIL_MAIN', function(e){
  1801. updateLoadingBar(true);
  1802.  
  1803. GL_username = $(this).parent().parent().parent().attr('data-username');
  1804. 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);
  1805.  
  1806. var $main = $(this).parent().parent().parent();
  1807. var index = getVisibleNodeIndex($main);
  1808.  
  1809. IG_createDM(true, false);
  1810.  
  1811. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", "").then(()=>{
  1812. let checkBlob = setInterval(()=>{
  1813. if($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0){
  1814. clearInterval(checkBlob);
  1815. var $videoThumbnail = $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="'+(index+1)+'"]')?.parent().find('.videoThumbnail')?.first();
  1816.  
  1817. if($videoThumbnail != null && $videoThumbnail.length > 0){
  1818. $videoThumbnail.click();
  1819. }
  1820. else{
  1821. alert('Can not find thumbnail url.');
  1822. }
  1823.  
  1824. updateLoadingBar(false);
  1825. $('.IG_SN_DIG').remove();
  1826. }
  1827. },250);
  1828. });
  1829. });
  1830.  
  1831. $(this).on('click', '.SNKMS_IG_NEWTAB_MAIN', function(e){
  1832. updateLoadingBar(true);
  1833.  
  1834. GL_username = $(this).parent().parent().parent().attr('data-username');
  1835. 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);
  1836.  
  1837. var $main = $(this).parent().parent().parent();
  1838. var index = getVisibleNodeIndex($main);
  1839.  
  1840. IG_createDM(true, false);
  1841.  
  1842. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", "").then(()=>{
  1843. let checkBlob = setInterval(()=>{
  1844. if($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0){
  1845. clearInterval(checkBlob);
  1846. var $linkElement = $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="'+(index+1)+'"]');
  1847.  
  1848. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && USER_SETTING.NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST){
  1849. triggerLinkElement( $linkElement.first()[0], true);
  1850. }
  1851. else{
  1852. let href = $linkElement?.attr('data-href');
  1853. if(href){
  1854. // replace https://instagram.ftpe8-2.fna.fbcdn.net/ to https://scontent.cdninstagram.com/ becase of same origin policy (some video)
  1855. var urlObj = new URL(href);
  1856. urlObj.host = 'scontent.cdninstagram.com';
  1857.  
  1858. openNewTab(urlObj.href);
  1859. }
  1860. else{
  1861. alert('Can not find open tab url.');
  1862. }
  1863. }
  1864.  
  1865. updateLoadingBar(false);
  1866. $('.IG_SN_DIG').remove();
  1867. }
  1868. },250);
  1869. });
  1870. });
  1871.  
  1872. // Running if user click the download icon
  1873. $(this).on('click','.SNKMS_IG_DW_MAIN', async function(e){
  1874. GL_username = $(this).parent().parent().parent().attr('data-username');
  1875. 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);
  1876.  
  1877. // Create element that download dailog
  1878. IG_createDM(USER_SETTING.DIRECT_DOWNLOAD_ALL, true);
  1879.  
  1880. $("#article-id").html(`<a href="https://www.instagram.com/p/${GL_postPath}">${GL_postPath}</a>`);
  1881.  
  1882. if(USER_SETTING.DIRECT_DOWNLOAD_VISIBLE_RESOURCE){
  1883. updateLoadingBar(true);
  1884. IG_setDM(true);
  1885.  
  1886. var index = getVisibleNodeIndex($(this).parent().parent().parent());
  1887.  
  1888. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY", "").then(()=>{
  1889. let checkBlob = setInterval(()=>{
  1890. if($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0){
  1891. clearInterval(checkBlob);
  1892. var href = $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="'+(index+1)+'"]')?.attr('data-href');
  1893.  
  1894. if(href){
  1895. updateLoadingBar(false);
  1896. $('.IG_SN_DIG .IG_SN_DIG_BODY a[data-globalindex="'+(index+1)+'"]')?.click();
  1897. }
  1898. else{
  1899. alert('Can not find download url.');
  1900. }
  1901.  
  1902. $('.IG_SN_DIG').remove();
  1903. }
  1904. },250);
  1905. });
  1906.  
  1907. return;
  1908. }
  1909.  
  1910. if(!USER_SETTING.DIRECT_DOWNLOAD_ALL){
  1911. // Find video/image element and add the download icon
  1912. var s = 0;
  1913. var multiple = $(this).parent().parent().find('._acay ._acaz').length;
  1914. var pathname = window.location.pathname;
  1915. var fullpathname = "/"+pathname.split('/')[1]+"/"+pathname.split('/')[2]+"/";
  1916. var blob = USER_SETTING.FORCE_FETCH_ALL_RESOURCES;
  1917. var publish_time = new Date($(this).parent().parent().find('a[href^="/p/"] time[datetime]').first().attr('datetime')).getTime();
  1918.  
  1919. // If posts have more than one images or videos.
  1920. if(multiple){
  1921. $(this).parent().find('._acay ._acaz').each(function(){
  1922. let element_videos = $(this).parent().parent().find('video');
  1923. //if(element_videos && element_videos.attr('src') && element_videos.attr('src').match(/^blob:/ig)){
  1924. if(element_videos && element_videos.attr('src')){
  1925. blob = true;
  1926. }
  1927. });
  1928.  
  1929.  
  1930. if(blob || USER_SETTING.FORCE_RESOURCE_VIA_MEDIA){
  1931. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_MULTIPLE"));
  1932. }
  1933. else{
  1934. $(this).parent().find('._acay ._acaz').each(function(){
  1935. s++;
  1936. let element_videos = $(this).find('video');
  1937. let element_images = $(this).find('._aagv img');
  1938. let imgLink = (element_images.attr('srcset'))?element_images.attr('srcset').split(" ")[0]:element_images.attr('src');
  1939.  
  1940. if(element_videos && element_videos.attr('src')){
  1941. blob = true;
  1942. }
  1943. if(element_images && imgLink){
  1944. $('.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>`);
  1945. }
  1946.  
  1947. });
  1948.  
  1949. if(blob){
  1950. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_RELOAD"));
  1951. }
  1952. }
  1953. }
  1954. else{
  1955. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA){
  1956. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_MULTIPLE"));
  1957. }
  1958. else{
  1959. s++;
  1960. let element_videos = $(this).parent().parent().find('video');
  1961. let element_images = $(this).parent().parent().find('._aagv img');
  1962. let imgLink = (element_images.attr('srcset'))?element_images.attr('srcset').split(" ")[0]:element_images.attr('src');
  1963.  
  1964.  
  1965. if(element_videos && element_videos.attr('src')){
  1966. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_ONE"));
  1967. }
  1968. if(element_images && imgLink){
  1969. $('.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>`);
  1970. }
  1971. }
  1972. }
  1973. }
  1974.  
  1975. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function(){
  1976. $(this).wrap('<div></div>');
  1977. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  1978. $(this).after(`<div title="${_i18n("NEW_TAB")}" class="newTab">${SVG.NEW_TAB}</div>`);
  1979.  
  1980. if($(this).attr('data-name') == 'video'){
  1981. $(this).after(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="videoThumbnail">${SVG.THUMBNAIL}</div>`);
  1982. }
  1983. });
  1984.  
  1985. if(USER_SETTING.DIRECT_DOWNLOAD_ALL){
  1986. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_MULTIPLE")).then(()=>{
  1987. let checkBlob = setInterval(()=>{
  1988. if($('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').length > 0){
  1989. clearInterval(checkBlob);
  1990. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function(){
  1991. $(this).click();
  1992. });
  1993.  
  1994. $('.IG_SN_DIG').remove();
  1995. }
  1996. },250);
  1997. });
  1998. }
  1999. });
  2000.  
  2001. // Add the mark that download is ready
  2002. var username = $(this).find("header > div:last-child > div:first-child span a").first().text();
  2003.  
  2004. $(this).attr('data-snig','canDownload');
  2005. $(this).attr('data-username',username);
  2006. }
  2007. });
  2008. }
  2009.  
  2010. /**
  2011. * createMediaListDOM
  2012. * Create a list of media elements from post URLs
  2013. *
  2014. * @param {String} postURL
  2015. * @param {String} selector - Use CSS element selectors to choose where it appears.
  2016. * @param {String} message - i18n display loading message
  2017. * @return {void}
  2018. */
  2019. function createMediaListDOM(postURL,selector,message){
  2020. return new Promise(async (resolve) => {
  2021. $(`${selector} a`).remove();
  2022. $(selector).append('<p id="_SNLOAD">'+ message +'</p>');
  2023. let media = await getBlobMedia(postURL);
  2024.  
  2025. let idx = 1;
  2026. let resource = media.shortcode_media;
  2027.  
  2028. // GraphVideo
  2029. if(resource.__typename == "GraphVideo" && resource.video_url){
  2030. $(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>`);
  2031. idx++;
  2032. }
  2033. // GraphImage
  2034. if(resource.__typename == "GraphImage"){
  2035. $(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>`);
  2036. idx++;
  2037. }
  2038. // GraphSidecar
  2039. if(resource.__typename == "GraphSidecar" && resource.edge_sidecar_to_children){
  2040. for(let e of resource.edge_sidecar_to_children.edges){
  2041. if(e.node.__typename == "GraphVideo"){
  2042. $(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>`);
  2043. }
  2044.  
  2045. if(e.node.__typename == "GraphImage"){
  2046. $(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>`);
  2047. }
  2048. idx++;
  2049. }
  2050. }
  2051.  
  2052. $("#_SNLOAD").remove();
  2053. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function(){
  2054. $(this).wrap('<div></div>');
  2055. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  2056. $(this).after(`<div title="${_i18n("NEW_TAB")}" class="newTab">${SVG.NEW_TAB}</div>`);
  2057.  
  2058. if($(this).attr('data-name') == 'video'){
  2059. $(this).after(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="videoThumbnail">${SVG.THUMBNAIL}</div>`);
  2060. }
  2061. });
  2062.  
  2063. resolve(true);
  2064. });
  2065. }
  2066.  
  2067. /**
  2068. * IG_createDM
  2069. * A dialog showing a list of all media files in the post
  2070. *
  2071. * @param {Boolean} hasHidden
  2072. * @param {Boolean} hasCheckbox
  2073. * @return {void}
  2074. */
  2075. function IG_createDM(hasHidden, hasCheckbox){
  2076. let isHidden = (hasHidden)?"hidden":"";
  2077. $('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>');
  2078. $('.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>`);
  2079.  
  2080. if(hasCheckbox){
  2081. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE').append(`<div style="text-align: center;" id="button_group"></div>`);
  2082. $('.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>`);
  2083. $('.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>`);
  2084. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE').append(`<label class="checkbox"><input value="yes" type="checkbox" />${_i18n('ALL_CHECK')}</label>`);
  2085. }
  2086. }
  2087.  
  2088. /**
  2089. * IG_setDM
  2090. * Set a dialog status
  2091. *
  2092. * @param {Boolean} hasHidden
  2093. * @return {void}
  2094. */
  2095. function IG_setDM(hasHidden){
  2096. if($('.IG_SN_DIG').length){
  2097. if(hasHidden){
  2098. $('.IG_SN_DIG').addClass("hidden");
  2099. }
  2100. else{
  2101. $('.IG_SN_DIG').removeClass("hidden");
  2102. }
  2103. }
  2104. }
  2105.  
  2106. /**
  2107. * saveFiles
  2108. * Download the specified media URL to the computer
  2109. *
  2110. * @param {String} downloadLink
  2111. * @param {String} username
  2112. * @param {String} sourceType
  2113. * @param {Integer} timestamp
  2114. * @param {String} filetype
  2115. * @param {String} shortcode
  2116. * @return {void}
  2117. */
  2118. function saveFiles(downloadLink,username,sourceType,timestamp,filetype,shortcode){
  2119. setTimeout(()=>{
  2120. updateLoadingBar(true);
  2121. fetch(downloadLink).then(res => {
  2122. return res.blob().then(dwel => {
  2123. updateLoadingBar(false);
  2124. createSaveFileElement(downloadLink,dwel,username,sourceType,timestamp,filetype,shortcode);
  2125. });
  2126. });
  2127. }, 50);
  2128. }
  2129.  
  2130. /**
  2131. * createSaveFileElement
  2132. * Download the specified media with link element
  2133. *
  2134. * @param {String} downloadLink
  2135. * @param {Object} object
  2136. * @param {String} username
  2137. * @param {String} sourceType
  2138. * @param {Integer} timestamp
  2139. * @param {String} filetype
  2140. * @param {String} shortcode
  2141. * @return {void}
  2142. */
  2143. function createSaveFileElement(downloadLink,object,username,sourceType,timestamp,filetype,shortcode) {
  2144. timestamp = parseInt(timestamp.toString().padEnd(13, '0'));
  2145.  
  2146. if(USER_SETTING.RENAME_PUBLISH_DATE){
  2147. timestamp = parseInt(timestamp.toString().padEnd(13, '0'));
  2148. }
  2149.  
  2150. const date = new Date(timestamp);
  2151.  
  2152. const a = document.createElement("a");
  2153. const original_name = new URL(downloadLink).pathname.split('/').at(-1).split('.').slice(0,-1).join('.');
  2154. const year = date.getFullYear().toString();
  2155. const month = (date.getMonth()+1).toString().padStart(2,'0');
  2156. const day = date.getDate().toString().padStart(2,'0');
  2157. const hour = date.getHours().toString().padStart(2,'0');
  2158. const minute = date.getMinutes().toString().padStart(2,'0');
  2159. const second = date.getSeconds().toString().padStart(2,'0');
  2160.  
  2161. var filename = RENAME_FORMAT.toUpperCase();
  2162. var replacements = {
  2163. '%USERNAME%': username,
  2164. '%SOURCE_TYPE%': sourceType,
  2165. '%SHORTCODE%': (shortcode)?shortcode:'',
  2166. '%YEAR%': year,
  2167. '%MONTH%': month,
  2168. '%DAY%': day,
  2169. '%HOUR%': hour,
  2170. '%MINUTE%': minute,
  2171. '%SECOND%': second,
  2172. '%ORIGINAL_NAME%': original_name
  2173. };
  2174.  
  2175. filename = filename.replace(/%\w+%/g, function(str) {
  2176. return replacements[str] || str;
  2177. });
  2178.  
  2179. const originally = username + '_' + original_name + '.' + filetype;
  2180.  
  2181. a.href = URL.createObjectURL(object);
  2182. a.setAttribute("download", (USER_SETTING.AUTO_RENAME)?filename+'.'+filetype:originally);
  2183. a.click();
  2184. a.remove();
  2185. }
  2186.  
  2187. /**
  2188. * triggerLinkElement
  2189. * Trigger the link element to start downloading the resource
  2190. *
  2191. * @param {Object} element
  2192. * @return {void}
  2193. */
  2194. async function triggerLinkElement(element, isPreview) {
  2195. let date = new Date().getTime();
  2196. let timestamp = Math.floor(date / 1000);
  2197. let username = ($(element).attr('data-username')) ? $(element).attr('data-username') : GL_username;
  2198.  
  2199. if(!username && $(element).attr('data-path')){
  2200. console.log('catching owner name from shortcode:',$(element).attr('data-href'));
  2201. username = await getPostOwner($(element).attr('data-path'));
  2202. }
  2203.  
  2204. if(USER_SETTING.RENAME_PUBLISH_DATE && $(element).attr('datetime')){
  2205. timestamp = parseInt($(element).attr('datetime'));
  2206. }
  2207.  
  2208. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA){
  2209. updateLoadingBar(true);
  2210. let result = await getMediaInfo($(element).attr('media-id'));
  2211. updateLoadingBar(false);
  2212.  
  2213. if(result.status === 'ok'){
  2214. var resource_url = null;
  2215. if(result.items[0].video_versions){
  2216. resource_url = result.items[0].video_versions[0].url;
  2217. }
  2218. else{
  2219. resource_url = result.items[0].image_versions2.candidates[0].url;
  2220. }
  2221.  
  2222. if(isPreview){
  2223. let urlObj = new URL(resource_url);
  2224. urlObj.host = 'scontent.cdninstagram.com';
  2225.  
  2226. openNewTab(urlObj.href);
  2227. }
  2228. else{
  2229. saveFiles(resource_url, username, $(element).attr('data-name'),timestamp, $(element).attr('data-type'), $(element).attr('data-path'));
  2230. }
  2231. }
  2232. else{
  2233. if(USER_SETTING.USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT){
  2234. if(isPreview){
  2235. let urlObj = new URL($(element).attr('data-href'));
  2236. urlObj.host = 'scontent.cdninstagram.com';
  2237.  
  2238. openNewTab(urlObj.href);
  2239. }
  2240. else{
  2241. saveFiles($(element).attr('data-href'),username,$(element).attr('data-name'),timestamp,$(element).attr('data-type'), $(element).attr('data-path'));
  2242. }
  2243. }
  2244. else{
  2245. alert('Fetch failed from Media API. API response message: ' + result.message);
  2246. }
  2247. console.log(result);
  2248. }
  2249. }
  2250. else{
  2251. saveFiles($(element).attr('data-href'),username,$(element).attr('data-name'),timestamp,$(element).attr('data-type'), $(element).attr('data-path'));
  2252. }
  2253. }
  2254.  
  2255. /**
  2256. * translateText
  2257. * i18n translation text
  2258. *
  2259. * @param {String} lang
  2260. * @return {void}
  2261. */
  2262. function translateText(lang){
  2263. var eLocale = {
  2264. "en-US": {
  2265. "SELECT_LANG": "English",
  2266. "RELOAD_SCRIPT": "Reload Script",
  2267. "DONATE": "Donate",
  2268. "FEEDBACK": "Feedback",
  2269. "NEW_TAB": "Open in new tab",
  2270. "SHOW_DOM_TREE": "Show DOM Tree",
  2271. "SELECT_AND_COPY": "Select All and Copy of the Input Box",
  2272. "DOWNLOAD_DOM_TREE": "Download DOM Tree as Text File",
  2273. "REPORT_GITHUB": "Report Issue On GitHub",
  2274. "REPORT_DISCORD": "Report Issue On Discord Support Server",
  2275. "DEBUG": "Debug Window",
  2276. "CLOSE": "Close",
  2277. "ALL_CHECK": "Select All",
  2278. "BATCH_DOWNLOAD_SELECTED": "Download Selected Resources",
  2279. "BATCH_DOWNLOAD_DIRECT": "Download All Resources",
  2280. "IMG": "Image",
  2281. "VID": "Video",
  2282. "DW": "Download",
  2283. "THUMBNAIL_INTRO": "Download video thumbnail",
  2284. "LOAD_BLOB_ONE": "Loading Blob Media...",
  2285. "LOAD_BLOB_MULTIPLE": "Loading Blob Media and others...",
  2286. "LOAD_BLOB_RELOAD": "Detect Blob Media, now reloading...",
  2287. "NO_CHECK_RESOURCE": "You need to check resource to download.",
  2288. "NO_VID_URL": "Can not find video url.",
  2289. "SETTING": "Settings",
  2290. "AUTO_RENAME": "Automatically Rename Files (Right-Click To Set)",
  2291. "RENAME_SHORTCODE": "Rename The File and Include Shortcode",
  2292. "RENAME_PUBLISH_DATE": "Set Rename File Timestamp to Resource Publish Date",
  2293. "RENAME_LOCATE_DATE": "Modify Renamed File Timestamp Date Format (Right-Click To Set)",
  2294. "DISABLE_VIDEO_LOOPING": "Disable Video Auto-looping",
  2295. "HTML5_VIDEO_CONTROL": "Display HTML5 Video Controller",
  2296. "REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE": "Redirect When Right-Clicking User Story Picture",
  2297. "FORCE_FETCH_ALL_RESOURCES": "Forcing Fetch All Resources In the Post",
  2298. "DIRECT_DOWNLOAD_VISIBLE_RESOURCE": "Directly Download the Visible Resources In the Post",
  2299. "DIRECT_DOWNLOAD_ALL": "Directly Download All Resources In the Post",
  2300. "MODIFY_VIDEO_VOLUME": "Modify Video Volume (Right-Click To Set)",
  2301. "SCROLL_BUTTON": "Enable Scroll Buttons For Reels Page",
  2302. "FORCE_RESOURCE_VIA_MEDIA": "Force Fetch Resource via Media API",
  2303. "USE_BLOB_FETCH_WHEN_MEDIA_RATE_LITMIT": "Use Other Methods to Download When the Media API is Not Accessible",
  2304. "NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST": '"Open in new tab" in posts always uses Media API',
  2305. "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",
  2306. "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.",
  2307. "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.",
  2308. "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.",
  2309. "DISABLE_VIDEO_LOOPING_INTRO": "Disable video auto-looping in reels and posts.",
  2310. "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.",
  2311. "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.",
  2312. "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.",
  2313. "DIRECT_DOWNLOAD_VISIBLE_RESOURCE_INTRO": "Directly download the current resources in the post.",
  2314. "DIRECT_DOWNLOAD_ALL_INTRO": "When you click the download button, all resources in the post will be directly forced to be fetched and downloaded.",
  2315. "MODIFY_VIDEO_VOLUME_INTRO": "Modify the video playback volume in Reels and Posts (right-click to open the volume setting slider).",
  2316. "SCROLL_BUTTON_INTRO": "Enable scroll buttons for the lower right corner of Reels page.",
  2317. "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.",
  2318. "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).",
  2319. "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."
  2320. }
  2321. };
  2322.  
  2323. var resultUnsorted = Object.assign({}, eLocale, locale);
  2324. var resultSorted = Object.keys(resultUnsorted).sort().reduce(
  2325. (obj, key) => {
  2326. obj[key] = resultUnsorted[key];
  2327. return obj;
  2328. }, {}
  2329. );
  2330.  
  2331. return resultSorted;
  2332. }
  2333.  
  2334. /**
  2335. * _i18n
  2336. * Perform i18n translation
  2337. *
  2338. * @param {String} text
  2339. * @return {void}
  2340. */
  2341. function _i18n(text){
  2342. const translate = translateText();
  2343.  
  2344. if(translate[lang] != undefined && translate[lang][text] != undefined){
  2345. return translate[lang][text];
  2346. }
  2347. else{
  2348. return translate["en-US"][text];
  2349. }
  2350. }
  2351.  
  2352. /**
  2353. * showSetting
  2354. * Show script settings window
  2355. *
  2356. * @return {void}
  2357. */
  2358. function showSetting(){
  2359. $('.IG_SN_DIG').remove();
  2360. IG_createDM();
  2361. $('.IG_SN_DIG #post_info').text('Preference Settings');
  2362.  
  2363. $('.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>');
  2364.  
  2365. for(let o in translateText()){
  2366. $('.IG_SN_DIG .IG_SN_DIG_TITLE > div #langSelect').append(`<option value="${o}" ${(lang == o)?'selected':''}>${translateText()[o].SELECT_LANG}</option>`);
  2367. }
  2368.  
  2369. for(let name in USER_SETTING){
  2370. $('.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>`);
  2371.  
  2372. if(name === 'MODIFY_VIDEO_VOLUME'){
  2373. $('.IG_SN_DIG .IG_SN_DIG_BODY input[id="'+name+'"]').parent('label').on('contextmenu', function(e){
  2374. e.preventDefault();
  2375. if($(this).find('#tempWrapper').length === 0){
  2376. $(this).append('<div id="tempWrapper"></div>');
  2377. $(this).children('#tempWrapper').append('<input value="' + VIDEO_VOLUME + '" type="range" min="0" max="1" step="0.05" />');
  2378. $(this).children('#tempWrapper').append('<input value="' + VIDEO_VOLUME + '" step="0.05" type="number" />');
  2379. $(this).children('#tempWrapper').append(`<div class="IG_SN_DIG_BTN">${SVG.CLOSE}</div>`);
  2380. }
  2381. });
  2382. }
  2383.  
  2384. if(name === 'AUTO_RENAME'){
  2385. $('.IG_SN_DIG .IG_SN_DIG_BODY input[id="'+name+'"]').parent('label').on('contextmenu', function(e){
  2386. e.preventDefault();
  2387. if($(this).find('#tempWrapper').length === 0){
  2388. $(this).append('<div id="tempWrapper"></div>');
  2389.  
  2390. $(this).children('#tempWrapper').append('<input id="date_format" value="' + RENAME_FORMAT + '" />');
  2391. $(this).children('#tempWrapper').append(`<div class="IG_SN_DIG_BTN">${SVG.CLOSE}</div>`);
  2392. }
  2393. });
  2394. }
  2395. }
  2396. }
  2397.  
  2398. /**
  2399. * showDebugDOM
  2400. * Show full DOM tree
  2401. *
  2402. * @return {void}
  2403. */
  2404. function showDebugDOM(){
  2405. $('.IG_SN_DIG').remove();
  2406. IG_createDM();
  2407. $('.IG_SN_DIG #post_info').text('IG Debug DOM Tree');
  2408.  
  2409. $('.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>`);
  2410. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<span style="display:block;text-align:center;">`);
  2411. $('.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>`);
  2412. $('.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>`);
  2413. $('.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/>`);
  2414. $('.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>`);
  2415. $('.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>`);
  2416. }
  2417.  
  2418. /**
  2419. * openNewTab
  2420. * Open url in new tab
  2421. *
  2422. * @param {String} link
  2423. * @return {void}
  2424. */
  2425. function openNewTab(link){
  2426. var a = document.createElement('a');
  2427. a.href = link;
  2428. a.target = '_blank';
  2429.  
  2430. document.body.appendChild(a);
  2431. a.click();
  2432. a.remove();
  2433. }
  2434.  
  2435. /**
  2436. * reloadScript
  2437. * Re-register main timer
  2438. *
  2439. * @return {void}
  2440. */
  2441. function reloadScript(){
  2442. clearInterval(GL_repeat);
  2443. pageLoaded = false;
  2444. firstStarted = false;
  2445. currentURL = location.href;
  2446. GL_observer.disconnect();
  2447.  
  2448. console.log('main timer re-register completed');
  2449. }
  2450.  
  2451. /**
  2452. * initSettings
  2453. * Initialize preferences
  2454. *
  2455. * @return {void}
  2456. */
  2457. function initSettings(){
  2458. for(let name in USER_SETTING){
  2459. if(GM_getValue(name) != null && typeof GM_getValue(name) === 'boolean'){
  2460. USER_SETTING[name] = GM_getValue(name);
  2461. }
  2462. }
  2463. }
  2464.  
  2465. // Running if document is ready
  2466. $(function(){
  2467. $('body').on('click','.IG_SN_DIG .IG_SN_DIG_BODY .IG_DISPLAY_DOM_TREE',function(){
  2468. let text = $('div[id^="mount"]')[0];
  2469. $('.IG_SN_DIG .IG_SN_DIG_BODY textarea').text("Location: " + location.pathname + "\nDOM Tree:\n" + text.innerHTML);
  2470. });
  2471.  
  2472. $('body').on('click','.IG_SN_DIG .IG_SN_DIG_BODY .IG_SELECT_DOM_TREE',function(){
  2473. $('.IG_SN_DIG .IG_SN_DIG_BODY textarea').select();
  2474. document.execCommand('copy');
  2475. });
  2476.  
  2477. $('body').on('click','.IG_SN_DIG .IG_SN_DIG_BODY .IG_DOWNLOAD_DOM_TREE',function(){
  2478. 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;
  2479. var a = document.createElement("a");
  2480. var file = new Blob([text], {type: "text/plain"});
  2481. a.href = URL.createObjectURL(file);
  2482. a.download = "DOMTree.txt";
  2483.  
  2484. document.body.appendChild(a);
  2485. a.click();
  2486. a.remove();
  2487. });
  2488.  
  2489. // Close the download dialog if user click the close icon
  2490. $('body').on('click','.IG_SN_DIG_BTN, .IG_SN_DIG_BG',function(){
  2491. if($(this).parent('#tempWrapper').length > 0){
  2492. $(this).parent('#tempWrapper').fadeOut(250, function(){
  2493. $(this).remove();
  2494. });
  2495. }
  2496. else{
  2497. $('.IG_SN_DIG').remove();
  2498. }
  2499. });
  2500.  
  2501. $(window).keydown(function(e){
  2502. // Hot key [Alt+Q] to close the download dialog
  2503. if (e.keyCode == '81' && e.altKey){
  2504. $('.IG_SN_DIG').remove();
  2505. e.preventDefault();
  2506. }
  2507. // Hot key [Alt+W] to open the settings dialog
  2508. if (e.keyCode == '87' && e.altKey){
  2509. showSetting();
  2510. e.preventDefault();
  2511. }
  2512.  
  2513. // Hot key [Alt+Z] to open the settings dialog
  2514. if (e.keyCode == '90' && e.altKey){
  2515. showDebugDOM();
  2516. e.preventDefault();
  2517. }
  2518.  
  2519. // Hot key [Alt+R] to open the settings dialog
  2520. if (e.keyCode == '82' && e.altKey){
  2521. reloadScript();
  2522. e.preventDefault();
  2523. }
  2524. });
  2525.  
  2526. $('body').on('change', '.IG_SN_DIG input',function(e){
  2527. var name = $(this).attr('id');
  2528.  
  2529. if(name && USER_SETTING[name] !== undefined){
  2530. let isChecked = $(this).prop('checked');
  2531. GM_setValue(name, isChecked);
  2532. USER_SETTING[name] = isChecked;
  2533.  
  2534. console.log('user settings', name, isChecked);
  2535. }
  2536. });
  2537.  
  2538. $('body').on('click', '.IG_SN_DIG .globalSettings',function(e){
  2539. if($(this).find('#tempWrapper').length > 0){
  2540. e.preventDefault();
  2541. }
  2542. });
  2543.  
  2544. $('body').on('change', '.IG_SN_DIG #tempWrapper input:not(#date_format)',function(){
  2545. let value = $(this).val();
  2546.  
  2547. if($(this).attr('type') == 'range'){
  2548. $(this).next().val(value);
  2549. }
  2550. else{
  2551. $(this).prev().val(value);
  2552. }
  2553.  
  2554. if(value >= 0 && value <= 1){
  2555. VIDEO_VOLUME = value;
  2556. GM_setValue('G_VIDEO_VOLUME', value);
  2557. }
  2558. });
  2559.  
  2560. $('body').on('input', '.IG_SN_DIG #tempWrapper input:not(#date_format)',function(e){
  2561. if($(this).attr('type') == 'range'){
  2562. let value = $(this).val();
  2563. $(this).next().val(value);
  2564. }
  2565. else{
  2566. let value = $(this).val();
  2567. if(value >= 0 && value <= 1){
  2568. $(this).prev().val(value);
  2569. }
  2570. else{
  2571. if(value < 0){
  2572. $(this).val(0);
  2573. }
  2574. else{
  2575. $(this).val(1);
  2576. }
  2577. }
  2578. }
  2579. });
  2580.  
  2581. $('body').on('input', '.IG_SN_DIG #tempWrapper input#date_format',function(e){
  2582. GM_setValue('G_RENAME_FORMAT', $(this).val());
  2583. RENAME_FORMAT = $(this).val();
  2584. });
  2585.  
  2586. $('body').on('click','a[data-needed="direct"]', function(e){
  2587. e.preventDefault();
  2588. triggerLinkElement(this);
  2589. });
  2590.  
  2591. $('body').on('click','.IG_SN_DIG_BODY .newTab', function(){
  2592. // replace https://instagram.ftpe8-2.fna.fbcdn.net/ to https://scontent.cdninstagram.com/ becase of same origin policy (some video)
  2593.  
  2594. if(USER_SETTING.FORCE_RESOURCE_VIA_MEDIA && USER_SETTING.NEW_TAB_ALWAYS_FORCE_MEDIA_IN_POST){
  2595. triggerLinkElement( $(this).parent().children('a').first()[0], true);
  2596. }
  2597. else{
  2598. var urlObj = new URL($(this).parent().children('a').attr('data-href'));
  2599. urlObj.host = 'scontent.cdninstagram.com';
  2600.  
  2601. openNewTab(urlObj.href);
  2602. }
  2603. });
  2604.  
  2605. $('body').on('click','.IG_SN_DIG_BODY .videoThumbnail', function(){
  2606. 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());
  2607. });
  2608.  
  2609. // Running if user left-click download icon in stories
  2610. $('body').on('click','.IG_DWSTORY',function(){
  2611. onStory(true);
  2612. });
  2613.  
  2614. // Running if user left-click 'open in new tab' icon in stories
  2615. $('body').on('click','.IG_DWNEWTAB',function(e){
  2616. e.preventDefault();
  2617. onStory(true, true, true);
  2618. });
  2619.  
  2620. // Running if user left-click download thumbnail icon in stories
  2621. $('body').on('click','.IG_DWSTORY_THUMBNAIL',function(){
  2622. onStoryThumbnail(true);
  2623. });
  2624.  
  2625. // Running if user left-click download icon in profile
  2626. $('body').on('click','.IG_DWPROFILE',function(e){
  2627. e.stopPropagation();
  2628. onProfileAvatar(true);
  2629. });
  2630.  
  2631. // Running if user left-click download icon in highlight stories
  2632. $('body').on('click','.IG_DWHISTORY',function(){
  2633. onHighlightsStory(true);
  2634. });
  2635.  
  2636. // Running if user left-click 'open in new tab' icon in highlight stories
  2637. $('body').on('click','.IG_DWHINEWTAB',function(e){
  2638. e.preventDefault();
  2639. onHighlightsStory(true, true);
  2640. });
  2641.  
  2642. // Running if user left-click thumbnail download icon in highlight stories
  2643. $('body').on('click','.IG_DWHISTORY_THUMBNAIL',function(){
  2644. onHighlightsStoryThumbnail(true);
  2645. });
  2646.  
  2647. // Running if user left-click download icon in reels
  2648. $('body').on('click','.IG_REELS',function(){
  2649. onReels(true,true);
  2650. });
  2651.  
  2652. // Running if user left-click newtab icon in reels
  2653. $('body').on('click','.IG_REELS_NEWTAB',function(){
  2654. onReels(true,true,true);
  2655. });
  2656.  
  2657. // Running if user left-click download icon in reels
  2658. $('body').on('click','.IG_REELS_THUMBNAIL',function(){
  2659. onReels(true,false);
  2660. });
  2661.  
  2662. // Running if user right-click profile picture in stories area
  2663. $('body').on('mousedown','button[role="menuitem"]',function(e){
  2664. // Right-Click || Middle-Click
  2665. if(e.which === 3 || e.which === 2){
  2666. if(location.href === 'https://www.instagram.com/' && USER_SETTING.REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE){
  2667. e.preventDefault();
  2668. if($(this).find('canvas._aarh').length > 0){
  2669. const targetUrl = 'https://www.instagram.com/'+$(this).children('div').last().text();
  2670. if(e.which === 2){
  2671. GM_openInTab(targetUrl);
  2672. }
  2673. else{
  2674. location.href = targetUrl;
  2675. }
  2676. }
  2677. }
  2678. }
  2679. });
  2680.  
  2681. $('body').on('change', '.IG_SN_DIG_TITLE .checkbox', function(){
  2682. var isChecked = $(this).find('input').prop('checked');
  2683. $('.IG_SN_DIG_BODY .inner_box').each(function(){
  2684. $(this).prop('checked', isChecked);
  2685. });
  2686. });
  2687.  
  2688. $('body').on('change', '.IG_SN_DIG_BODY .inner_box', function(){
  2689. var checked = $('.IG_SN_DIG_BODY .inner_box:checked').length;
  2690. var total = $('.IG_SN_DIG_BODY .inner_box').length;
  2691.  
  2692.  
  2693. $('.IG_SN_DIG_TITLE .checkbox').find('input').prop('checked', checked == total);
  2694. });
  2695.  
  2696. $('body').on('click', '.IG_SN_DIG_TITLE #batch_download_selected', function(){
  2697. let index = 0;
  2698. $('.IG_SN_DIG_BODY a[data-needed="direct"]').each(function(){
  2699. if($(this).prev().children('input').prop('checked')){
  2700. $(this).click();
  2701. index++;
  2702. }
  2703. });
  2704.  
  2705. if(index == 0){
  2706. alert(_i18n('NO_CHECK_RESOURCE'));
  2707. }
  2708. });
  2709.  
  2710. $('body').on('change', '.IG_SN_DIG_TITLE #langSelect', function(){
  2711. GM_setValue('lang', $(this).val());
  2712. lang = $(this).val();
  2713.  
  2714. showSetting();
  2715. });
  2716.  
  2717. $('body').on('change', '.IG_SN_DIG_BODY #locateSelect', function(){
  2718. $('#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('/','-')}`);
  2719. LOCATE_DATE_FORMAT = $(this).val();
  2720. GM_setValue('G_LOCATE_DATE_FORMAT', $(this).val());
  2721. });
  2722.  
  2723. $('body').on('click', '.IG_SN_DIG_TITLE #batch_download_direct', function(){
  2724. $('.IG_SN_DIG_BODY a[data-needed="direct"]').each(function(){
  2725. $(this).click();
  2726. });
  2727. });
  2728. });
  2729. })(jQuery);