IG小助手

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

当前为 2024-11-18 提交的版本,查看 最新版本

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