forked from raj-khare/yt-migrate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
222 lines (209 loc) · 6.03 KB
/
main.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
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
const CLIENT_ID =
"CLIENT_ID";
const API_KEY = "API_KEY";
const signinOldAccount = document.getElementById("signin-old");
const signinNewAccount = document.getElementById("signin-new");
const notifications = document.getElementById("notifications");
const transfer = document.getElementById("transfer");
const oldData = document.getElementById("old-data");
const completed = document.getElementById("completed");
const remaining = document.getElementById("remaining");
const already = document.getElementById("already");
const stats = document.getElementById("stats");
//Polyfill
if (!Promise.allSettled) {
Promise.allSettled = function (promises) {
return Promise.all(
promises.map((p) =>
Promise.resolve(p).then(
(value) => ({
state: "fulfilled",
value,
}),
(reason) => ({
state: "rejected",
reason,
})
)
)
);
};
}
const USER_DATA = {
oldSubscriptions: {},
currentSubscriptions: {},
alreadyInAccount: {},
newSubscriptionsCount: 0,
};
gapi.load("client:auth2", () => {
gapi.auth2.init({
client_id: CLIENT_ID,
fetch_basic_profile: false,
scope: "https://www.googleapis.com/auth/youtube",
});
});
const notify = (msg) => {
notifications.textContent = msg;
};
const authenticate = () => {
notify("Signing in...");
return gapi.auth2
.getAuthInstance()
.signIn({
scope: "https://www.googleapis.com/auth/youtube",
prompt: "select_account",
})
.then(
() => {
notify("Sign-in successful");
},
(err) => {
throw new Error(err.error);
}
);
};
const loadClient = () => {
gapi.client.setApiKey(API_KEY);
return gapi.client
.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(null, () => {
throw new Error("Client loading failed. Please try again");
});
};
const getSubscriptions = async (type, pageToken = null) => {
notify(`Fetching your ${type} subscriptions...`);
try {
const userData =
type === "old"
? USER_DATA.oldSubscriptions
: USER_DATA.currentSubscriptions;
const response = await gapi.client.youtube.subscriptions.list({
part: "snippet",
mine: true,
maxResults: 50,
pageToken: pageToken ? pageToken : undefined,
order: 'alphabetical',
});
response.result.items.forEach((element) => {
userData[element.snippet.resourceId.channelId] = element.snippet.title;
});
nextPage = response.result.nextPageToken;
if (nextPage)
await getSubscriptions(type, (pageToken = response.result.nextPageToken));
else {
notify("Subscriptions fetched successfully");
}
} catch (err) {
throw new Error(err.result.error.errors[0].reason);
}
};
const transferSubscriptions = () => {
notify("Transferring subsciptions...");
promises = [];
for (let [id, name] of Object.entries(USER_DATA.oldSubscriptions)) {
if (!(id in USER_DATA.currentSubscriptions)) {
// New subscription
USER_DATA.newSubscriptionsCount += 1;
promises.push(
new Promise((res, rej) => {
gapi.client.youtube.subscriptions
.insert({
part: "snippet",
resource: {
snippet: {
resourceId: {
kind: "youtube#channel",
channelId: id,
},
},
},
})
.then(() => {
res({ name });
})
.catch(() => {
rej({ name });
});
})
);
} else {
USER_DATA.alreadyInAccount[id] = name;
}
}
return Promise.allSettled(promises);
};
signinOldAccount.onclick = async () => {
try {
await authenticate();
await loadClient();
signinOldAccount.remove();
await getSubscriptions("old");
notify(
"Old subscriptions fetched successfully. Please sign in with your new account"
);
let content = `| ${
Object.keys(USER_DATA.oldSubscriptions).length
} subscriptions |`;
oldData.textContent = content;
signinNewAccount.classList.remove("d-none");
} catch (err) {
notify(err.message);
}
};
signinNewAccount.onclick = async () => {
try {
await authenticate();
await loadClient();
signinNewAccount.remove();
notify("Signed in with new account");
await getSubscriptions("current");
notify("Current subscriptions fetched successfully!");
transfer.classList.remove("d-none");
} catch (err) {
notify(err.message);
}
};
const addSubscriptionToDom = (name, el) => {
let li = document.createElement("li");
li.appendChild(document.createTextNode(name));
li.classList.add("list-group-item");
el.appendChild(li);
};
transfer.onclick = async () => {
try {
const successSubs = [];
const failedSubs = [];
const results = await transferSubscriptions();
console.log(results);
results.forEach((result) => {
if (result.status == "fulfilled") {
successSubs.push(result.value.name);
} else {
failedSubs.push(result.reason.name);
}
});
if (successSubs.length === USER_DATA.newSubscriptionsCount)
notify(
`${successSubs.length}/${
USER_DATA.newSubscriptionsCount
} new subscriptions transferred successfully! ${
Object.keys(USER_DATA.oldSubscriptions).length -
USER_DATA.newSubscriptionsCount
} subscriptions are already in your account.`
);
else
notify(
`${successSubs.length}/${USER_DATA.newSubscriptionsCount} new subscriptions transferred. You may have exhausted the quota. Please try remaining tomorrow`
);
stats.classList.remove("d-none");
stats.classList.add("d-flex");
successSubs.forEach((el) => addSubscriptionToDom(el, completed));
failedSubs.forEach((el) => addSubscriptionToDom(el, remaining));
Object.values(USER_DATA.alreadyInAccount).forEach((el) =>
addSubscriptionToDom(el, already)
);
transfer.remove();
} catch (err) {
notify(err.message);
}
};