IG小助手

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

当前为 2023-11-24 提交的版本,查看 最新版本

  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.11.8
  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. // @author SN-Koarashi (5026)
  15. // @match https://*.instagram.com/*
  16. // @grant GM_addStyle
  17. // @grant GM_setValue
  18. // @grant GM_getValue
  19. // @grant GM_xmlhttpRequest
  20. // @grant GM_registerMenuCommand
  21. // @grant GM_getResourceText
  22. // @connect i.instagram.com
  23. // @require https://code.jquery.com/jquery-3.6.3.min.js#sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=
  24. // @resource INTERNAL_CSS https://raw.githubusercontent.com/SN-Koarashi/ig-helper/master/style.css
  25. // @supportURL https://github.com/SN-Koarashi/ig-helper/
  26. // @contributionURL https://ko-fi.com/snkoarashi
  27. // @icon https://www.google.com/s2/favicons?domain=www.instagram.com
  28. // @compatible firefox >= 87
  29. // @compatible chrome >= 90
  30. // @compatible edge >= 90
  31. // @license GPL-3.0-only
  32. // ==/UserScript==
  33.  
  34. (function($) {
  35. 'use strict';
  36. // Icon download by https://www.flaticon.com/authors/pixel-perfect
  37.  
  38. /******** USER SETTINGS ********/
  39. // !!! DO NOT CHANGE THIS AREA !!!
  40. // PLEASE CHANGE SETTING WITH MENU
  41. const USER_SETTING = {
  42. 'AUTO_RENAME': (GM_getValue('AUTO_RENAME'))?GM_getValue('AUTO_RENAME'):true,
  43. 'RENAME_SHORTCODE': (GM_getValue('RENAME_SHORTCODE'))?GM_getValue('RENAME_SHORTCODE'):true,
  44. 'DISABLE_VIDEO_LOOPING': (GM_getValue('DISABLE_VIDEO_LOOPING'))?GM_getValue('DISABLE_VIDEO_LOOPING'):false,
  45. 'REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE': (GM_getValue('REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE'))?GM_getValue('REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE'):false,
  46. 'FORCE_FETCH_ALL_RESOURCES': (GM_getValue('FORCE_FETCH_ALL_RESOURCES'))?GM_getValue('FORCE_FETCH_ALL_RESOURCES'):false
  47. };
  48. /*******************************/
  49.  
  50. const checkInterval = 250;
  51. const lang = navigator.language || navigator.userLanguage;
  52. const style = GM_getResourceText("INTERNAL_CSS");
  53.  
  54. GM_addStyle(style);
  55. GM_registerMenuCommand(_i18n('SETTING'), () => {
  56. showSetting();
  57. });
  58.  
  59. var currentURL = location.href;
  60. var currentHeight = $(document).height();
  61. var firstStarted = false;
  62. var pageLoaded = false;
  63.  
  64. var GL_postPath;
  65. var GL_username;
  66. var GL_repeat;
  67. var GL_dataCache = {
  68. stories: {},
  69. highlights: {}
  70. };
  71.  
  72. // Main Timer
  73. var timer = setInterval(function(){
  74. currentHeight = $(document).height();
  75. // Call Instagram dialog function if url changed.
  76. if(currentURL != location.href || !firstStarted || !pageLoaded){
  77. clearInterval(GL_repeat);
  78. pageLoaded = false;
  79. firstStarted = true;
  80. currentURL = location.href;
  81.  
  82. if(location.href.startsWith("https://www.instagram.com/p/") || location.href.startsWith("https://www.instagram.com/reel/")){
  83. GL_dataCache.stories = {};
  84.  
  85. console.log('isDialog');
  86. setTimeout(()=>{
  87. onReadyMyDW(false);
  88. },150);
  89. pageLoaded = true;
  90. }
  91.  
  92. if(location.href.startsWith("https://www.instagram.com/reels/")){
  93. console.log('isReels');
  94. setTimeout(()=>{
  95. onReels(false);
  96. },150);
  97. pageLoaded = true;
  98. }
  99.  
  100. if(location.href.split("?")[0] == "https://www.instagram.com/"){
  101. GL_dataCache.stories = {};
  102.  
  103. console.log('isHomepage');
  104. setTimeout(()=>{
  105. onReadyMyDW(false);
  106. },150);
  107. pageLoaded = true;
  108. }
  109. if($('div[id^="mount"] > div > div > div').first().is(':hidden') && $('canvas._aarh').length && location.href.match(/^(https:\/\/www\.instagram\.com\/)([0-9A-Za-z\.\-_]+)\/?$/ig) && !location.href.match(/^(https:\/\/www\.instagram\.com\/(stories|explore)\/?)/ig)){
  110. console.log('isProfile');
  111. setTimeout(()=>{
  112. onProfileAvatar(false);
  113. },150);
  114. pageLoaded = true;
  115. }
  116.  
  117. if(!pageLoaded){
  118. // Call Instagram stories function
  119. if(location.href.match(/^(https:\/\/www\.instagram\.com\/stories\/highlights\/)/ig)){
  120. GL_dataCache.highlights = {};
  121.  
  122. console.log('isHighlightsStory');
  123. onHighlightsStory(false);
  124. GL_repeat = setInterval(()=>{
  125. onHighlightsStoryThumbnail(false);
  126. },checkInterval);
  127.  
  128. if($(".IG_DWHISTORY").length) setTimeout(()=>{pageLoaded = true;},150);
  129. }
  130. else if(location.href.match(/^(https:\/\/www\.instagram\.com\/stories\/)/ig)){
  131. console.log('isStory');
  132. onStory(false);
  133. onStoryThumbnail(false);
  134.  
  135. if($(".IG_DWSTORY").length) setTimeout(()=>{pageLoaded = true;},150);
  136. }
  137. else{
  138. pageLoaded = false;
  139. // Remove the download icon
  140. $('.IG_DWSTORY').remove();
  141. $('.IG_DWSTORY_THUMBNAIL').remove();
  142. }
  143. }
  144.  
  145. }
  146. },checkInterval);
  147.  
  148. // Call general function when user scroll the page
  149. $(document).scroll(function(){
  150. if(currentHeight != $(this).height() && location.href.split("?")[0] == "https://www.instagram.com/"){
  151. onReadyMyDW();
  152. }
  153. });
  154.  
  155. /**
  156. * onProfileAvatar
  157. * Trigger user avatar download event or button display event.
  158. *
  159. * @param {Boolean} isDownload - Check if it is a download operation
  160. * @return {void}
  161. */
  162. async function onProfileAvatar(isDownload){
  163. if(isDownload){
  164. let date = new Date().getTime();
  165. let timestamp = Math.floor(date / 1000);
  166. let username = location.href.replace(/\/$/ig,'').split('/').at(-1);
  167. let userInfo = await getUserId(username);
  168. try{
  169. let dataURL = await getUserHighSizeProfile(userInfo.user.pk);
  170. saveFiles(dataURL,username,"avatar",timestamp,'jpg');
  171. }
  172. catch(err){
  173. saveFiles(userInfo.user.profile_pic_url,username,"avatar",timestamp,'jpg');
  174. }
  175. }
  176. else{
  177. // Add the profile download button
  178. if(!$('.IG_DWPROFILE').length){
  179. let profileTimer = setInterval(()=>{
  180. if($('.IG_DWPROFILE').length) clearInterval(profileTimer);
  181.  
  182. $('body > div main canvas._aarh').parent().append(`<div title="${_i18n("DW")}" class="IG_DWPROFILE"><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></div>`);
  183. },150);
  184. }
  185. }
  186. }
  187.  
  188. /**
  189. * onHighlightsStory
  190. * Trigger user's highlight download event or button display event.
  191. *
  192. * @param {Boolean} isDownload - Check if it is a download operation
  193. * @return {void}
  194. */
  195. async function onHighlightsStory(isDownload){
  196. if(isDownload){
  197. let date = new Date().getTime();
  198. let timestamp = Math.floor(date / 1000);
  199. let highlightId = location.href.replace(/\/$/ig,'').split('/').at(-1);
  200. let nowIndex = $("body > div section._ac0a header._ac0k > ._ac3r ._ac3n ._ac3p[style]").length;
  201. let username = "";
  202. let target = 0;
  203.  
  204. if(GL_dataCache.highlights[highlightId]){
  205. console.log('Fetch from memory cache:', highlightId);
  206.  
  207. let totIndex = GL_dataCache.highlights[highlightId].data.reels_media[0].items.length;
  208. username = GL_dataCache.highlights[highlightId].data.reels_media[0].owner.username;
  209. target = GL_dataCache.highlights[highlightId].data.reels_media[0].items[totIndex-nowIndex];
  210. }
  211. else{
  212. let highStories = await getHighlightStories(highlightId);
  213. let totIndex = highStories.data.reels_media[0].items.length;
  214. username = highStories.data.reels_media[0].owner.username;
  215. target = highStories.data.reels_media[0].items[totIndex-nowIndex];
  216.  
  217. GL_dataCache.highlights[highlightId] = highStories;
  218. }
  219.  
  220. if(target.is_video){
  221. saveFiles(target.video_resources.at(-1).src,username,"highlights",timestamp,'mp4', highlightId);
  222. }
  223. else{
  224. saveFiles(target.display_resources.at(-1).src,username,"highlights",timestamp,'jpg', highlightId);
  225. }
  226. }
  227. else{
  228. // Add the stories download button
  229. if(!$('.IG_DWHISTORY').length){
  230. let $element = null;
  231. if($('body > div section._ac0a').length > 0){
  232. $element = $('body > div section._ac0a');
  233. }
  234. else{
  235. $element = $('body > div section > div > div:not([class])');
  236. }
  237.  
  238. if($element != null){
  239. $element.css('position','relative');
  240. $element.append(`<div title="${_i18n("DW")}" class="IG_DWHISTORY"><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></div>`);
  241. }
  242. }
  243. }
  244. }
  245.  
  246. /**
  247. * onHighlightsStoryThumbnail
  248. * Trigger user's highlight video thumbnail download event or button display event.
  249. *
  250. * @param {Boolean} isDownload - Check if it is a download operation
  251. * @return {void}
  252. */
  253. async function onHighlightsStoryThumbnail(isDownload){
  254. if(isDownload){
  255. let date = new Date().getTime();
  256. let timestamp = Math.floor(date / 1000);
  257. let highlightId = location.href.replace(/\/$/ig,'').split('/').at(-1);
  258. let username = "";
  259. let nowIndex = $("body > div section._ac0a header._ac0k > ._ac3r ._ac3n ._ac3p[style]").length;
  260. let target = "";
  261.  
  262. if(GL_dataCache.highlights[highlightId]){
  263. console.log('Fetch from memory cache:', highlightId);
  264.  
  265. let totIndex = GL_dataCache.highlights[highlightId].data.reels_media[0].items.length;
  266. username = GL_dataCache.highlights[highlightId].data.reels_media[0].owner.username;
  267. target = GL_dataCache.highlights[highlightId].data.reels_media[0].items[totIndex-nowIndex];
  268. }
  269. else{
  270. let highStories = await getHighlightStories(highlightId);
  271. let totIndex = highStories.data.reels_media[0].items.length;
  272. username = highStories.data.reels_media[0].owner.username;
  273. target = highStories.data.reels_media[0].items[totIndex-nowIndex];
  274.  
  275. GL_dataCache.highlights[highlightId] = highStories;
  276. }
  277.  
  278. saveFiles(target.display_resources.at(-1).src,username,"highlights",timestamp,'jpg', highlightId);
  279. }
  280. else{
  281. if($('body > div section video.xh8yej3').length){
  282. // Add the stories download button
  283. if(!$('.IG_DWHISTORY_THUMBNAIL').length){
  284. let $element = null;
  285. if($('body > div section._ac0a').length > 0){
  286. $element = $('body > div section._ac0a');
  287. }
  288. else{
  289. $element = $('body > div section > div > div:not([class])');
  290. }
  291.  
  292. if($element != null){
  293. $element.css('position','relative');
  294. $element.append(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="IG_DWHISTORY_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></div>`);
  295. }
  296. }
  297. }
  298. else{
  299. $('.IG_DWHISTORY_THUMBNAIL').remove();
  300. }
  301. }
  302. }
  303.  
  304. /**
  305. * onStory
  306. * Trigger user's story download event or button display event.
  307. *
  308. * @param {Boolean} isDownload - Check if it is a download operation
  309. * @return {void}
  310. */
  311. async function onStory(isDownload,isForce){
  312. if(isDownload){
  313. let date = new Date().getTime();
  314. let timestamp = Math.floor(date / 1000);
  315. let username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split('/').at(2);
  316.  
  317. if($('body > div section._ac0a div._ac0b video.x1lliihq').length){
  318. // Download stories if it is video
  319. let type = "mp4";
  320. let videoURL = "";
  321. let targetURL = location.href.replace(/\/$/ig,'').split("/").at(-1);
  322.  
  323. if(GL_dataCache.stories[username] && !isForce){
  324. console.log('Fetch from memory cache:', username);
  325. GL_dataCache.stories[username].data.reels_media[0].items.forEach(item => {
  326. if(item.id == targetURL){
  327. videoURL = item.video_resources[0].src;
  328. }
  329. });
  330.  
  331. if(videoURL.length == 0){
  332. console.log('Memory cache not found, try fetch from API:', username);
  333. onStory(true,true);
  334. return;
  335. }
  336. }
  337. else{
  338. let userInfo = await getUserId(username);
  339. let userId = userInfo.user.pk;
  340. let stories = await getStories(userId);
  341.  
  342. stories.data.reels_media[0].items.forEach(item => {
  343. if(item.id == targetURL){
  344. videoURL = item.video_resources[0].src;
  345. }
  346. });
  347.  
  348. GL_dataCache.stories[username] = stories;
  349. }
  350.  
  351. if(videoURL.length == 0){
  352. alert(_i18n("NO_VID_URL"));
  353. }
  354. else{
  355. saveFiles(videoURL,username,"stories",timestamp,type);
  356. }
  357.  
  358. }
  359. else{
  360. // Download stories if it is image
  361. let srcset = $('section._ac0a ._aa64 img._aa63').attr('srcset').split(',')[0].split(' ')[0];
  362. let link = (srcset)?srcset:$('section._ac0a ._aa64 img._aa63').attr('src');
  363.  
  364. let downloadLink = link;
  365. let type = 'jpg';
  366.  
  367. saveFiles(downloadLink,username,"stories",timestamp,type);
  368. }
  369. }
  370. else{
  371. // Add the stories download button
  372. let style = "position: absolute;right:-40px;top:15px;padding:5px;line-height:1;background:#fff;border-radius: 5px;cursor:pointer;";
  373. if(!$('.IG_DWSTORY').length){
  374. GL_dataCache.stories = {};
  375. let $element = null;
  376. if($('body > div section._ac0a').length > 0){
  377. $element = $('body > div section._ac0a');
  378. }
  379. else{
  380. $element = $('body > div section > div > div:not([class])');
  381. }
  382.  
  383. if($element != null){
  384. $element.css('position','relative');
  385. $element.append(`<div title="${_i18n("DW")}" class="IG_DWSTORY"><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></div>`);
  386. }
  387. }
  388. }
  389. }
  390.  
  391. /**
  392. * onStoryThumbnail
  393. * Trigger user's story video thumbnail download event or button display event.
  394. *
  395. * @param {Boolean} isDownload - Check if it is a download operation
  396. * @return {void}
  397. */
  398. async function onStoryThumbnail(isDownload,isForce){
  399. if(isDownload){
  400. // Download stories if it is video
  401. let date = new Date().getTime();
  402. let timestamp = Math.floor(date / 1000);
  403. let type = 'jpg';
  404. let username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split('/').at(2);
  405. 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;';
  406. // Download thumbnail
  407. let targetURL = location.href.replace(/\/$/ig,'').split("/").at(-1);
  408. let videoThumbnailURL = "";
  409.  
  410.  
  411. if(GL_dataCache.stories[username] && !isForce){
  412. console.log('Fetch from memory cache:', username);
  413. GL_dataCache.stories[username].data.reels_media[0].items.forEach(item => {
  414. if(item.id == targetURL){
  415. videoThumbnailURL = item.display_url;
  416. }
  417. });
  418.  
  419. if(videoThumbnailURL.length == 0){
  420. console.log('Memory cache not found, try fetch from API:', username);
  421. onStoryThumbnail(true,true);
  422. return;
  423. }
  424. }
  425. else{
  426. let userInfo = await getUserId(username);
  427. let userId = userInfo.user.pk;
  428. let stories = await getStories(userId);
  429.  
  430. stories.data.reels_media[0].items.forEach(item => {
  431. if(item.id == targetURL){
  432. videoThumbnailURL = item.display_url;
  433. }
  434. });
  435. }
  436.  
  437. saveFiles(videoThumbnailURL,username,"thumbnail",timestamp,type);
  438. }
  439. else{
  440. if($('body > div section video.xh8yej3').length){
  441. // Add the stories download button
  442. if(!$('.IG_DWSTORY_THUMBNAIL').length){
  443. let $element = null;
  444. if($('body > div section._ac0a').length > 0){
  445. $element = $('body > div section._ac0a');
  446. }
  447. else{
  448. $element = $('body > div section > div > div:not([class])');
  449. }
  450.  
  451. if($element != null){
  452. $element.css('position','relative');
  453. $element.append(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="IG_DWSTORY_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></div>`);
  454. }
  455. }
  456. }
  457. else{
  458. $('.IG_DWSTORY_THUMBNAIL').remove();
  459. }
  460. }
  461. }
  462.  
  463. /**
  464. * onReels
  465. * Trigger user's reels download event or button display event.
  466. *
  467. * @param {Boolean} isDownload - Check if it is a download operation
  468. * @param {Boolean} isVideo - Check if reel is a video element
  469. * @return {void}
  470. */
  471. async function onReels(isDownload, isVideo){
  472. if(isDownload){
  473. let reelsPath = location.href.split('?').at(0).split('instagram.com/reels/').at(-1).replaceAll('/','');
  474. let data = await getBlobMedia(reelsPath);
  475. let timestamp = new Date().getTime();
  476.  
  477. if(isVideo && data.shortcode_media.is_video){
  478. let type = 'mp4';
  479. saveFiles(data.shortcode_media.video_url,data.shortcode_media.owner.username,"reels",timestamp,type,reelsPath);
  480. }
  481. else{
  482. let type = 'jpg';
  483. saveFiles(data.shortcode_media.display_resources.at(-1).src,data.shortcode_media.owner.username,"reels",timestamp,type,reelsPath);
  484. }
  485. }
  486. else{
  487. //$('.IG_REELS_THUMBNAIL, .IG_REELS').remove();
  488. var timer = setInterval(()=>{
  489. if($('section > main[role="main"] > div div.x1qjc9v5 video').length > 0){
  490. clearInterval(timer);
  491. $('section > main[role="main"] > div').children('div').each(function(){
  492. if($(this).children().length > 0){
  493. if(!$(this).children().find('.IG_REELS').length){
  494. $(this).children().css('position','relative');
  495.  
  496. $(this).children().append(`<div title="${_i18n("DW")}" class="IG_REELS"><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></div>`);
  497. $(this).children().append(`<div title="${_i18n("THUMBNAIL_INTRO")}" class="IG_REELS_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></div>`);
  498.  
  499. // Disable video autoplay
  500. if(USER_SETTING.DISABLE_VIDEO_LOOPING){
  501. $(this).find('video').each(function(){
  502. if(!$(this).data('loop')){
  503. console.log('Added video event listener');
  504. $(this).on('ended',function(){
  505. $(this).attr('data-loop', true);
  506. $(this).parent().find('.xpgaw4o').removeAttr('style');
  507. console.log('paused');
  508.  
  509. this.pause();
  510. });
  511. }
  512. });
  513. }
  514. }
  515. }
  516. });
  517. }
  518. },250);
  519. }
  520. }
  521.  
  522. /**
  523. * getHighlightStories
  524. * Get a list of all stories in highlight Id.
  525. *
  526. * @param {Integer} highlightId
  527. * @return {Object}
  528. */
  529. function getHighlightStories(highlightId){
  530. return new Promise((resolve,reject)=>{
  531. 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`;
  532.  
  533. GM_xmlhttpRequest({
  534. method: "GET",
  535. url: getURL,
  536. onload: function(response) {
  537. let obj = JSON.parse(response.response);
  538. resolve(obj);
  539. },
  540. onerror: function(err){
  541. reject(err);
  542. }
  543. });
  544. });
  545. }
  546.  
  547. /**
  548. * getStories
  549. * Get a list of all stories in user Id.
  550. *
  551. * @param {Integer} userId
  552. * @return {Object}
  553. */
  554. function getStories(userId){
  555. return new Promise((resolve,reject)=>{
  556. 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`;
  557.  
  558. GM_xmlhttpRequest({
  559. method: "GET",
  560. url: getURL,
  561. onload: function(response) {
  562. let obj = JSON.parse(response.response);
  563. resolve(obj);
  564. },
  565. onerror: function(err){
  566. reject(err);
  567. }
  568. });
  569. });
  570. }
  571.  
  572. /**
  573. * getUserId
  574. * Get user's id with username
  575. *
  576. * @param {String} username
  577. * @return {Integer}
  578. */
  579. function getUserId(username){
  580. return new Promise((resolve,reject)=>{
  581. let getURL = `https://www.instagram.com/web/search/topsearch/?query=${username}`;
  582.  
  583. GM_xmlhttpRequest({
  584. method: "GET",
  585. url: getURL,
  586. onload: function(response) {
  587. let obj = JSON.parse(response.response);
  588. resolve(obj.users[0]);
  589. },
  590. onerror: function(err){
  591. reject(err);
  592. }
  593. });
  594. });
  595. }
  596.  
  597. /**
  598. * getUserHighSizeProfile
  599. * Get user's high quality avatar image.
  600. *
  601. * @param {Integer} userId
  602. * @return {String}
  603. */
  604. function getUserHighSizeProfile(userId){
  605. return new Promise((resolve,reject)=>{
  606. let getURL = `https://i.instagram.com/api/v1/users/${userId}/info/`;
  607.  
  608. GM_xmlhttpRequest({
  609. method: "GET",
  610. url: getURL,
  611. headers: {
  612. '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'
  613. },
  614. onload: function(response) {
  615. let obj = JSON.parse(response.response);
  616. if(obj.status !== 'ok'){
  617. reject('faild');
  618. }
  619. else{
  620. resolve(obj.user.hd_profile_pic_url_info?.url);
  621. }
  622. },
  623. onerror: function(err){
  624. reject(err);
  625. }
  626. });
  627. });
  628. }
  629.  
  630. /**
  631. * getPostOwner
  632. * Get post's author with post shortcode
  633. *
  634. * @param {String} postPath
  635. * @return {String}
  636. */
  637. function getPostOwner(postPath){
  638. return new Promise((resolve,reject)=>{
  639. if(!postPath) reject("NOPATH");
  640. let postShortCode = postPath;
  641. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  642.  
  643. GM_xmlhttpRequest({
  644. method: "GET",
  645. url: getURL,
  646. onload: function(response) {
  647. let obj = JSON.parse(response.response);
  648. resolve(obj.data.shortcode_media.owner.username);
  649. },
  650. onerror: function(err){
  651. reject(err);
  652. }
  653. });
  654. });
  655. }
  656.  
  657. /**
  658. * getBlobMedia
  659. * Get list of all media files in post with post shortcode
  660. *
  661. * @param {String} postPath
  662. * @return {Object}
  663. */
  664. function getBlobMedia(postPath){
  665. return new Promise((resolve,reject)=>{
  666. if(!postPath) reject("NOPATH");
  667. let postShortCode = postPath;
  668. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  669.  
  670. GM_xmlhttpRequest({
  671. method: "GET",
  672. url: getURL,
  673. onload: function(response) {
  674. let obj = JSON.parse(response.response);
  675. console.log(obj);
  676. resolve(obj.data);
  677. },
  678. onerror: function(err){
  679. reject(err);
  680. }
  681. });
  682. });
  683. }
  684.  
  685. /**
  686. * onReadyMyDW
  687. * Create an event entry point for the download button for the post
  688. *
  689. * @param {Boolean} NoDialog - Check if it not showing the dialog
  690. * @return {void}
  691. */
  692. function onReadyMyDW(NoDialog){
  693. // Whether is Instagram dialog?
  694. if(!NoDialog){
  695. // Running if it is dialog
  696. $('article, main > div > div.xdt5ytf > div').each(function(){
  697. $(this).removeAttr('data-snig');
  698. $(this).unbind('click');
  699. });
  700. $('.SNKMS_IG_DW_MAIN,.SNKMS_IG_DW_MAIN_VIDEO').remove();
  701. }
  702. if(NoDialog == false){
  703. var repeat = setInterval(() => {
  704. // div.x13ehr01 << (sigle post in top, not floating) >>
  705. if($('article[data-snig="canDownload"], main > div > div.xdt5ytf > div[data-snig="canDownload"]').length > 0) clearInterval(repeat);
  706. createDownloadButton();
  707. },250);
  708. }
  709. else{
  710. createDownloadButton();
  711. }
  712. }
  713.  
  714. /**
  715. * createDownloadButton
  716. * Create a download button in the upper right corner of each post
  717. *
  718. * @return {void}
  719. */
  720. function createDownloadButton(){
  721. // Add download icon per each posts
  722. $('article, main > div > div.xdt5ytf > div').each(function(){
  723. // If it is have not download icon
  724. if(!$(this).attr('data-snig') && !$(this).hasClass('x1iyjqo2')){
  725. console.log("Found article");
  726. var rightPos = 15;
  727. if(this.tagName === "DIV"){
  728. rightPos = ($(this).children('div:last-child').width() !== undefined) ? $(this).children('div:last-child').width()+15 : 335+15
  729. }
  730.  
  731. // Add the download icon
  732. let $childElement = $(this).children("div").children("div");
  733. $childElement.eq((this.tagName === "DIV")? 0 : $childElement.length - 2).append(`<div title="${_i18n("DW")}" class="SNKMS_IG_DW_MAIN" style="right:${rightPos}px;"><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></div>`);
  734.  
  735. // Disable video autoplay
  736. if(USER_SETTING.DISABLE_VIDEO_LOOPING){
  737. $(this).find('video').each(function(){
  738. if(!$(this).data('loop')){
  739. console.log('Added video event listener');
  740. $(this).on('ended',function(){
  741. $(this).attr('data-loop', true);
  742. this.pause();
  743. });
  744. }
  745. });
  746. }
  747.  
  748. // Running if user click the download icon
  749. $(this).on('click','.SNKMS_IG_DW_MAIN', async function(e){
  750. GL_username = $(this).parent().parent().parent().attr('data-username');
  751. GL_postPath = location.pathname.split('/p/').at(-1).replaceAll('/','') || $(this).parent().parent().children("div:last-child").children("div").children("div:last-child").find('a[href^="/p/"]').last().attr("href").split("/").at(2);
  752.  
  753. // Create element that download dailog
  754. IG_createDM(GM_getValue('AutoDownload'), true);
  755.  
  756. $("#article-id").html(`<a href="https://www.instagram.com/p/${GL_postPath}">${GL_postPath}</a>`);
  757.  
  758. // Find video/image element and add the download icon
  759. var s = 0;
  760. var multiple = $(this).parent().parent().find('._aap0 ._acaz').length;
  761. var pathname = window.location.pathname;
  762. var fullpathname = "/"+pathname.split('/')[1]+"/"+pathname.split('/')[2]+"/";
  763. var blob = USER_SETTING.FORCE_FETCH_ALL_RESOURCES;
  764.  
  765. // If posts have more than one images or videos.
  766. if(multiple){
  767. $(this).parent().find('._aap0 ._acaz').each(function(){
  768. let element_videos = $(this).parent().parent().find('video');
  769. //if(element_videos && element_videos.attr('src') && element_videos.attr('src').match(/^blob:/ig)){
  770. if(element_videos && element_videos.attr('src')){
  771. blob = true;
  772. }
  773. });
  774.  
  775.  
  776. if(blob){
  777. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_MULTIPLE"));
  778. }
  779. else{
  780. $(this).parent().find('._aap0 ._acaz').each(function(){
  781. s++;
  782. let element_videos = $(this).find('video');
  783. let element_images = $(this).find('._aagv img');
  784. let imgLink = (element_images.attr('srcset'))?element_images.attr('srcset').split(" ")[0]:element_images.attr('src');
  785.  
  786. if(element_videos && element_videos.attr('src')){
  787. blob = true;
  788. /*
  789. let video_image = element_videos.attr('poster');
  790. let video_url = element_videos.attr('src');
  791.  
  792. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY').append(`<a data-needed="direct" data-path="${GL_postPath}" data-name="IGTV" data-type="mp4" data-globalIndex="${s}" href="javascript:;" data-href="${video_url}"><img width="100" src="${video_image}" /><br/>- ${_i18n("VID")} ${s} -</a>`);
  793.  
  794. if(video_url.match(/^blob:/ig)) blob = true;
  795. */
  796. }
  797. if(element_images && imgLink){
  798. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY').append(`<a data-needed="direct" data-path="${GL_postPath}" data-name="photo" data-type="jpg" data-globalIndex="${s}" href="javascript:;" data-href="${imgLink}"><img width="100" src="${imgLink}" /><br/>- ${_i18n("IMG")} ${s} -</a>`);
  799. }
  800.  
  801. });
  802.  
  803. if(blob){
  804. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_RELOAD"));
  805. }
  806. }
  807. }
  808. else{
  809. s++;
  810. let element_videos = $(this).parent().parent().find('video');
  811. let element_images = $(this).parent().parent().find('._aagv img');
  812. let imgLink = (element_images.attr('srcset'))?element_images.attr('srcset').split(" ")[0]:element_images.attr('src');
  813.  
  814.  
  815. if(element_videos && element_videos.attr('src')){
  816. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_ONE"));
  817.  
  818. /*
  819. let video_image = element_videos.attr('poster');
  820. let video_url = element_videos.attr('src');
  821.  
  822. if(element_videos.attr('src').match(/^blob:/ig)){
  823. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_ONE"));
  824. }
  825. else{
  826. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY').append(`<a data-needed="direct" data-path="${GL_postPath}" data-name="video" data-type="mp4" data-globalIndex="${s}" href="javascript:;" data-href="${video_url}"><img width="100" src="${video_image}" /><br/>- ${_i18n("VID")} ${s} -</a>`);
  827. }
  828. */
  829. }
  830. if(element_images && imgLink){
  831. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY').append(`<a data-needed="direct" data-path="${GL_postPath}" data-name="photo" data-type="jpg" data-globalIndex="${s}" href="javascript:;" href="" data-href="${imgLink}"><img width="100" src="${imgLink}" /><br/>- ${_i18n("IMG")} ${s} -</a>`);
  832. }
  833. }
  834.  
  835.  
  836. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function(){
  837. $(this).wrap('<div></div>');
  838. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  839. });
  840. });
  841.  
  842. // Add the mark that download is ready
  843. var username = $(this).find("header > div:last-child > div:first-child span").first().text();
  844.  
  845. $(this).attr('data-snig','canDownload');
  846. $(this).attr('data-username',username);
  847. }
  848. });
  849. }
  850.  
  851. /**
  852. * createMediaListDOM
  853. * Create a list of media elements from post URLs
  854. *
  855. * @param {String} postURL
  856. * @param {String} selector - Use CSS element selectors to choose where it appears.
  857. * @param {String} message - i18n display loading message
  858. * @return {void}
  859. */
  860. async function createMediaListDOM(postURL,selector,message){
  861. $(`${selector} a`).remove();
  862. $(selector).append('<p id="_SNLOAD">'+ message +'</p>');
  863. let media = await getBlobMedia(postURL);
  864. let idx = 1;
  865. let resource = media.shortcode_media;
  866.  
  867. // GraphVideo
  868. if(resource.__typename == "GraphVideo" && resource.video_url){
  869. $(selector).append(`<a data-blob="true" data-needed="direct" data-path="${resource.shortcode}" data-name="video" data-type="mp4" data-username="${resource.owner.username}" data-globalIndex="${idx}" href="javascript:;" data-href="${resource.video_url}"><img width="100" src="${resource.display_resources[1].src}" /><br/>- ${_i18n("VID")} ${idx} -</a>`);
  870. idx++;
  871. }
  872. // GraphSidecar
  873. if(resource.__typename == "GraphSidecar" && resource.edge_sidecar_to_children){
  874. for(let e of resource.edge_sidecar_to_children.edges){
  875. if(e.node.__typename == "GraphVideo"){
  876. $(selector).append(`<a data-blob="true" data-needed="direct" data-path="${resource.shortcode}" data-name="video" data-type="mp4" data-username="${resource.owner.username}" data-globalIndex="${idx}" href="javascript:;" data-href="${e.node.video_url}"><img width="100" src="${e.node.display_resources[1].src}" /><br/>- ${_i18n("VID")} ${idx} -</a>`);
  877. }
  878.  
  879. if(e.node.__typename == "GraphImage"){
  880. $(selector).append(`<a data-blob="true" data-needed="direct" data-path="${resource.shortcode}" data-name="photo" data-type="jpg" data-username="${resource.owner.username}" data-globalIndex="${idx}" href="javascript:;" data-href="${e.node.display_resources[e.node.display_resources.length - 1].src}"><img width="100" src="${e.node.display_resources[1].src}" /><br/>- ${_i18n("IMG")} ${idx} -</a>`);
  881. }
  882. idx++;
  883. }
  884. }
  885. $("#_SNLOAD").remove();
  886. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function(){
  887. $(this).wrap('<div></div>');
  888. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  889. });
  890. }
  891.  
  892. /**
  893. * IG_createDM
  894. * A dialog showing a list of all media files in the post
  895. *
  896. * @param {Boolean} hasHidden
  897. * @param {Boolean} hasCheckbox
  898. * @return {void}
  899. */
  900. function IG_createDM(hasHidden, hasCheckbox){
  901. let isHidden = (hasHidden)?"hidden":"";
  902. $('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>');
  903. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE').append('<div style="position:relative;height:36px;text-align:center;margin-bottom: 7px;"><div style="position:absolute;left:0px;line-height: 18px;"><kbd>Alt</kbd>+<kbd>Q</kbd> ['+_i18n("CLOSE")+']</div><div style="line-height: 18px;">IG Helper</div><div id="post_info" style="line-height: 14px;font-size:14px;">Post ID: <span id="article-id"></span></div><svg width="26" height="26" class="IG_SN_DIG_BTN" style="cursor:pointer;position:absolute;right:0px;top:0px;fill: rgb(var(--ig-primary-text));" xmlns="http://www.w3.org/2000/svg" id="bold" enable-background="new 0 0 24 24" height="512" viewBox="0 0 24 24" width="512"><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"/></svg></div>');
  904.  
  905. if(hasCheckbox){
  906. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE').append(`<div style="text-align: center;" id="button_group"></div>`);
  907. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE > div#button_group').append(`<button id="batch_download_selected">${_i18n('BATCH_DOWNLOAD_SELECTED')}</button>`);
  908. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE > div#button_group').append(`<button id="batch_download_direct">${_i18n('BATCH_DOWNLOAD_DIRECT')}</button>`);
  909. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE').append(`<br/><label class="checkbox"><input value="yes" type="checkbox" />${_i18n('ALL_CHECK')}</label>`);
  910. }
  911. }
  912.  
  913. /**
  914. * saveFiles
  915. * Download the specified media URL to the computer
  916. *
  917. * @param {String} downloadLink
  918. * @param {String} username
  919. * @param {String} sourceType
  920. * @param {Integer} timestamp
  921. * @param {String} filetype
  922. * @param {String} shortcode
  923. * @return {void}
  924. */
  925. function saveFiles(downloadLink,username,sourceType,timestamp,filetype,shortcode){
  926. fetch(downloadLink).then(res => {
  927. return res.blob().then(dwel => {
  928. const a = document.createElement("a");
  929. const name = username+'-'+sourceType+'-'+((USER_SETTING.RENAME_SHORTCODE && shortcode)?shortcode+'-':'')+timestamp+'.'+filetype;
  930. const originally = username + '_' + downloadLink.split('/').at(-1).split('?').at(0);
  931.  
  932. a.href = URL.createObjectURL(dwel);
  933. a.setAttribute("download", (USER_SETTING.AUTO_RENAME)?name:originally);
  934. a.click();
  935. a.remove();
  936. });
  937. });
  938. }
  939.  
  940. /**
  941. * translateText
  942. * i18n translation text
  943. *
  944. * @param {String} lang
  945. * @return {void}
  946. */
  947. function translateText(lang){
  948. return {
  949. "zh-TW": {
  950. "CLOSE": "關閉",
  951. "ALL_CHECK": "全選",
  952. "BATCH_DOWNLOAD_SELECTED": "批次下載已勾選資源",
  953. "BATCH_DOWNLOAD_DIRECT": "批次下載全部資源",
  954. "IMG": "相片",
  955. "VID": "影片",
  956. "DDL": "快速下載",
  957. "DDL_INTRO": "勾選後將直接下載點選當下位置的相片/影片",
  958. "DW": "下載",
  959. "THUMBNAIL_INTRO": "下載影片縮圖",
  960. "LOAD_BLOB_ONE": "正在載入二進位大型物件...",
  961. "LOAD_BLOB_MULTIPLE": "正在載入多個二進位大型物件...",
  962. "LOAD_BLOB_RELOAD": "正在重新載入二進位大型物件...",
  963. "NO_CHECK_RESOURCE": "您需要勾選資源才能下載。",
  964. "NO_VID_URL": "找不到影片網址",
  965. "SETTING": "設定",
  966. "AUTO_RENAME": "自動重新命名檔案",
  967. "RENAME_SHORTCODE": "重新命名檔案並包含 Shortcode",
  968. "DISABLE_VIDEO_LOOPING": "關閉影片自動循環播放",
  969. "REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE": "右鍵點擊使用者限時動態區域頭貼時重定向",
  970. "FORCE_FETCH_ALL_RESOURCES": "強制提取貼文中所有資源",
  971. "AUTO_RENAME_INTRO": "將檔案自動重新命名為以下格式:\n使用者名稱-類型-時間戳.檔案類型\n例如:instagram-photo-1670350000.jpg\n\n若設為 false,則檔案名稱將保持原始樣貌。 \n例如:instagram_321565527_679025940443063_4318007696887450953_n.jpg",
  972. "RENAME_SHORTCODE_INTRO": "將檔案自動重新命名為以下格式:\n使用者名稱-類型-Shortcode-時間戳.檔案類型\n示例:instagram-photo-CwkxyiVynpW-1670350000.jpg\n\n此功能僅在[自動重新命名檔案]設定為 TRUE 時有效。",
  973. "DISABLE_VIDEO_LOOPING_INTRO": "關閉連續短片和貼文中影片自動循環播放。",
  974. "REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE_INTRO": "右鍵點選首頁限時動態區域中的使用者頭貼時,重新導向到使用者的個人資料頁面。",
  975. "FORCE_FETCH_ALL_RESOURCES_INTRO": "透過 Instagram API 強制取得貼文中的所有資源(照片和影片),以取消每個貼文單次提取三個資源的限制。",
  976. },
  977. "zh-CN": {
  978. "CLOSE": "关闭",
  979. "ALL_CHECK": "全选",
  980. "BATCH_DOWNLOAD_SELECTED": "批量下载已勾选资源",
  981. "BATCH_DOWNLOAD_DIRECT": "批量下载全部资源",
  982. "IMG": "图像",
  983. "VID": "视频",
  984. "DDL": "便捷下载",
  985. "DDL_INTRO": "勾选后将直接下载點擊當下位置的图像/视频",
  986. "DW": "下载",
  987. "THUMBNAIL_INTRO": "下载视频缩略图",
  988. "LOAD_BLOB_ONE": "正在载入大型媒体对象...",
  989. "LOAD_BLOB_MULTIPLE": "正在载入多个大型媒体对象...",
  990. "LOAD_BLOB_RELOAD": "正在重新载入大型媒体对象...",
  991. "NO_CHECK_RESOURCE": "您需要勾選资源才能下載。",
  992. "NO_VID_URL": "找不到视频网址",
  993. "SETTING": "设置",
  994. "AUTO_RENAME": "自动重命名文件",
  995. "RENAME_SHORTCODE": "重命名文件并包含物件短码",
  996. "DISABLE_VIDEO_LOOPING": "禁用视频自动循环",
  997. "REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE": "右键单击用户故事区域头像时重定向",
  998. "FORCE_FETCH_ALL_RESOURCES": "强制抓取帖子中所有资源",
  999. "AUTO_RENAME_INTRO": "将文件自动重新命名为以下格式类型:\n用户名-类型-时间戳.文件类型\n例如:instagram-photo-1670350000.jpg\n\n若设为false,则文件名将保持原样。 \n例如:instagram_321565527_679025940443063_4318007696887450953_n.jpg",
  1000. "RENAME_SHORTCODE_INTRO": "自动重命名文件为以下格式类型:\n用户名-类型-短码-时间戳.文件类型\n示例:instagram-photo-CwkxyiVynpW-1670350000.jpg\n\n它仅在[自动重命名文件]设置为 TRUE 时有效。",
  1001. "DISABLE_VIDEO_LOOPING_INTRO": "禁用 Reels 和帖子中的视频自动播放。",
  1002. "REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE_INTRO": "右键单击主页故事区域中的用户头像,重定向到用户的个人资料页面。",
  1003. "FORCE_FETCH_ALL_RESOURCES_INTRO": "通过 Instagram API 强制获取帖子中的所有资源(照片和视频),以取消每个帖子单次抓取三个资源的限制。"
  1004. },
  1005. "en-US": {
  1006. "CLOSE": "Close",
  1007. "ALL_CHECK": "Select All",
  1008. "BATCH_DOWNLOAD_SELECTED": "Download Selected Resources",
  1009. "BATCH_DOWNLOAD_DIRECT": "Download All Resources",
  1010. "IMG": "Image",
  1011. "VID": "Video",
  1012. "DDL": "Quick Download",
  1013. "DDL_INTRO": "Checking it will direct download current photo/media in the posts.",
  1014. "DW": "Download",
  1015. "THUMBNAIL_INTRO": "Download video thumbnail.",
  1016. "LOAD_BLOB_ONE": "Loading Blob Media...",
  1017. "LOAD_BLOB_MULTIPLE": "Loading Blob Media and others...",
  1018. "LOAD_BLOB_RELOAD": "Detect Blob Media, now reloading...",
  1019. "NO_CHECK_RESOURCE": "You need to check resource to download.",
  1020. "NO_VID_URL": "Can not find video url.",
  1021. "SETTING": "Settings",
  1022. "AUTO_RENAME": "Automatically Rename Files",
  1023. "RENAME_SHORTCODE": "Rename The File and Include Shortcode",
  1024. "DISABLE_VIDEO_LOOPING": "Disable Video Auto-looping",
  1025. "REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE": "Redirect When Right-Clicking User Story Picture",
  1026. "FORCE_FETCH_ALL_RESOURCES": "Forcing Fetch All Resources In the Post",
  1027. "AUTO_RENAME_INTRO": "Auto rename file to format type following:\nUSERNAME-TYPE-TIMESTAMP.FILETYPE\nExample: instagram-photo-1670350000.jpg\n\nIf set to false, the file name will remain as it is.\nExample: instagram_321565527_679025940443063_4318007696887450953_n.jpg",
  1028. "RENAME_SHORTCODE_INTRO": "Auto rename file to format type following:\nUSERNAME-TYPE-SHORTCODE-TIMESTAMP.FILETYPE\nExample: instagram-photo-CwkxyiVynpW-1670350000.jpg\n\nIt will ONLY work in [Automatically Rename Files] setting to TRUE.",
  1029. "DISABLE_VIDEO_LOOPING_INTRO": "Disable video auto-looping in reels and posts.",
  1030. "REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE_INTRO": "Redirect to a user's profile page when right-clicking on their user avatar in the story area on the homepage.",
  1031. "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."
  1032. }
  1033. };
  1034. }
  1035.  
  1036. /**
  1037. * _i18n
  1038. * Perform i18n translation
  1039. *
  1040. * @param {String} text
  1041. * @return {void}
  1042. */
  1043. function _i18n(text){
  1044. let userLang = (lang)?lang:"en-US";
  1045. let translate = {
  1046. "zh-TW": function(){
  1047. return translateText()["zh-TW"];
  1048. },
  1049. "zh-HK": function(){
  1050. return translateText()["zh-TW"];
  1051. },
  1052. "zh-MO": function(){
  1053. return translateText()["zh-TW"];
  1054. },
  1055. "zh-CN": function(){
  1056. return translateText()["zh-CN"];
  1057. },
  1058. "en-US": function(){
  1059. return translateText()["en-US"];
  1060. }
  1061. }
  1062.  
  1063. try{
  1064. return translate[lang]()[text];
  1065. }
  1066. catch{
  1067. return translate["en-US"]()[text];
  1068. }
  1069. }
  1070.  
  1071. /**
  1072. * showSetting
  1073. * Show script settings window
  1074. *
  1075. * @return {void}
  1076. */
  1077. function showSetting(){
  1078. $('.IG_SN_DIG').remove();
  1079. IG_createDM();
  1080. $('.IG_SN_DIG #post_info').text('IG Helper Settings');
  1081.  
  1082. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<label class="globalSettings" title="${_i18n('AUTO_RENAME_INTRO')}"><span>${_i18n('AUTO_RENAME')}</span> <input id="AUTO_RENAME" value="box" type="checkbox" ${(USER_SETTING.AUTO_RENAME)?'checked':''}><div class="chbtn"><div class="rounds"></div></div></label>`);
  1083. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<label class="globalSettings" title="${_i18n('RENAME_SHORTCODE_INTRO')}"><span>${_i18n('RENAME_SHORTCODE')}</span> <input id="RENAME_SHORTCODE" value="box" type="checkbox" ${(USER_SETTING.RENAME_SHORTCODE)?'checked':''}><div class="chbtn"><div class="rounds"></div></div></label>`);
  1084. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<label class="globalSettings" title="${_i18n('DISABLE_VIDEO_LOOPING_INTRO')}"><span>${_i18n('DISABLE_VIDEO_LOOPING')}</span> <input id="DISABLE_VIDEO_LOOPING" value="box" type="checkbox" ${(USER_SETTING.DISABLE_VIDEO_LOOPING)?'checked':''}><div class="chbtn"><div class="rounds"></div></div></label>`);
  1085. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<label class="globalSettings" title="${_i18n('REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE_INTRO')}"><span>${_i18n('REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE')}</span> <input id="REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE" value="box" type="checkbox" ${(USER_SETTING.REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE)?'checked':''}><div class="chbtn"><div class="rounds"></div></div></label>`);
  1086. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<label class="globalSettings" title="${_i18n('FORCE_FETCH_ALL_RESOURCES_INTRO')}"><span>${_i18n('FORCE_FETCH_ALL_RESOURCES')}</span> <input id="FORCE_FETCH_ALL_RESOURCES" value="box" type="checkbox" ${(USER_SETTING.FORCE_FETCH_ALL_RESOURCES)?'checked':''}><div class="chbtn"><div class="rounds"></div></div></label>`);
  1087. }
  1088.  
  1089. /**
  1090. * showDebugDOM
  1091. * Show full DOM tree
  1092. *
  1093. * @return {void}
  1094. */
  1095. function showDebugDOM(text){
  1096. $('.IG_SN_DIG').remove();
  1097. IG_createDM();
  1098. $('.IG_SN_DIG #post_info').text('IG Debug DOM Tree');
  1099.  
  1100. $('.IG_SN_DIG .IG_SN_DIG_BODY').append(`<textarea style="width:100%;box-sizing: border-box;height:300px;">${text.innerHTML}</textarea>`);
  1101. }
  1102.  
  1103. // Running if document is ready
  1104. $(function(){
  1105. // Close the download dialog if user click the close icon
  1106. $('body').on('click','.IG_SN_DIG_BTN,.IG_SN_DIG_BG',function(){
  1107. $('.IG_SN_DIG').remove();
  1108. });
  1109.  
  1110. $(window).keydown(function(e){
  1111. // Hot key [Alt+Q] to close the download dialog
  1112. if (e.keyCode == '81' && e.altKey){
  1113. $('.IG_SN_DIG').remove();
  1114. e.preventDefault();
  1115. }
  1116. // Hot key [Alt+W] to open the settings dialog
  1117. if (e.keyCode == '87' && e.altKey){
  1118. showSetting();
  1119. e.preventDefault();
  1120. }
  1121.  
  1122. // Hot key [Alt+Z] to open the settings dialog
  1123. if (e.keyCode == '90' && e.altKey){
  1124. let text = $('div[id^="mount"]')[0];
  1125. showDebugDOM(text);
  1126. e.preventDefault();
  1127. }
  1128. });
  1129.  
  1130. $('body').on('change', '.IG_SN_DIG input',function(){
  1131. var isChecked = $(this).prop('checked');
  1132. var name = $(this).attr('id');
  1133.  
  1134. GM_setValue(name, isChecked);
  1135. USER_SETTING[name] = isChecked;
  1136. });
  1137.  
  1138. $('body').on('click','a[data-needed="direct"]',async function(){
  1139. let date = new Date().getTime();
  1140. let timestamp = Math.floor(date / 1000);
  1141. let username = ($(this).attr('data-username')) ? $(this).attr('data-username') : GL_username;
  1142.  
  1143. if(!username && $(this).attr('data-path')){
  1144. console.log('catching owner name from shortcode:',$(this).attr('data-href'));
  1145. username = await getPostOwner($(this).attr('data-path'));
  1146. }
  1147. saveFiles($(this).attr('data-href'),username,$(this).attr('data-name'),timestamp,$(this).attr('data-type'), $(this).attr('data-path'));
  1148. });
  1149.  
  1150. // Running if user left-click download icon in stories
  1151. $('body').on('click','.IG_DWSTORY',function(){
  1152. onStory(true);
  1153. });
  1154.  
  1155. // Running if user left-click download icon in stories
  1156. $('body').on('click','.IG_DWSTORY_THUMBNAIL',function(){
  1157. onStoryThumbnail(true);
  1158. });
  1159.  
  1160. // Running if user left-click download icon in profile
  1161. $('body').on('click','.IG_DWPROFILE',function(e){
  1162. e.stopPropagation();
  1163. onProfileAvatar(true);
  1164. });
  1165.  
  1166. // Running if user left-click download icon in highlight stories
  1167. $('body').on('click','.IG_DWHISTORY',function(){
  1168. onHighlightsStory(true);
  1169. });
  1170.  
  1171. // Running if user left-click download icon in highlight stories
  1172. $('body').on('click','.IG_DWHISTORY_THUMBNAIL',function(){
  1173. onHighlightsStoryThumbnail(true);
  1174. });
  1175.  
  1176. // Running if user left-click download icon in reels
  1177. $('body').on('click','.IG_REELS',function(){
  1178. onReels(true,true);
  1179. });
  1180.  
  1181. // Running if user left-click download icon in reels
  1182. $('body').on('click','.IG_REELS_THUMBNAIL',function(){
  1183. onReels(true,false);
  1184. });
  1185.  
  1186. // Running if user right-click profile picture in stories area
  1187. $('body').on('contextmenu','button[role="menuitem"]',function(){
  1188. if(location.href === 'https://www.instagram.com/' && USER_SETTING.REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE){
  1189. if($(this).find('canvas._aarh').length > 0){
  1190. location.href = 'https://www.instagram.com/'+$(this).children('div').last().text();
  1191. }
  1192. }
  1193. });
  1194.  
  1195. $('body').on('change', '.IG_SN_DIG_TITLE .checkbox', function(){
  1196. var isChecked = $(this).find('input').prop('checked');
  1197. $('.IG_SN_DIG_BODY .inner_box').each(function(){
  1198. $(this).prop('checked', isChecked);
  1199. });
  1200. });
  1201.  
  1202. $('body').on('change', '.IG_SN_DIG_BODY .inner_box', function(){
  1203. var checked = $('.IG_SN_DIG_BODY .inner_box:checked').length;
  1204. var total = $('.IG_SN_DIG_BODY .inner_box').length;
  1205.  
  1206.  
  1207. $('.IG_SN_DIG_TITLE .checkbox').find('input').prop('checked', checked == total);
  1208. });
  1209.  
  1210. $('body').on('click', '.IG_SN_DIG_TITLE #batch_download_selected', function(){
  1211. let index = 0;
  1212. $('.IG_SN_DIG_BODY a[data-needed="direct"]').each(function(){
  1213. if($(this).prev().prop('checked')){
  1214. $(this).click();
  1215. index++;
  1216. }
  1217. });
  1218.  
  1219. if(index == 0){
  1220. alert(_i18n('NO_CHECK_RESOURCE'));
  1221. }
  1222. });
  1223.  
  1224. $('body').on('click', '.IG_SN_DIG_TITLE #batch_download_direct', function(){
  1225. $('.IG_SN_DIG_BODY a[data-needed="direct"]').each(function(){
  1226. $(this).click();
  1227. });
  1228. });
  1229. });
  1230. })(jQuery);