IG小助手

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

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

  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.6
  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. $('body > div section._ac0a').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>`);
  231. }
  232. }
  233. }
  234.  
  235. /**
  236. * onHighlightsStoryThumbnail
  237. * Trigger user's highlight video thumbnail download event or button display event.
  238. *
  239. * @param {Boolean} isDownload - Check if it is a download operation
  240. * @return {void}
  241. */
  242. async function onHighlightsStoryThumbnail(isDownload){
  243. if(isDownload){
  244. let date = new Date().getTime();
  245. let timestamp = Math.floor(date / 1000);
  246. let highlightId = location.href.replace(/\/$/ig,'').split('/').at(-1);
  247. let username = "";
  248. let nowIndex = $("body > div section._ac0a header._ac0k > ._ac3r ._ac3n ._ac3p[style]").length;
  249. let target = "";
  250.  
  251. if(GL_dataCache.highlights[highlightId]){
  252. console.log('Fetch from memory cache:', highlightId);
  253.  
  254. let totIndex = GL_dataCache.highlights[highlightId].data.reels_media[0].items.length;
  255. username = GL_dataCache.highlights[highlightId].data.reels_media[0].owner.username;
  256. target = GL_dataCache.highlights[highlightId].data.reels_media[0].items[totIndex-nowIndex];
  257. }
  258. else{
  259. let highStories = await getHighlightStories(highlightId);
  260. let totIndex = highStories.data.reels_media[0].items.length;
  261. username = highStories.data.reels_media[0].owner.username;
  262. target = highStories.data.reels_media[0].items[totIndex-nowIndex];
  263.  
  264. GL_dataCache.highlights[highlightId] = highStories;
  265. }
  266.  
  267. saveFiles(target.display_resources.at(-1).src,username,"highlights",timestamp,'jpg', highlightId);
  268. }
  269. else{
  270. if($('body > div section._ac0a video.xh8yej3').length){
  271. // Add the stories download button
  272. if(!$('.IG_DWHISTORY_THUMBNAIL').length){
  273. $('body > div section._ac0a').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>`);
  274. }
  275. }
  276. else{
  277. $('.IG_DWHISTORY_THUMBNAIL').remove();
  278. }
  279. }
  280. }
  281.  
  282. /**
  283. * onStory
  284. * Trigger user's story download event or button display event.
  285. *
  286. * @param {Boolean} isDownload - Check if it is a download operation
  287. * @return {void}
  288. */
  289. async function onStory(isDownload,isForce){
  290. if(isDownload){
  291. let date = new Date().getTime();
  292. let timestamp = Math.floor(date / 1000);
  293. let username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split('/').at(2);
  294.  
  295. if($('body > div section._ac0a div._ac0b video.x1lliihq').length){
  296. // Download stories if it is video
  297. let type = "mp4";
  298. let videoURL = "";
  299. let targetURL = location.href.replace(/\/$/ig,'').split("/").at(-1);
  300.  
  301. if(GL_dataCache.stories[username] && !isForce){
  302. console.log('Fetch from memory cache:', username);
  303. GL_dataCache.stories[username].data.reels_media[0].items.forEach(item => {
  304. if(item.id == targetURL){
  305. videoURL = item.video_resources[0].src;
  306. }
  307. });
  308.  
  309. if(videoURL.length == 0){
  310. console.log('Memory cache not found, try fetch from API:', username);
  311. onStory(true,true);
  312. return;
  313. }
  314. }
  315. else{
  316. let userInfo = await getUserId(username);
  317. let userId = userInfo.user.pk;
  318. let stories = await getStories(userId);
  319.  
  320. stories.data.reels_media[0].items.forEach(item => {
  321. if(item.id == targetURL){
  322. videoURL = item.video_resources[0].src;
  323. }
  324. });
  325.  
  326. GL_dataCache.stories[username] = stories;
  327. }
  328.  
  329. if(videoURL.length == 0){
  330. alert(_i18n("NO_VID_URL"));
  331. }
  332. else{
  333. saveFiles(videoURL,username,"stories",timestamp,type);
  334. }
  335.  
  336. }
  337. else{
  338. // Download stories if it is image
  339. let srcset = $('section._ac0a ._aa64 img._aa63').attr('srcset').split(',')[0].split(' ')[0];
  340. let link = (srcset)?srcset:$('section._ac0a ._aa64 img._aa63').attr('src');
  341.  
  342. let downloadLink = link;
  343. let type = 'jpg';
  344.  
  345. saveFiles(downloadLink,username,"stories",timestamp,type);
  346. }
  347. }
  348. else{
  349. // Add the stories download button
  350. let style = "position: absolute;right:-40px;top:15px;padding:5px;line-height:1;background:#fff;border-radius: 5px;cursor:pointer;";
  351. if(!$('.IG_DWSTORY').length){
  352. GL_dataCache.stories = {};
  353. $('body > div section._ac0a').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>`);
  354. }
  355. }
  356. }
  357.  
  358. /**
  359. * onStoryThumbnail
  360. * Trigger user's story video thumbnail download event or button display event.
  361. *
  362. * @param {Boolean} isDownload - Check if it is a download operation
  363. * @return {void}
  364. */
  365. async function onStoryThumbnail(isDownload,isForce){
  366. if(isDownload){
  367. // Download stories if it is video
  368. let date = new Date().getTime();
  369. let timestamp = Math.floor(date / 1000);
  370. let type = 'jpg';
  371. let username = $("body > div section._ac0a header._ac0k ._ac0l a + div a").first().text() || location.pathname.split('/').at(2);
  372. 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;';
  373. // Download thumbnail
  374. let targetURL = location.href.replace(/\/$/ig,'').split("/").at(-1);
  375. let videoThumbnailURL = "";
  376.  
  377.  
  378. if(GL_dataCache.stories[username] && !isForce){
  379. console.log('Fetch from memory cache:', username);
  380. GL_dataCache.stories[username].data.reels_media[0].items.forEach(item => {
  381. if(item.id == targetURL){
  382. videoThumbnailURL = item.display_url;
  383. }
  384. });
  385.  
  386. if(videoThumbnailURL.length == 0){
  387. console.log('Memory cache not found, try fetch from API:', username);
  388. onStoryThumbnail(true,true);
  389. return;
  390. }
  391. }
  392. else{
  393. let userInfo = await getUserId(username);
  394. let userId = userInfo.user.pk;
  395. let stories = await getStories(userId);
  396.  
  397. stories.data.reels_media[0].items.forEach(item => {
  398. if(item.id == targetURL){
  399. videoThumbnailURL = item.display_url;
  400. }
  401. });
  402. }
  403.  
  404. saveFiles(videoThumbnailURL,username,"thumbnail",timestamp,type);
  405. }
  406. else{
  407. if($('body > div section._ac0a video.xh8yej3').length){
  408. // Add the stories download button
  409. if(!$('.IG_DWSTORY_THUMBNAIL').length){
  410. $('body > div section._ac0a').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>`);
  411. }
  412. }
  413. else{
  414. $('.IG_DWSTORY_THUMBNAIL').remove();
  415. }
  416. }
  417. }
  418.  
  419. /**
  420. * onReels
  421. * Trigger user's reels download event or button display event.
  422. *
  423. * @param {Boolean} isDownload - Check if it is a download operation
  424. * @param {Boolean} isVideo - Check if reel is a video element
  425. * @return {void}
  426. */
  427. async function onReels(isDownload, isVideo){
  428. if(isDownload){
  429. let reelsPath = location.href.split('?').at(0).split('instagram.com/reels/').at(-1).replaceAll('/','');
  430. let data = await getBlobMedia(reelsPath);
  431. let timestamp = new Date().getTime();
  432.  
  433. if(isVideo && data.shortcode_media.is_video){
  434. let type = 'mp4';
  435. saveFiles(data.shortcode_media.video_url,data.shortcode_media.owner.username,"reels",timestamp,type,reelsPath);
  436. }
  437. else{
  438. let type = 'jpg';
  439. saveFiles(data.shortcode_media.display_resources.at(-1).src,data.shortcode_media.owner.username,"reels",timestamp,type,reelsPath);
  440. }
  441. }
  442. else{
  443. //$('.IG_REELS_THUMBNAIL, .IG_REELS').remove();
  444. var timer = setInterval(()=>{
  445. if($('section > main[role="main"] > div div.x1qjc9v5 video').length > 0){
  446. clearInterval(timer);
  447. $('section > main[role="main"] > div').children('div').each(function(){
  448. if($(this).children().length > 0){
  449. if(!$(this).children().find('.IG_REELS').length){
  450. $(this).children().css('position','relative');
  451.  
  452. $(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>`);
  453. $(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>`);
  454.  
  455. // Disable video autoplay
  456. if(USER_SETTING.DISABLE_VIDEO_LOOPING){
  457. $(this).find('video').each(function(){
  458. if(!$(this).data('loop')){
  459. console.log('Added video event listener');
  460. $(this).on('ended',function(){
  461. $(this).attr('data-loop', true);
  462. $(this).parent().find('.xpgaw4o').removeAttr('style');
  463. console.log('paused');
  464.  
  465. this.pause();
  466. });
  467. }
  468. });
  469. }
  470. }
  471. }
  472. });
  473. }
  474. },250);
  475. }
  476. }
  477.  
  478. /**
  479. * getHighlightStories
  480. * Get a list of all stories in highlight Id.
  481. *
  482. * @param {Integer} highlightId
  483. * @return {Object}
  484. */
  485. function getHighlightStories(highlightId){
  486. return new Promise((resolve,reject)=>{
  487. 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`;
  488.  
  489. GM_xmlhttpRequest({
  490. method: "GET",
  491. url: getURL,
  492. onload: function(response) {
  493. let obj = JSON.parse(response.response);
  494. resolve(obj);
  495. },
  496. onerror: function(err){
  497. reject(err);
  498. }
  499. });
  500. });
  501. }
  502.  
  503. /**
  504. * getStories
  505. * Get a list of all stories in user Id.
  506. *
  507. * @param {Integer} userId
  508. * @return {Object}
  509. */
  510. function getStories(userId){
  511. return new Promise((resolve,reject)=>{
  512. 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`;
  513.  
  514. GM_xmlhttpRequest({
  515. method: "GET",
  516. url: getURL,
  517. onload: function(response) {
  518. let obj = JSON.parse(response.response);
  519. resolve(obj);
  520. },
  521. onerror: function(err){
  522. reject(err);
  523. }
  524. });
  525. });
  526. }
  527.  
  528. /**
  529. * getUserId
  530. * Get user's id with username
  531. *
  532. * @param {String} username
  533. * @return {Integer}
  534. */
  535. function getUserId(username){
  536. return new Promise((resolve,reject)=>{
  537. let getURL = `https://www.instagram.com/web/search/topsearch/?query=${username}`;
  538.  
  539. GM_xmlhttpRequest({
  540. method: "GET",
  541. url: getURL,
  542. onload: function(response) {
  543. let obj = JSON.parse(response.response);
  544. resolve(obj.users[0]);
  545. },
  546. onerror: function(err){
  547. reject(err);
  548. }
  549. });
  550. });
  551. }
  552.  
  553. /**
  554. * getUserHighSizeProfile
  555. * Get user's high quality avatar image.
  556. *
  557. * @param {Integer} userId
  558. * @return {String}
  559. */
  560. function getUserHighSizeProfile(userId){
  561. return new Promise((resolve,reject)=>{
  562. let getURL = `https://i.instagram.com/api/v1/users/${userId}/info/`;
  563.  
  564. GM_xmlhttpRequest({
  565. method: "GET",
  566. url: getURL,
  567. headers: {
  568. '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'
  569. },
  570. onload: function(response) {
  571. let obj = JSON.parse(response.response);
  572. if(obj.status !== 'ok'){
  573. reject('faild');
  574. }
  575. else{
  576. resolve(obj.user.hd_profile_pic_url_info?.url);
  577. }
  578. },
  579. onerror: function(err){
  580. reject(err);
  581. }
  582. });
  583. });
  584. }
  585.  
  586. /**
  587. * getPostOwner
  588. * Get post's author with post shortcode
  589. *
  590. * @param {String} postPath
  591. * @return {String}
  592. */
  593. function getPostOwner(postPath){
  594. return new Promise((resolve,reject)=>{
  595. if(!postPath) reject("NOPATH");
  596. let postShortCode = postPath;
  597. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  598.  
  599. GM_xmlhttpRequest({
  600. method: "GET",
  601. url: getURL,
  602. onload: function(response) {
  603. let obj = JSON.parse(response.response);
  604. resolve(obj.data.shortcode_media.owner.username);
  605. },
  606. onerror: function(err){
  607. reject(err);
  608. }
  609. });
  610. });
  611. }
  612.  
  613. /**
  614. * getBlobMedia
  615. * Get list of all media files in post with post shortcode
  616. *
  617. * @param {String} postPath
  618. * @return {Object}
  619. */
  620. function getBlobMedia(postPath){
  621. return new Promise((resolve,reject)=>{
  622. if(!postPath) reject("NOPATH");
  623. let postShortCode = postPath;
  624. let getURL = `https://www.instagram.com/graphql/query/?query_hash=2c4c2e343a8f64c625ba02b2aa12c7f8&variables=%7B%22shortcode%22:%22${postShortCode}%22}`;
  625.  
  626. GM_xmlhttpRequest({
  627. method: "GET",
  628. url: getURL,
  629. onload: function(response) {
  630. let obj = JSON.parse(response.response);
  631. console.log(obj);
  632. resolve(obj.data);
  633. },
  634. onerror: function(err){
  635. reject(err);
  636. }
  637. });
  638. });
  639. }
  640.  
  641. /**
  642. * onReadyMyDW
  643. * Create an event entry point for the download button for the post
  644. *
  645. * @param {Boolean} NoDialog - Check if it not showing the dialog
  646. * @return {void}
  647. */
  648. function onReadyMyDW(NoDialog){
  649. // Whether is Instagram dialog?
  650. if(!NoDialog){
  651. // Running if it is dialog
  652. $('article, main > div > div.xdt5ytf > div').each(function(){
  653. $(this).removeAttr('data-snig');
  654. $(this).unbind('click');
  655. });
  656. $('.SNKMS_IG_DW_MAIN,.SNKMS_IG_DW_MAIN_VIDEO').remove();
  657. }
  658. if(NoDialog == false){
  659. var repeat = setInterval(() => {
  660. // div.x13ehr01 << (sigle post in top, not floating) >>
  661. if($('article[data-snig="canDownload"], main > div > div.xdt5ytf > div[data-snig="canDownload"]').length > 0) clearInterval(repeat);
  662. createDownloadButton();
  663. },250);
  664. }
  665. else{
  666. createDownloadButton();
  667. }
  668. }
  669.  
  670. /**
  671. * createDownloadButton
  672. * Create a download button in the upper right corner of each post
  673. *
  674. * @return {void}
  675. */
  676. function createDownloadButton(){
  677. // Add download icon per each posts
  678. $('article, main > div > div.xdt5ytf > div').each(function(){
  679. // If it is have not download icon
  680. if(!$(this).attr('data-snig') && !$(this).hasClass('x1iyjqo2')){
  681. console.log("Found article");
  682. var rightPos = 15;
  683. if(this.tagName === "DIV"){
  684. rightPos = ($(this).children('div:last-child').width() !== undefined) ? $(this).children('div:last-child').width()+15 : 335+15
  685. }
  686.  
  687. // Add the download icon
  688. let $childElement = $(this).children("div").children("div");
  689. $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>`);
  690.  
  691. // Disable video autoplay
  692. if(USER_SETTING.DISABLE_VIDEO_LOOPING){
  693. $(this).find('video').each(function(){
  694. if(!$(this).data('loop')){
  695. console.log('Added video event listener');
  696. $(this).on('ended',function(){
  697. $(this).attr('data-loop', true);
  698. this.pause();
  699. });
  700. }
  701. });
  702. }
  703.  
  704. // Running if user click the download icon
  705. $(this).on('click','.SNKMS_IG_DW_MAIN', async function(e){
  706. GL_username = $(this).parent().parent().parent().attr('data-username');
  707. 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);
  708.  
  709. // Create element that download dailog
  710. IG_createDM(GM_getValue('AutoDownload'), true);
  711.  
  712. $("#article-id").html(`<a href="https://www.instagram.com/p/${GL_postPath}">${GL_postPath}</a>`);
  713.  
  714. // Find video/image element and add the download icon
  715. var s = 0;
  716. var multiple = $(this).parent().parent().find('._aap0 ._acaz').length;
  717. var pathname = window.location.pathname;
  718. var fullpathname = "/"+pathname.split('/')[1]+"/"+pathname.split('/')[2]+"/";
  719. var blob = USER_SETTING.FORCE_FETCH_ALL_RESOURCES;
  720.  
  721. // If posts have more than one images or videos.
  722. if(multiple){
  723. $(this).parent().find('._aap0 ._acaz').each(function(){
  724. let element_videos = $(this).parent().parent().find('video');
  725. //if(element_videos && element_videos.attr('src') && element_videos.attr('src').match(/^blob:/ig)){
  726. if(element_videos && element_videos.attr('src')){
  727. blob = true;
  728. }
  729. });
  730.  
  731.  
  732. if(blob){
  733. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_MULTIPLE"));
  734. }
  735. else{
  736. $(this).parent().find('._aap0 ._acaz').each(function(){
  737. s++;
  738. let element_videos = $(this).find('video');
  739. let element_images = $(this).find('._aagv img');
  740. let imgLink = (element_images.attr('srcset'))?element_images.attr('srcset').split(" ")[0]:element_images.attr('src');
  741.  
  742. if(element_videos && element_videos.attr('src')){
  743. blob = true;
  744. /*
  745. let video_image = element_videos.attr('poster');
  746. let video_url = element_videos.attr('src');
  747.  
  748. $('.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>`);
  749.  
  750. if(video_url.match(/^blob:/ig)) blob = true;
  751. */
  752. }
  753. if(element_images && imgLink){
  754. $('.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>`);
  755. }
  756.  
  757. });
  758.  
  759. if(blob){
  760. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_RELOAD"));
  761. }
  762. }
  763. }
  764. else{
  765. s++;
  766. let element_videos = $(this).parent().parent().find('video');
  767. let element_images = $(this).parent().parent().find('._aagv img');
  768. let imgLink = (element_images.attr('srcset'))?element_images.attr('srcset').split(" ")[0]:element_images.attr('src');
  769.  
  770.  
  771. if(element_videos && element_videos.attr('src')){
  772. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_ONE"));
  773.  
  774. /*
  775. let video_image = element_videos.attr('poster');
  776. let video_url = element_videos.attr('src');
  777.  
  778. if(element_videos.attr('src').match(/^blob:/ig)){
  779. createMediaListDOM(GL_postPath,".IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY",_i18n("LOAD_BLOB_ONE"));
  780. }
  781. else{
  782. $('.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>`);
  783. }
  784. */
  785. }
  786. if(element_images && imgLink){
  787. $('.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>`);
  788. }
  789. }
  790.  
  791.  
  792. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function(){
  793. $(this).wrap('<div></div>');
  794. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  795. });
  796. });
  797.  
  798. // Add the mark that download is ready
  799. var username = $(this).find("header > div:last-child > div:first-child span").first().text();
  800.  
  801. $(this).attr('data-snig','canDownload');
  802. $(this).attr('data-username',username);
  803. }
  804. });
  805. }
  806.  
  807. /**
  808. * createMediaListDOM
  809. * Create a list of media elements from post URLs
  810. *
  811. * @param {String} postURL
  812. * @param {String} selector - Use CSS element selectors to choose where it appears.
  813. * @param {String} message - i18n display loading message
  814. * @return {void}
  815. */
  816. async function createMediaListDOM(postURL,selector,message){
  817. $(`${selector} a`).remove();
  818. $(selector).append('<p id="_SNLOAD">'+ message +'</p>');
  819. let media = await getBlobMedia(postURL);
  820. let idx = 1;
  821. let resource = media.shortcode_media;
  822.  
  823. // GraphVideo
  824. if(resource.__typename == "GraphVideo" && resource.video_url){
  825. $(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>`);
  826. idx++;
  827. }
  828. // GraphSidecar
  829. if(resource.__typename == "GraphSidecar" && resource.edge_sidecar_to_children){
  830. for(let e of resource.edge_sidecar_to_children.edges){
  831. if(e.node.__typename == "GraphVideo"){
  832. $(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>`);
  833. }
  834.  
  835. if(e.node.__typename == "GraphImage"){
  836. $(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>`);
  837. }
  838. idx++;
  839. }
  840. }
  841. $("#_SNLOAD").remove();
  842. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_BODY a').each(function(){
  843. $(this).wrap('<div></div>');
  844. $(this).before('<label class="inner_box_wrapper"><input class="inner_box" type="checkbox"><span></span></label>');
  845. });
  846. }
  847.  
  848. /**
  849. * IG_createDM
  850. * A dialog showing a list of all media files in the post
  851. *
  852. * @param {Boolean} hasHidden
  853. * @param {Boolean} hasCheckbox
  854. * @return {void}
  855. */
  856. function IG_createDM(hasHidden, hasCheckbox){
  857. let isHidden = (hasHidden)?"hidden":"";
  858. $('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>');
  859. $('.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>');
  860.  
  861. if(hasCheckbox){
  862. $('.IG_SN_DIG .IG_SN_DIG_MAIN .IG_SN_DIG_TITLE').append(`<div style="text-align: center;" id="button_group"></div>`);
  863. $('.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>`);
  864. $('.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>`);
  865. $('.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>`);
  866. }
  867. }
  868.  
  869. /**
  870. * saveFiles
  871. * Download the specified media URL to the computer
  872. *
  873. * @param {String} downloadLink
  874. * @param {String} username
  875. * @param {String} sourceType
  876. * @param {Integer} timestamp
  877. * @param {String} filetype
  878. * @param {String} shortcode
  879. * @return {void}
  880. */
  881. function saveFiles(downloadLink,username,sourceType,timestamp,filetype,shortcode){
  882. fetch(downloadLink).then(res => {
  883. return res.blob().then(dwel => {
  884. const a = document.createElement("a");
  885. const name = username+'-'+sourceType+'-'+((USER_SETTING.RENAME_SHORTCODE && shortcode)?shortcode+'-':'')+timestamp+'.'+filetype;
  886. const originally = username + '_' + downloadLink.split('/').at(-1).split('?').at(0);
  887.  
  888. a.href = URL.createObjectURL(dwel);
  889. a.setAttribute("download", (USER_SETTING.AUTO_RENAME)?name:originally);
  890. a.click();
  891. a.remove();
  892. });
  893. });
  894. }
  895.  
  896. /**
  897. * translateText
  898. * i18n translation text
  899. *
  900. * @param {String} lang
  901. * @return {void}
  902. */
  903. function translateText(lang){
  904. return {
  905. "zh-TW": {
  906. "CLOSE": "關閉",
  907. "ALL_CHECK": "全選",
  908. "BATCH_DOWNLOAD_SELECTED": "批次下載已勾選資源",
  909. "BATCH_DOWNLOAD_DIRECT": "批次下載全部資源",
  910. "IMG": "相片",
  911. "VID": "影片",
  912. "DDL": "快速下載",
  913. "DDL_INTRO": "勾選後將直接下載點選當下位置的相片/影片",
  914. "DW": "下載",
  915. "THUMBNAIL_INTRO": "下載影片縮圖",
  916. "LOAD_BLOB_ONE": "正在載入二進位大型物件...",
  917. "LOAD_BLOB_MULTIPLE": "正在載入多個二進位大型物件...",
  918. "LOAD_BLOB_RELOAD": "正在重新載入二進位大型物件...",
  919. "NO_CHECK_RESOURCE": "您需要勾選資源才能下載。",
  920. "NO_VID_URL": "找不到影片網址",
  921. "SETTING": "設定",
  922. "AUTO_RENAME": "自動重新命名檔案",
  923. "RENAME_SHORTCODE": "重新命名檔案並包含 Shortcode",
  924. "DISABLE_VIDEO_LOOPING": "關閉影片自動循環播放",
  925. "REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE": "右鍵點擊使用者限時動態區域頭貼時重定向",
  926. "FORCE_FETCH_ALL_RESOURCES": "強制提取貼文中所有資源",
  927. "AUTO_RENAME_INTRO": "將檔案自動重新命名為以下格式:\n使用者名稱-類型-時間戳.檔案類型\n例如:instagram-photo-1670350000.jpg\n\n若設為 false,則檔案名稱將保持原始樣貌。 \n例如:instagram_321565527_679025940443063_4318007696887450953_n.jpg",
  928. "RENAME_SHORTCODE_INTRO": "將檔案自動重新命名為以下格式:\n使用者名稱-類型-Shortcode-時間戳.檔案類型\n示例:instagram-photo-CwkxyiVynpW-1670350000.jpg\n\n此功能僅在[自動重新命名檔案]設定為 TRUE 時有效。",
  929. "DISABLE_VIDEO_LOOPING_INTRO": "關閉連續短片和貼文中影片自動循環播放。",
  930. "REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE_INTRO": "右鍵點選首頁限時動態區域中的使用者頭貼時,重新導向到使用者的個人資料頁面。",
  931. "FORCE_FETCH_ALL_RESOURCES_INTRO": "透過 Instagram API 強制取得貼文中的所有資源(照片和影片),以取消每個貼文單次提取三個資源的限制。",
  932. },
  933. "zh-CN": {
  934. "CLOSE": "关闭",
  935. "ALL_CHECK": "全选",
  936. "BATCH_DOWNLOAD_SELECTED": "批量下载已勾选资源",
  937. "BATCH_DOWNLOAD_DIRECT": "批量下载全部资源",
  938. "IMG": "图像",
  939. "VID": "视频",
  940. "DDL": "便捷下载",
  941. "DDL_INTRO": "勾选后将直接下载點擊當下位置的图像/视频",
  942. "DW": "下载",
  943. "THUMBNAIL_INTRO": "下载视频缩略图",
  944. "LOAD_BLOB_ONE": "正在载入大型媒体对象...",
  945. "LOAD_BLOB_MULTIPLE": "正在载入多个大型媒体对象...",
  946. "LOAD_BLOB_RELOAD": "正在重新载入大型媒体对象...",
  947. "NO_CHECK_RESOURCE": "您需要勾選资源才能下載。",
  948. "NO_VID_URL": "找不到视频网址",
  949. "SETTING": "设置",
  950. "AUTO_RENAME": "自动重命名文件",
  951. "RENAME_SHORTCODE": "重命名文件并包含物件短码",
  952. "DISABLE_VIDEO_LOOPING": "禁用视频自动循环",
  953. "REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE": "右键单击用户故事区域头像时重定向",
  954. "FORCE_FETCH_ALL_RESOURCES": "强制抓取帖子中所有资源",
  955. "AUTO_RENAME_INTRO": "将文件自动重新命名为以下格式类型:\n用户名-类型-时间戳.文件类型\n例如:instagram-photo-1670350000.jpg\n\n若设为false,则文件名将保持原样。 \n例如:instagram_321565527_679025940443063_4318007696887450953_n.jpg",
  956. "RENAME_SHORTCODE_INTRO": "自动重命名文件为以下格式类型:\n用户名-类型-短码-时间戳.文件类型\n示例:instagram-photo-CwkxyiVynpW-1670350000.jpg\n\n它仅在[自动重命名文件]设置为 TRUE 时有效。",
  957. "DISABLE_VIDEO_LOOPING_INTRO": "禁用 Reels 和帖子中的视频自动播放。",
  958. "REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE_INTRO": "右键单击主页故事区域中的用户头像,重定向到用户的个人资料页面。",
  959. "FORCE_FETCH_ALL_RESOURCES_INTRO": "通过 Instagram API 强制获取帖子中的所有资源(照片和视频),以取消每个帖子单次抓取三个资源的限制。"
  960. },
  961. "en-US": {
  962. "CLOSE": "Close",
  963. "ALL_CHECK": "Select All",
  964. "BATCH_DOWNLOAD_SELECTED": "Download Selected Resources",
  965. "BATCH_DOWNLOAD_DIRECT": "Download All Resources",
  966. "IMG": "Image",
  967. "VID": "Video",
  968. "DDL": "Quick Download",
  969. "DDL_INTRO": "Checking it will direct download current photo/media in the posts.",
  970. "DW": "Download",
  971. "THUMBNAIL_INTRO": "Download video thumbnail.",
  972. "LOAD_BLOB_ONE": "Loading Blob Media...",
  973. "LOAD_BLOB_MULTIPLE": "Loading Blob Media and others...",
  974. "LOAD_BLOB_RELOAD": "Detect Blob Media, now reloading...",
  975. "NO_CHECK_RESOURCE": "You need to check resource to download.",
  976. "NO_VID_URL": "Can not find video url.",
  977. "SETTING": "Settings",
  978. "AUTO_RENAME": "Automatically Rename Files",
  979. "RENAME_SHORTCODE": "Rename The File and Include Shortcode",
  980. "DISABLE_VIDEO_LOOPING": "Disable Video Auto-looping",
  981. "REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE": "Redirect When Right-Clicking User Story Picture",
  982. "FORCE_FETCH_ALL_RESOURCES": "Forcing Fetch All Resources In the Post",
  983. "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",
  984. "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.",
  985. "DISABLE_VIDEO_LOOPING_INTRO": "Disable video auto-looping in reels and posts.",
  986. "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.",
  987. "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."
  988. }
  989. };
  990. }
  991.  
  992. /**
  993. * _i18n
  994. * Perform i18n translation
  995. *
  996. * @param {String} text
  997. * @return {void}
  998. */
  999. function _i18n(text){
  1000. let userLang = (lang)?lang:"en-US";
  1001. let translate = {
  1002. "zh-TW": function(){
  1003. return translateText()["zh-TW"];
  1004. },
  1005. "zh-HK": function(){
  1006. return translateText()["zh-TW"];
  1007. },
  1008. "zh-MO": function(){
  1009. return translateText()["zh-TW"];
  1010. },
  1011. "zh-CN": function(){
  1012. return translateText()["zh-CN"];
  1013. },
  1014. "en-US": function(){
  1015. return translateText()["en-US"];
  1016. }
  1017. }
  1018.  
  1019. try{
  1020. return translate[lang]()[text];
  1021. }
  1022. catch{
  1023. return translate["en-US"]()[text];
  1024. }
  1025. }
  1026.  
  1027. /**
  1028. * showSetting
  1029. * Show script settings window
  1030. *
  1031. * @return {void}
  1032. */
  1033. function showSetting(){
  1034. $('.IG_SN_DIG').remove();
  1035. IG_createDM();
  1036. $('.IG_SN_DIG #post_info').text('IG Helper Settings');
  1037.  
  1038. $('.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>`);
  1039. $('.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>`);
  1040. $('.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>`);
  1041. $('.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>`);
  1042. $('.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>`);
  1043. }
  1044.  
  1045. // Running if document is ready
  1046. $(function(){
  1047. // Close the download dialog if user click the close icon
  1048. $('body').on('click','.IG_SN_DIG_BTN,.IG_SN_DIG_BG',function(){
  1049. $('.IG_SN_DIG').remove();
  1050. });
  1051.  
  1052. $(window).keydown(function(e){
  1053. // Hot key [Alt+Q] to close the download dialog
  1054. if (e.keyCode == '81' && e.altKey){
  1055. $('.IG_SN_DIG').remove();
  1056. e.preventDefault();
  1057. }
  1058. // Hot key [Alt+W] to open the settings dialog
  1059. if (e.keyCode == '87' && e.altKey){
  1060. showSetting();
  1061. e.preventDefault();
  1062. }
  1063. });
  1064.  
  1065. $('body').on('change', '.IG_SN_DIG input',function(){
  1066. var isChecked = $(this).prop('checked');
  1067. var name = $(this).attr('id');
  1068.  
  1069. GM_setValue(name, isChecked);
  1070. USER_SETTING[name] = isChecked;
  1071. });
  1072.  
  1073. $('body').on('click','a[data-needed="direct"]',async function(){
  1074. let date = new Date().getTime();
  1075. let timestamp = Math.floor(date / 1000);
  1076. let username = ($(this).attr('data-username')) ? $(this).attr('data-username') : GL_username;
  1077.  
  1078. if(!username && $(this).attr('data-path')){
  1079. console.log('catching owner name from shortcode:',$(this).attr('data-href'));
  1080. username = await getPostOwner($(this).attr('data-path'));
  1081. }
  1082. saveFiles($(this).attr('data-href'),username,$(this).attr('data-name'),timestamp,$(this).attr('data-type'), $(this).attr('data-path'));
  1083. });
  1084.  
  1085. // Running if user left-click download icon in stories
  1086. $('body').on('click','.IG_DWSTORY',function(){
  1087. onStory(true);
  1088. });
  1089.  
  1090. // Running if user left-click download icon in stories
  1091. $('body').on('click','.IG_DWSTORY_THUMBNAIL',function(){
  1092. onStoryThumbnail(true);
  1093. });
  1094.  
  1095. // Running if user left-click download icon in profile
  1096. $('body').on('click','.IG_DWPROFILE',function(e){
  1097. e.stopPropagation();
  1098. onProfileAvatar(true);
  1099. });
  1100.  
  1101. // Running if user left-click download icon in highlight stories
  1102. $('body').on('click','.IG_DWHISTORY',function(){
  1103. onHighlightsStory(true);
  1104. });
  1105.  
  1106. // Running if user left-click download icon in highlight stories
  1107. $('body').on('click','.IG_DWHISTORY_THUMBNAIL',function(){
  1108. onHighlightsStoryThumbnail(true);
  1109. });
  1110.  
  1111. // Running if user left-click download icon in reels
  1112. $('body').on('click','.IG_REELS',function(){
  1113. onReels(true,true);
  1114. });
  1115.  
  1116. // Running if user left-click download icon in reels
  1117. $('body').on('click','.IG_REELS_THUMBNAIL',function(){
  1118. onReels(true,false);
  1119. });
  1120.  
  1121. // Running if user right-click profile picture in stories area
  1122. $('body').on('contextmenu','button[role="menuitem"]',function(){
  1123. if(location.href === 'https://www.instagram.com/' && USER_SETTING.REDIRECT_RIGHT_CLICK_USER_STORY_PICTURE){
  1124. if($(this).find('canvas._aarh').length > 0){
  1125. location.href = 'https://www.instagram.com/'+$(this).children('div').last().text();
  1126. }
  1127. }
  1128. });
  1129.  
  1130. $('body').on('change', '.IG_SN_DIG_TITLE .checkbox', function(){
  1131. var isChecked = $(this).find('input').prop('checked');
  1132. $('.IG_SN_DIG_BODY .inner_box').each(function(){
  1133. $(this).prop('checked', isChecked);
  1134. });
  1135. });
  1136.  
  1137. $('body').on('change', '.IG_SN_DIG_BODY .inner_box', function(){
  1138. var checked = $('.IG_SN_DIG_BODY .inner_box:checked').length;
  1139. var total = $('.IG_SN_DIG_BODY .inner_box').length;
  1140.  
  1141.  
  1142. $('.IG_SN_DIG_TITLE .checkbox').find('input').prop('checked', checked == total);
  1143. });
  1144.  
  1145. $('body').on('click', '.IG_SN_DIG_TITLE #batch_download_selected', function(){
  1146. let index = 0;
  1147. $('.IG_SN_DIG_BODY a[data-needed="direct"]').each(function(){
  1148. if($(this).prev().prop('checked')){
  1149. $(this).click();
  1150. index++;
  1151. }
  1152. });
  1153.  
  1154. if(index == 0){
  1155. alert(_i18n('NO_CHECK_RESOURCE'));
  1156. }
  1157. });
  1158.  
  1159. $('body').on('click', '.IG_SN_DIG_TITLE #batch_download_direct', function(){
  1160. $('.IG_SN_DIG_BODY a[data-needed="direct"]').each(function(){
  1161. $(this).click();
  1162. });
  1163. });
  1164. });
  1165. })(jQuery);