forked from igdmapps/igdm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
71 lines (61 loc) · 1.72 KB
/
utils.js
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
const fs = require('fs');
const Client = require('instagram-private-api').V1;
const app = require('electron').app;
const path = require('path');
const buildAndGetStoragePath = () => {
const storagePath = path.join(app.getPath('userData'), 'session-cookie')
if (!fs.existsSync(storagePath)) {
// make directory if it doesn't exist
fs.mkdirSync(storagePath)
}
return storagePath
}
const canUseFileStorage = () => {
try {
fs.accessSync(`${app.getPath('userData')}/`, fs.W_OK);
return true
} catch (error) {
return false
}
}
const guessUsername = () => {
let username;
if (canUseFileStorage()) {
const files = fs.readdirSync(`${buildAndGetStoragePath()}`);
if (files.length && files[0].endsWith('.json')) {
username = files[0].slice(0, -5);
}
}
return username;
}
const getCookieStorage = (filePath) => {
let storage;
let username;
if (canUseFileStorage()) {
if (!filePath && (username = guessUsername())) {
filePath = `${username}.json`
}
if (filePath) storage = new Client.CookieFileStorage(`${buildAndGetStoragePath()}/${filePath}`);
} else {
storage = new Client.CookieMemoryStorage();
}
return storage;
}
const clearCookieFiles = () => {
// delete all session storage
if (canUseFileStorage() && fs.existsSync(buildAndGetStoragePath())) {
fs.readdirSync(`${buildAndGetStoragePath()}`).forEach((filename) => {
fs.unlinkSync(`${buildAndGetStoragePath()}/${filename}`);
})
}
}
const getDevice = (username) => {
let device;
username = username || guessUsername();
if (username) device = new Client.Device(username);
return device;
}
module.exports = {
canUseFileStorage, guessUsername,
getCookieStorage, clearCookieFiles, getDevice
}