-
Notifications
You must be signed in to change notification settings - Fork 1
/
TrackFinder.js
317 lines (279 loc) · 9.1 KB
/
TrackFinder.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
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
/* globals $ */
const OPENWHYD_ORIGIN = "https://openwhyd.org";
const STREAM_LIMIT = 999999;
const NB_TRACKS = 20;
// AJAX functions
window.$ =
window.$ ||
new (function FakeJquery() {
function loadJS(src, cb) {
var inc = document.createElement("script");
if (cb)
inc.onload = inc.onreadystatechange = function () {
if (
inc.readyState == "loaded" ||
inc.readyState == "complete" ||
inc.readyState == 4
)
cb();
};
inc.src = src;
document.getElementsByTagName("head")[0].appendChild(inc);
}
var _getJSON_counter = 0;
return {
getJSON: (url, cb) => {
var wFct = "_getJSON_cb_" + ++_getJSON_counter;
var wUrl = url.replace("=?", "=" + wFct);
window[wFct] = function (data) {
cb(data);
// TODO: remove script element from DOM
delete window[wFct];
};
loadJS(wUrl);
},
};
})();
// main logic of mobile/index.html
(function () {
// TrackFinder configuration
var LABELS = {
myPlaylists: "My playlists",
playlistTracks: "Tracks",
myLastPosts: "My recent tracks",
myPosts: "My tracks",
theirPosts: "Other tracks",
};
function eidToUrl(eId) {
return (eId || "")
.replace("/yt/", "https://youtube.com/watch?v=")
.replace("/sc/", "https://soundcloud.com/")
.replace("/dm/", "https://dailymotion.com/video/")
.replace("/dz/", "https://deezer.com/track/")
.replace("/vi/", "https://vimeo.com/");
}
// general utils / tools
function htmlEscape(str) {
return String(str)
.replace(/&/g, "&")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/</g, "<")
.replace(/>/g, ">");
}
// rendering
function renderResults(array, name, q) {
return ["<h1>" + (LABELS[name] || name) + "</h1>", "<ul>"]
.concat(
array.map(function (item) {
var name = htmlEscape(item.name);
if (q) name = name.replace(new RegExp(q, "gi"), "<b>$&</b>"); // highlight matching part
return (
"<li class='" +
(item.cssClass || "") +
"' " + // class='"+(item.playerLabel||"")+"'
(item.img ? " data-img='" + htmlEscape(item.img) + "'" : "") +
(item.eId ? " data-eid='" + htmlEscape(item.eId) + "'" : "") +
(item.id ? " data-pid='" + htmlEscape(item.id) + "'" : "") +
">" +
"<div class='btnAdd'>✚</div>" +
"<a href='" +
htmlEscape(item.url) +
"' target='_blank'>" +
"<div class='thumb' style='background-image:url(" +
htmlEscape(item.img) +
")'></div>" +
name +
"</a>" +
//+ ((item.pl || {}).name ? "<p>" + htmlEscape(item.pl.name) + "</p>" : "")
"</li>"
);
})
)
.concat(["</ul>"])
.join("\n");
}
const renderTrack = (t) => ({
url: eidToUrl(t.eId),
img: t.img,
name: t.name,
});
const renderPlaylist = (userId) => (playlist, i) => ({
cssClass: "playlist" + (i >= 3 ? " hidden" : ""),
url: playlist.url,
img: `${OPENWHYD_ORIGIN}/img/playlist/${userId}_${playlist.id}`,
name: playlist.name,
});
function displayTracks(tracks, sectionId) {
document.getElementById(sectionId).innerHTML = renderResults(
tracks.map(renderTrack),
sectionId
);
}
function displayPlaylists(userId, playlists, sectionId) {
const more = { cssClass: "showMore", name: "More..." };
document.getElementById(sectionId).innerHTML = renderResults(
playlists.map(renderPlaylist(userId)).concat(more),
sectionId
);
document.getElementsByClassName("showMore")[0].onclick = function (e) {
e.preventDefault();
this.parentNode.removeChild(this);
fadeIn(document.getElementsByClassName("hidden"));
return false;
};
const playlistNodes = document.getElementsByClassName("playlist");
for (let i = 0; i < playlistNodes.length; ++i)
playlistNodes[i].onclick = function (e) {
e.preventDefault();
loadPlaylist(e.target);
return false;
};
}
// data retrieval
function loadStream(url, callback) {
$.getJSON(
`${url}?format=json&limit=${STREAM_LIMIT}&callback=?`,
callback,
"json"
);
}
function loadUserPlaylists(userId, callback) {
$.getJSON(
`${OPENWHYD_ORIGIN}/u/${userId}/playlists?format=json&callback=?`,
callback
);
}
function loadPlaylist(playlist) {
var url =
OPENWHYD_ORIGIN + playlist.href.substr(playlist.href.indexOf("/u/"));
document.getElementById("playlistName").innerText = playlist.innerText;
document.getElementById("playlistTracks").innerHTML = "";
var i = 0;
loadStream(url, function (tracks) {
tracks = tracks || [];
displayTracks(tracks, "playlistTracks");
document.getElementById(
"toYouTube"
).href = `https://www.youtube.com/watch_videos?video_ids=${tracks
.filter((track) => track.eId.startsWith("/yt/"))
.map((track) => track.eId.replace("/yt/", ""))
.join(",")}`;
});
switchToPage("pgPlaylist");
}
// main logic
let myTracks = [];
function loadMainPage() {
const userId = new URLSearchParams(window.location.search).get("uId");
if (!userId) return;
loadUserPlaylists(userId, function (playlists) {
document.getElementById("pleaseLogin").style.display = "none";
displayPlaylists(userId, playlists, "myPlaylists");
loadStream(`${OPENWHYD_ORIGIN}/u/${userId}`, (tracks) => {
if (tracks) displayTracks(tracks.slice(0, NB_TRACKS), "myLastPosts");
myTracks = tracks.map((tr) => ({
...tr,
_normalized: [tr.name, tr.text].join(" ").toLowerCase(), // pre-compute and store normalized post name & description (for faster search)
}));
});
});
}
function switchToPage(id) {
var pages = document.getElementsByClassName("page");
for (let i = 0; i < pages.length; ++i) pages[i].style.display = "none";
document.getElementById(id).style.display = "block";
}
// function onAddTrack(btn) {
// var elt = btn.target.parentElement;
// var track = elt.dataset;
// var postData = {
// action: "insert",
// ctx: "mob",
// eId: track.eid,
// img: track.img,
// name: elt.getElementsByTagName("a")[0].innerText,
// "src[id]": "http://openwhyd.org/mobile",
// "src[name]": "Openwhyd Mobile Track Finder",
// };
// console.log("posting...", postData);
// var params = Object.keys(postData).map(function (key) {
// return key + "=" + encodeURIComponent(postData[key]);
// });
// $.getJSON(
// `${OPENWHYD_ORIGIN}/api/post?${params.join("&")}`,
// function (post) {
// console.log("posted:", post);
// if (!post || post.error)
// alert(
// "Sorry, we were unable to add this track\n" +
// ((post || {}).error || "")
// );
// else alert("Succesfully added this track!");
// }
// );
// }
var defaultResults = document.getElementById("pgResults").innerHTML;
const searchBox = document.getElementById("q");
function search(query) {
var results = [];
query = query.trim().toLowerCase(); // normalize search query
var terms = !query ? [] : query.split(" ");
return terms.reduce(
// exclude results which name do not contain this term
(results, term) =>
results.filter((res) => res._normalized.indexOf(term) !== -1),
myTracks
);
}
function displaySearchResults(query) {
if (!query) {
switchToPage("pgMain");
return;
}
switchToPage("pgResults");
const tracks = search(query);
if (tracks.length === 0) {
document.getElementById("pgResults").innerHTML = defaultResults;
} else {
displayTracks(tracks, "myPosts");
}
}
searchBox.onkeyup = () => displaySearchResults(searchBox.value);
document.getElementsByClassName("searchClear")[0].onclick = function () {
searchBox.value = "";
displaySearchResults();
};
document.getElementById("exitPlaylist").onclick = function () {
switchToPage("pgMain");
};
// fade-in effect for results
function fadeIn(nodeSet, liCondition) {
var fadeQueue = [];
for (let i = 0; i < nodeSet.length; ++i) {
var li = nodeSet[i];
//if (log) console.log(li);
if (li.nodeName == "LI" && (!liCondition || liCondition(li))) {
fadeQueue.push(li);
li.className = (li.className || "") + " hidden";
}
}
if (fadeQueue.length)
var interval = setInterval(function () {
var elt = fadeQueue.shift();
if (elt) elt.className = elt.className.replace("hidden", "fadeIn");
else clearInterval(interval);
}, 10);
}
document.getElementById("searchPane").addEventListener(
"DOMNodeInserted",
function (ev) {
if (ev.target.nodeName == "UL")
fadeIn(ev.target.children, function (li) {
return li.className.indexOf("hidden") == -1;
});
},
false
);
loadMainPage();
})();