IG Helper

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

2025-01-09 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

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