IG Helper

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

Verze ze dne 08. 01. 2025. Zobrazit nejnovější verzi.

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