-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1572 lines (1356 loc) · 61.9 KB
/
Copy pathmain.js
File metadata and controls
1572 lines (1356 loc) · 61.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { app, BrowserWindow, shell, ipcMain, session, Tray, Menu, dialog, nativeImage, clipboard, Notification } = require("electron");
const DiscordRPC = require('discord-rpc');
const clientId = '1327795288290758768';
let rpc = null;
const Store = require("electron-store");
const path = require("path");
const axios = require('axios');
const stream = require('stream');
const util = require('util');
const fs = require('fs');
const fetch = require('node-fetch');
const pipeline = util.promisify(stream.pipeline);
const allDownloader = require("all-downloader");
const Updater = require('./updater');
const sharp = require('sharp');
const { cwd } = require("process");
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
} else {
app.on('second-instance', (event, commandLine, workingDirectory) => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
app.whenReady().then(async () => {
const trayIconPath = path.join(__dirname, 'assets', 'tray.png');
if (!require('fs').existsSync(trayIconPath)) {
throw new Error('Required tray icon missing');
}
if (settingsStore.get('autoUpdate')) {
const updater = new Updater();
await updater.checkForUpdates();
}
if (settingsStore.get('discordRPC')) {
try {
await initDiscordRPC();
} catch (error) {
console.log('Failed to initialize Discord RPC on startup:', error.message);
}
}
app.setName("Freakygram");
if (process.platform === 'win32') {
app.setAppUserModelId('com.freakygram.desktop');
app.setPath('userData', path.join(app.getPath('appData'), 'Freakygram'));
}
mainWindow = createWindow();
createTray();
if (process.platform === "win32") {
mainWindow.setIcon(path.join(__dirname, "assets", "icon.ico"));
}
}).catch(error => {
console.error('Failed to initialize app:', error);
app.quit();
});
const store = new Store({
name: "config",
encryptionKey: "instagram-desktop-app",
clearInvalidConfig: true,
defaults: {
windowState: { width: 1200, height: 800 },
accounts: [],
currentAccount: null
},
});
const settingsStore = new Store({
name: "settings",
defaults: {
closeToTray: false,
notifications: false,
messageNotifications: false,
downloadPath: app.getPath('downloads'),
discordRPC: false,
autoUpdate: true,
alwaysOnTop: false,
showReelCount: true,
autoScrollReels: false
}
});
const accountStores = new Map();
function getAccountStore(username) {
if (!accountStores.has(username)) {
accountStores.set(username, new Store({
name: `account_${username}`,
encryptionKey: "instagram-desktop-app",
defaults: {}
}));
}
return accountStores.get(username);
}
let lastScrollTime = 0;
const SCROLL_COOLDOWN = 1000;
async function handleReelAutoScroll(url) {
const autoScrollEnabled = settingsStore.get('autoScrollReels');
if (!autoScrollEnabled) return;
try {
let requestUrl = url.replace("reels", "p");
if (url.endsWith("/reels/")) {
console.log('[AutoScroll] Skipping main reels page');
return;
}
console.log('[AutoScroll] URL:', requestUrl);
let scrollDelay = 5000;
const cookies = await mainWindow.webContents.session.cookies.get({
url: 'https://www.instagram.com'
});
const cookieHeader = cookies
.map(cookie => `${cookie.name}=${cookie.value}`)
.join('; ');
try {
const videoData = await allDownloader.parse(requestUrl, {
headers: {
'Cookie': cookieHeader,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
}
});
if (!videoData) {
console.log('[AutoScroll] No video data found, using default delay');
} else {
console.log('[AutoScroll] Video duration:', videoData.video_duration);
scrollDelay = (videoData.video_duration * 1000);
}
} catch (igError) {
if (igError.message.includes('401')) {
console.log('[AutoScroll] Authentication required');
return;
}
console.log('[AutoScroll] Failed to get video data, using default delay:', igError);
}
setTimeout(() => {
try {
const now = Date.now();
if (now - lastScrollTime < SCROLL_COOLDOWN) {
console.log('[AutoScroll] Manual scroll detected, skipping');
return;
}
const bounds = mainWindow.getBounds();
const centerX = Math.floor(bounds.width / 2);
const centerY = Math.floor(bounds.height / 2);
mainWindow.webContents.sendInputEvent({
type: 'mouseWheel',
deltaY: -200,
x: centerX,
y: centerY
});
reelUrlHistory = [];
lastReelUrl = '';
lastScrollTime = now;
} catch (e) {
console.error('[AutoScroll] Scroll event failed:', e);
}
}, scrollDelay);
} catch (error) {
console.error('[AutoScroll] Error:', error);
}
}
let currentActivity = 'browsing';
let rpcStartTimestamp = Date.now();
let isRPCConnected = false;
let reelCount = 0;
let lastReelUrl = '';
const MAX_REEL_HISTORY = 10;
let reelUrlHistory = [];
async function initDiscordRPC() {
try {
if (rpc) {
try {
await rpc.destroy().catch(() => { });
} catch (e) { }
rpc = null;
}
rpc = new DiscordRPC.Client({ transport: 'ipc' });
rpc.on('ready', () => {
console.log('Discord RPC connected');
isRPCConnected = true;
updateRPCActivity(currentActivity);
});
rpc.on('disconnected', () => {
console.log('Discord RPC disconnected');
isRPCConnected = false;
rpc = null;
});
const connectionTimeout = setTimeout(() => {
console.log('Discord RPC connection timed out');
if (rpc) {
rpc.destroy().catch(() => {});
rpc = null;
}
isRPCConnected = false;
}, 5000);
await rpc.login({ clientId }).then(() => {
clearTimeout(connectionTimeout);
}).catch((error) => {
clearTimeout(connectionTimeout);
if (error.message.includes('ENOENT') || error.message.includes('Could not connect')) {
console.log('Discord is not running, RPC disabled');
} else {
console.error('Discord RPC connection failed:', error.message);
}
isRPCConnected = false;
rpc = null;
});
} catch (error) {
console.log('Discord RPC initialization failed:', error.message);
isRPCConnected = false;
rpc = null;
}
}
async function destroyRPC() {
if (!rpc) return;
try {
isRPCConnected = false;
await rpc.destroy().catch((error) => {
console.log('Error during RPC cleanup:', error.message);
});
} catch (error) {
console.log('Error destroying RPC:', error.message);
} finally {
rpc = null;
}
}
function updateRPCActivity(activity) {
if (!rpc || !isRPCConnected) return;
try {
currentActivity = activity;
const showReelCount = settingsStore.get('showReelCount');
const activities = {
browsing: {
details: 'Browsing Feed',
largeImageKey: "instagram",
smallImageKey: 'feed',
},
reels: {
details: 'Watching Reels',
state: showReelCount ? `I have watched ${reelCount/2} reel` + (reelCount/2 !== 1 ? 's' : '') : undefined, // /2 because for some reason it doubles
largeImageKey: "instagram",
smallImageKey: 'reels',
smallImageText: 'Reels'
},
messages: {
details: 'Reading Messages',
largeImageKey: "instagram",
smallImageKey: 'messages',
smallImageText: 'Messages'
}
};
rpc.setActivity({
...activities[activity],
startTimestamp: rpcStartTimestamp,
largeImageKey: 'instagram',
largeImageText: 'Freakygram',
buttons: [
{ label: 'Download App', url: 'https://github.com/jqms/Freakygram/releases' }
]
}).catch((error) => {
console.log('Failed to update Discord RPC activity:', error.message);
isRPCConnected = false;
rpc = null;
});
} catch (error) {
console.log('Discord RPC update error:', error.message);
isRPCConnected = false;
rpc = null;
}
}
let mainWindow;
let accountWindow;
let isQuitting = false;
let tray = null;
let settingsWindow = null;
function createSvgIcon(svg) {
return nativeImage.createFromBuffer(Buffer.from(svg));
}
const fetchInstagramVideo = async (url) => {
try {
console.log(url)
const data = await allDownloader.parse(url);
return data;
} catch (error) {
console.error("Failed to fetch video:", error);
return null;
}
}
async function download(url) {
try {
const videoData = await fetchInstagramVideo(url.replace("reels", "p"));
console.log('Video data:', videoData);
let filename = videoData.shortcode + '.mp4';
const { canceled, filePath } = await dialog.showSaveDialog({
defaultPath: filename,
filters: [
{ name: 'MP4 Videos', extensions: ['mp4'] },
{ name: 'All Files', extensions: ['*'] }
],
properties: ['createDirectory']
});
if (canceled) {
return { success: false, error: 'File save cancelled by user' };
}
const response = await fetch(videoData.video_url);
if (!response.ok) {
throw new Error(`Unexpected response: ${response.statusText}`);
}
const buffer = await response.buffer();
fs.writeFileSync(filePath, buffer);
return { success: true, filePath };
} catch (error) {
console.error('Download error:', error);
return { success: false, error: error.message };
}
}
const icons = {
copy: `<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M4 4v8h8V4H4zM3 2h10v11H3V2zm-2 3h1v9h9v1H1V5z" fill="currentColor"/>
</svg>`,
browser: `<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2 2h12v12H2V2zm1 4h10v7H3V6zm0-3h10v2H3V3zm2 1h-1V3h1v1zm2 0H6V3h1v1zm2 0H8V3h1v1z" fill="currentColor"/>
</svg>`,
close: `<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M13.4 3.7L12 2.3 8 6.3 4 2.3 2.6 3.7 6.6 7.7l-4 4 1.4 1.4 4-4 4 4 1.4-1.4-4-4 4-4z" fill="currentColor"/>
</svg>`,
download: `<svg width="32" height="32" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14 9.333a.667.667 0 0 0-.667.667v2.667a.667.667 0 0 1-.666.666H3.333a.667.667 0 0 1-.666-.666V10a.667.667 0 0 0-1.334 0v2.667A2 2 0 0 0 3.333 14.667h9.334A2 2 0 0 0 14.667 12.667V10A.667.667 0 0 0 14 9.333zm-6.473 1.14a.667.667 0 0 0 .22.14.627.627 0 0 0 .506 0 .667.667 0 0 0 .22-.14l2.667-2.666a.667.667 0 0 0-.946-.947L8.667 8.393V2a.667.667 0 0 0-1.334 0v6.393L5.807 6.86a.667.667 0 1 0-.947.947l2.667 2.666z" fill="currentColor"/>
</svg>`,
};
app.on('before-quit', () => {
isQuitting = true;
destroyRPC();
try {
const tempDir = path.join(__dirname, 'temp');
if (fs.existsSync(tempDir)) {
const files = fs.readdirSync(tempDir);
files.forEach(file => {
try {
fs.unlinkSync(path.join(tempDir, file));
} catch (e) {}
});
fs.rmdirSync(tempDir);
}
} catch (error) {
console.error('Error cleaning temp directory:', error);
}
});
function injectDownloadButton() {
return `
(function() {
function addDownloadButtons() {
if (!window.location.href.includes('reels')) return;
const shareBtns = document.querySelectorAll('[aria-label="Share"]');
shareBtns.forEach(shareBtn => {
const container = shareBtn?.parentElement?.parentElement;
if (!container) return;
const existingBtn = container.parentElement.querySelector('[data-testid="download-button"]');
if (existingBtn) return;
const newDownloadBtn = document.createElement('div');
newDownloadBtn.setAttribute('data-testid', 'download-button');
newDownloadBtn.className = container.className;
newDownloadBtn.innerHTML = \`
<div class="x1i10hfl x1qjc9v5 xjbqb8w xjqpnuy xa49m3k xqeqjp1 x2hbi6w x13fuv20 xu3j5b3 x1q0q8m5 x26u7qi x972fbf xcfux6l x1qhh985 xm0m39n x9f619 x1ypdohk xdl72j9 x2lah0s xe8uvvx xdj266r x11i5rnm xat24cr x1mh8g0r x2lwn1j xeuugli xexx8yu x4uap5 x18d9i69 xkhd6sd x1n2onr6 x16tdsg8 x1hl2dhg xggy1nq x1ja2u2z x1t137rt x1o1ewxj x3x9cwd x1e5q0jg x13rtm0m x3nfvp2 x1q0g3np x87ps6o x1lku1pv x1a2a7pz x1mywscw" role="button" tabindex="0">
<svg aria-label="Download" class="x1lliihq x1n2onr6 xyb1xck" fill="currentColor" height="24" role="img" viewBox="0 0 24 24" width="24">
<title>Download</title>
<path d="M21,14a1,1,0,0,0-1,1v4a1,1,0,0,1-1,1H5a1,1,0,0,1-1-1V15a1,1,0,0,0-2,0v4a3,3,0,0,0,3,3H19a3,3,0,0,0,3-3V15A1,1,0,0,0,21,14Zm-9.71,1.71a1,1,0,0,0,.33.21.94.94,0,0,0,.76,0,1,1,0,0,0,.33-.21l4-4a1,1,0,0,0-1.42-1.42L13,12.59V3a1,1,0,0,0-2,0v9.59l-2.29-2.3a1,1,0,1,0-1.42,1.42Z"/>
</svg>
</div>
\`;
if (window.electron) {
const clickHandler = async (e) => {
e.preventDefault();
e.stopPropagation();
try {
const reelArticle = container.closest('article');
const reelLink = window.location.href;
if (reelLink) {
const videoUrl = reelLink;
const result = await window.electron.downloadVideo(videoUrl);
} else {
console.error('No reel link found');
}
} catch (error) {
console.error('Download failed:', error);
}
};
newDownloadBtn.querySelector('div').addEventListener('click', clickHandler);
container.parentElement.insertBefore(newDownloadBtn, container.nextSibling);
}
});
}
addDownloadButtons();
const observer = new MutationObserver((mutations) => {
addDownloadButtons();
});
observer.observe(document.body, {
childList: true,
subtree: true
});
window._downloadButtonObserver = observer;
})();
`;
}
function injectMessageNotificationHandler() {
return `
(function() {
if (window._messageNotificationHandlerInjected) {
return;
}
window._messageNotificationHandlerInjected = true;
const startupTime = Date.now();
const STARTUP_DELAY = 6000;
let lastKnownMessages = new Set();
let recentNotifications = new Map();
function extractMessageNotifications() {
const messageNotificationSelectors = [
'div[class*="xdj266r"][class*="x14z9mp"][class*="xat24cr"][class*="x1lziwak"][style*="--height: 80px; --width: 350px"]',
'div[style*="--height: 80px; --width: 350px"]',
'div[class*="xdj266r"][class*="xat24cr"]:has(img[alt*="profile picture"]):has(span[style*="-webkit-line-clamp"])'
];
const messageElements = new Set();
messageNotificationSelectors.forEach(selector => {
try {
const elements = document.querySelectorAll(selector);
console.log('Message notification selector:', selector, '- found', elements.length, 'elements');
elements.forEach(el => {
const hasAvatar = el.querySelector('img[alt*="profile picture"], img[alt*="avatar"]');
const hasMessageText = el.querySelector('span[style*="-webkit-line-clamp"]');
const hasUsername = el.querySelector('span[class*="x1lliihq"][class*="x193iq5w"]');
if (hasAvatar && hasMessageText && hasUsername) {
const containerRect = el.getBoundingClientRect();
const isNotificationSize = containerRect.width >= 300 && containerRect.height >= 70;
if (isNotificationSize) {
messageElements.add(el);
console.log('Valid message notification found:', el);
} else {
console.log('Element too small to be message notification:', containerRect);
}
} else {
console.log('Element missing required components:', {
hasAvatar: !!hasAvatar,
hasMessageText: !!hasMessageText,
hasUsername: !!hasUsername
});
}
});
} catch (e) {
console.log('Selector error:', selector, e);
}
});
console.log('Valid message notification elements found:', messageElements.size);
const newMessages = [];
messageElements.forEach(element => {
try {
let username = null;
const usernameSelectors = [
'span.x1lliihq.x193iq5w.x6ikm8r.x10wlt62.xlyipyv.xuxw1ft',
'span[class*="x1lliihq"][class*="x193iq5w"]',
'span[class*="xlyipyv"][class*="xuxw1ft"]'
];
for (const selector of usernameSelectors) {
const usernameEl = element.querySelector(selector);
if (usernameEl && usernameEl.textContent.trim()) {
username = usernameEl.textContent.trim();
break;
}
}
let messageContent = null;
const messageSelectors = [
'span[style*="-webkit-box-orient: vertical"][style*="-webkit-line-clamp: 2"]',
'span[class*="x1lliihq"][class*="x1plvlek"][style*="-webkit-line-clamp"]',
'span[class*="xo1l8bm"][class*="x1roi4f4"]'
];
for (const selector of messageSelectors) {
const messageEl = element.querySelector(selector);
if (messageEl && messageEl.textContent.trim()) {
messageContent = messageEl.textContent.trim();
break;
}
}
let avatarUrl = null;
const avatarSelectors = [
'img[alt="Instagram avatar profile picture"]',
'img[alt*="avatar"]',
'img[alt*="profile picture"]',
'img[class*="x15mokao"]'
];
for (const selector of avatarSelectors) {
const avatarImg = element.querySelector(selector);
if (avatarImg && avatarImg.src) {
avatarUrl = avatarImg.src;
break;
}
}
if (username && messageContent) {
const messageId = \`\${username}:\${messageContent}\`;
const notificationId = \`\${username}:\${messageContent}:\${Date.now()}\`;
const now = Date.now();
const recentThreshold = 30000;
for (const [id, timestamp] of recentNotifications.entries()) {
if (now - timestamp > recentThreshold) {
recentNotifications.delete(id);
}
}
let isDuplicate = false;
for (const [id, timestamp] of recentNotifications.entries()) {
if (id.startsWith(\`\${username}:\${messageContent}:\`)) {
isDuplicate = true;
break;
}
}
if (!lastKnownMessages.has(messageId) && !isDuplicate) {
lastKnownMessages.add(messageId);
recentNotifications.set(notificationId, now);
newMessages.push({
username,
content: messageContent,
avatarUrl,
timestamp: now
});
console.log('New message detected:', { username, messageContent, avatarUrl });
console.log('Message tracking - lastKnown size:', lastKnownMessages.size, 'recent size:', recentNotifications.size);
} else {
console.log('Message filtered out - inLastKnown:', lastKnownMessages.has(messageId), 'isDuplicate:', isDuplicate);
}
}
} catch (error) {
console.error('Error extracting message notification:', error);
}
});
return newMessages;
}
function checkForNewMessages() {
if (!window.electron) return;
const now = Date.now();
if (now - startupTime < STARTUP_DELAY) {
console.log('Still in startup delay period, ignoring notifications for', Math.ceil((STARTUP_DELAY - (now - startupTime)) / 1000), 'more seconds');
return;
}
console.log('Checking for new messages...');
const newMessages = extractMessageNotifications();
console.log('Found', newMessages.length, 'new messages');
newMessages.forEach(message => {
window.electron.handleNewMessage(message);
});
}
setTimeout(() => {
console.log('Startup delay complete, message notifications now active');
checkForNewMessages();
}, STARTUP_DELAY + 2000);
if (window._messageNotificationObserver) {
window._messageNotificationObserver.disconnect();
}
const observer = new MutationObserver((mutations) => {
let shouldCheck = false;
mutations.forEach(mutation => {
if (mutation.addedNodes.length > 0) {
Array.from(mutation.addedNodes).forEach(node => {
if (node.nodeType === 1 && (
node.classList?.contains('xdj266r') ||
node.querySelector?.('div[class*="xdj266r"]') ||
node.querySelector?.('img[alt*="avatar"]') ||
node.querySelector?.('img[alt*="profile picture"]')
)) {
shouldCheck = true;
}
});
}
});
if (shouldCheck) {
setTimeout(checkForNewMessages, 500);
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
setInterval(checkForNewMessages, 5000);
window.testMessageDetection = () => {
const messages = extractMessageNotifications();
console.log('Detected messages:', messages);
return messages;
};
window._messageNotificationObserver = observer;
})();
`;
}
function injectSettingsButton() {
return `
(function() {
let menuObserver = null;
function setupMenuObserver() {
if (menuObserver) {
menuObserver.disconnect();
}
menuObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.addedNodes.length) {
const menu = document.querySelector('div[role="dialog"]');
if (menu) {
checkAndInjectButton();
}
}
}
});
menuObserver.observe(document.body, {
childList: true,
subtree: true
});
}
function checkAndInjectButton() {
try {
const menuList = document.querySelector('div[role="dialog"] .x1y1aw1k');
if (!menuList) return false;
const existingBtn = menuList.querySelector('[data-testid="freakygram-settings"]');
if (existingBtn) return false;
const templateButton = Array.from(menuList.children).find(el =>
el.textContent.includes('Settings') &&
!el.textContent.includes('Freakygram')
);
if (!templateButton) return false;
const settingsBtn = templateButton.cloneNode(true);
settingsBtn.className = templateButton.className;
settingsBtn.setAttribute('data-testid', 'freakygram-settings');
settingsBtn.setAttribute('role', 'button');
settingsBtn.setAttribute('tabindex', '0');
settingsBtn.style.backgroundColor = 'rgb(var(--ig-banner-background))';
const xols6we = document.querySelectorAll('.xols6we');
xols6we.forEach(el => {
el.style.height = '1px';
});
const hoverDiv = settingsBtn.querySelector('div[role="none"]');
if (hoverDiv) {
hoverDiv.className = templateButton.querySelector('div[role="none"]').className;
hoverDiv.setAttribute('role', 'none');
hoverDiv.setAttribute('data-visualcompletion', 'ignore');
const originalHoverStyles = window.getComputedStyle(templateButton.querySelector('div[role="none"]'));
hoverDiv.style.cssText = originalHoverStyles.cssText;
hoverDiv.style.backgroundColor = 'transparent';
settingsBtn.addEventListener('mouseenter', () => {
hoverDiv.style.backgroundColor = 'rgba(var(--ig-hover-overlay))';
hoverDiv.style.opacity = '1';
hoverDiv.style.borderRadius = '8px';
hoverDiv.classList.remove('xg01cxk');
});
settingsBtn.addEventListener('mouseleave', () => {
hoverDiv.style.backgroundColor = 'transparent';
});
}
const textSpan = settingsBtn.querySelector('span.x1lliihq span');
if (textSpan) textSpan.textContent = 'Freakygram Settings';
settingsBtn.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
window.electron.showSettings();
});
const switchAccountsBtn = Array.from(menuList.children).find(el =>
el.textContent.includes('Switch accounts')
);
if (!switchAccountsBtn) return false;
menuList.insertBefore(settingsBtn, switchAccountsBtn);
return true;
} catch (error) {
console.error('[Freakygram] Error:', error);
return false;
}
}
setupMenuObserver();
checkAndInjectButton();
window.addEventListener('unload', () => {
if (menuObserver) {
menuObserver.disconnect();
}
});
})();
`;
}
function getStoryMedia(x, y) {
return `
(function() {
const element = document.elementFromPoint(${x}, ${y});
const storyContainer = element.closest('.x5yr21d.x1n2onr6.xh8yej3');
if (!storyContainer) return null;
const img = storyContainer.querySelector('img.xl1xv1r');
const video = storyContainer.querySelector('video');
if (img) {
return {
type: 'image',
url: img.src,
username: document.querySelector('a[role="link"]')?.textContent || 'story'
};
}
if (video) {
return {
type: 'video',
url: video.src,
username: document.querySelector('a[role="link"]')?.textContent || 'story'
};
}
return null;
})()
`;
}
function getFeedVideo(x, y) {
return `
(function() {
try {
let element = document.elementFromPoint(${x}, ${y});
let videoElement = element.closest('video');
if (!videoElement) return null;
let article = videoElement.closest('article');
if (!article) return null;
let postLink = article.querySelector('a[href*="/p/"]');
if (!postLink) return null;
let postId = postLink.href.match(/\/p\/([^/?]+)/)[1];
if (!postId) return null;
let username = article.querySelector('._aacl._aaco._aacw._aacx._aad7._aade')?.textContent || 'video';
return {
type: 'video',
postId: postId,
username: username
};
} catch(e) {
console.error('Video detection error:', e);
return null;
}
})()`;
}
function createWindow() {
const defaultState = { width: 1200, height: 800, x: undefined, y: undefined };
const windowState = store.get("windowState", defaultState);
const settings = settingsStore.store;
mainWindow = new BrowserWindow({
...windowState,
frame: true,
autoHideMenuBar: true,
backgroundColor: '#000000',
alwaysOnTop: settings.alwaysOnTop,
titleBarOverlay: {
color: '#000000',
symbolColor: '#FFFFFF'
},
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: false,
contextIsolation: true,
partition: 'persist:instagram',
webSecurity: true
}
});
try {
const ses = session.fromPartition('persist:instagram');
mainWindow.webContents.session.setPermissionRequestHandler((webContents, permission, callback) => {
if (permission === 'notifications') {
callback(settings.notifications || settings.messageNotifications);
} else {
callback(false);
}
});
mainWindow.webContents.on('context-menu', async (event, params) => {
const { x, y } = params;
function upperFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
try {
const storyMedia = await mainWindow.webContents.executeJavaScript(getStoryMedia(params.x, params.y));
if (storyMedia) {
const menu = Menu.buildFromTemplate([
{
label: `Copy ${upperFirstLetter(storyMedia.type)}`,
icon: createSvgIcon(icons.copy),
click: async () => {
try {
if (storyMedia.type === 'image') {
await mainWindow.webContents.copyImageAt(x, y);
} else {
await mainWindow.webContents.copyVideoAt(x, y);
}
} catch (error) {
console.error('Copy failed:', error);
}
}
},
{
label: `Save ${upperFirstLetter(storyMedia.type)}`,
icon: createSvgIcon(icons.download),
click: async () => {
const { canceled, filePath } = await dialog.showSaveDialog(mainWindow, {
defaultPath: path.join(
app.getPath('downloads'),
`instagram_story_${storyMedia.username}_${Date.now()}.${storyMedia.type === 'video' ? 'mp4' : 'jpg'}`
),
filters: [
{
name: storyMedia.type === 'video' ? 'Video' : 'Image',
extensions: [storyMedia.type === 'video' ? 'mp4' : 'jpg']
}
]
});
if (!canceled && filePath) {
mainWindow.webContents.downloadURL(storyMedia.url);
mainWindow.webContents.session.on('will-download', (event, item) => {
item.setSavePath(filePath);
});
}
}
},
{
label: 'Copy URL',
icon: createSvgIcon(icons.copy),
click: () => clipboard.writeText(storyMedia.url)
}
]);
menu.popup();
}
const imageUrl = await mainWindow.webContents.executeJavaScript(`
(function() {
const element = document.elementFromPoint(${x}, ${y});
const container = element.closest('._aagu');
if (container) {
const img = container.querySelector('._aagv img');
return img ? img.src : null;
}
return null;
})()
`);
if (imageUrl) {
const getFilename = (url) => {
try {
const urlObj = new URL(url);
const pathParts = urlObj.pathname.split('/');
const filename = pathParts[pathParts.length - 1];
return filename.split('?')[0].replace(/[^\w\-_.]/g, '');
} catch (e) {
return 'instagram_image.jpg';
}
};
const menu = Menu.buildFromTemplate([
{
label: 'Copy Image',
icon: createSvgIcon(icons.copy),
click: async () => {
try {
const imageData = await mainWindow.webContents.executeJavaScript(`
(function() {
const element = document.elementFromPoint(${x}, ${y});
const img = element.closest('._aagu').querySelector('._aagv img');
return img ? {
src: img.src,
naturalWidth: img.naturalWidth,
naturalHeight: img.naturalHeight
} : null;
})()
`);
if (imageData) {
await mainWindow.webContents.copyImageAt(x, y);