IG Helper

Downloading is possible for both photos and videos from posts, as well as for stories, reels or profile picture.

As of 2024-11-23. See the latest version.

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