Skip to content

Instantly share code, notes, and snippets.

@navdeepsingh
Created November 21, 2020 10:18
Show Gist options
  • Save navdeepsingh/1ec8b6ff285e45d149b585fc8d05f9d3 to your computer and use it in GitHub Desktop.
Save navdeepsingh/1ec8b6ff285e45d149b585fc8d05f9d3 to your computer and use it in GitHub Desktop.
Bani.js | IndexedDB | https://howlerjs.com/
/**
* Fetch Bani API
*/
const pathWrapper = document.getElementById('path'),
audio = document.getElementById('audio'),
previousLink = document.getElementById('prevBtn'),
nextLink = document.getElementById('nextBtn'),
loading = document.querySelector('.loading'),
urlSearchParams = new URLSearchParams(window.location.search),
pauriIndex = parseInt(urlSearchParams.get('i')),
previousPauriIndex = pauriIndex - 1,
nextPauriIndex = pauriIndex + 1,
DB_VERSION = 2,
BANI_ID = parseInt(urlSearchParams.get('id'));
let pageTitle = document.querySelector('title').innerHTML;
// DOM Updates
const currentBani = config.filter(bani => bani.baniID == BANI_ID),
chunkStart = currentBani[0]['pauris'][pauriIndex]['chunk']['s'],
chunkEnd = currentBani[0]['pauris'][pauriIndex]['chunk']['e'],
pauriMp3 = currentBani[0]['pauris'][pauriIndex]['mp3'],
baniTitle = currentBani[0]['baniName'],
unicodeBaniTitle = currentBani[0]['unicodeBaniName'];
document.querySelector('title').innerHTML = pageTitle.replace(/\$bani/, unicodeBaniTitle);
document.getElementById('title').innerHTML = baniTitle;
previousLink.setAttribute('href', '/bani.html?id=' + BANI_ID + '&i=' + previousPauriIndex);
nextLink.setAttribute('href', '/bani.html?id=' + BANI_ID + '&i=' + nextPauriIndex);
/**
* Fetch Bani verse as soon as page is loaded
*/
fetchBani = (from = 'indexeddb') => {
let db;
let openRequest = indexedDB.open('my-fiirst-gutka-db', this.DB_VERSION);
openRequest.onupgradeneeded = function (e) {
console.log('UpgradeNeeded Running..');
db = e.target.result;
if (!db.objectStoreNames.contains('bani')) {
db.createObjectStore('bani');
}
}
return new Promise(function (resolve, reject) {
openRequest.onsuccess = function (e) {
db = e.target.result;
// Get from DB
let transactionGet = db.transaction(['bani'], "readonly");
let storeGet = transactionGet.objectStore("bani");
let requestGet = storeGet.get(BANI_ID);
requestGet.onsuccess = function (e) {
let result = e.target.result;
if (result !== undefined && from == 'indexeddb') {
// If its in cache
console.log('Getting JSON from: IndexedDB');
resolve(generatePath(result));
} else {
//else request from network
resolve(fetchBaniAPI(db));
}
}
requestGet.onerror = function (e) {
console.log('On Error');
// reject can be here
}
}
});
}
fetchBaniAPI = async (db) => {
try {
const baniData = await fetch(`https://api.banidb.com/v2/banis/${BANI_ID}`);
const bani = await baniData.json();
const versesAllArr = bani.verses;
console.log(versesAllArr);
if (versesAllArr !== undefined) {
await createBaniDB(db, versesAllArr, BANI_ID)
await generatePath(versesAllArr)
}
} catch (e) {
if (e) {
console.log(e.message, 'Error while fetching API - sttm')
}
}
}
generatePath = (allPath) => {
let currentVerses = chunk(allPath, chunkStart, chunkEnd);
// Get Config from localStorage
const settings = JSON.parse(localStorage.getItem('config'));
let larivaarAssit = false;
let vishrams = false;
let fontClass = 'medium';
if (settings) {
if (settings['larivaar'] !== undefined && settings['larivaar']) {
larivaar();
}
if (settings['larivaar-assist'] !== undefined && settings['larivaar-assist']) {
larivaarAssit = true;
}
if (settings['vishrams'] !== undefined && settings['vishrams']) {
vishrams = true;
}
if (settings['font-size'] !== undefined && settings['font-size']) {
fontClass = settings['font-size'];
}
}
loading.style.display = 'none';
pauriAll = '';
pauriAll = parsedPath(currentVerses, larivaarAssit, vishrams);
pathWrapper.classList.add(fontClass);
pathWrapper.innerHTML = pauriAll;
var player = new Player([
{
title: pauriMp3,
file: pauriMp3,
howl: null
}
]);
// Bind our player controls.
playBtn.addEventListener('click', function () {
player.play();
});
pauseBtn.addEventListener('click', function () {
player.pause();
});
waveform.addEventListener('click', function (event) {
player.seek(event.clientX / window.innerWidth);
});
// Update the height of the wave animation.
// These are basically some hacks to get SiriWave.js to do what we want.
var resize = function () {
var height = window.innerHeight * 0.3;
var width = window.innerWidth;
wave.height = height;
wave.height_2 = height / 2;
wave.MAX = wave.height_2 - 4;
wave.width = width;
wave.width_2 = width / 2;
wave.width_4 = width / 4;
wave.canvas.height = height;
wave.canvas.width = width;
wave.container.style.margin = -(height / 2) + 'px auto';
// Update the position of the slider.
var sound = player.playlist[player.index].howl;
if (sound) {
var vol = sound.volume();
var barWidth = (vol * 0.9);
sliderBtn.style.left = (window.innerWidth * barWidth + window.innerWidth * 0.05 - 25) + 'px';
}
};
window.addEventListener('resize', resize);
resize();
}
const parsedPath = (currentVerses, larivaarAssit = false, vishrams = false) => {
currentVerses[0].map(currentVerse => {
let verse = '';
const shabadSplit = currentVerse.verse.verse.gurmukhi.split(' ');
const visraamArr = currentVerse.verse.visraam ? (currentVerse.verse.visraam.sttm ? currentVerse.verse.visraam.sttm : null) : null;
shabadSplit.map((word, index) => {
if (index === 0) {
verse += '<div class="line">';
}
if (index === shabadSplit.length - 1) {
verse += `${word}</div>`;
} else {
let spanClass = '';
if (visraamArr !== null) {
let puranVisraam = visraamArr.filter(visraam => visraam.t == 'v' && visraam.p === index);
let yamki = visraamArr.filter(visraam => visraam.t == 'y' && visraam.p === index);
// For Visraams or Pauses
if (vishrams) {
if (puranVisraam.length) {
spanClass = ' puran-visraam'
}
if (yamki.length) {
spanClass = ' yamki'
}
}
}
// For Larivaar Assist
if (larivaarAssit) {
let newIndex = index + 1;
spanClass = (newIndex % 2 === 0) ? `larivaar-assist` : ``;
}
verse += `<span class="${spanClass}">${word}</span>`;
}
})
pauriAll += verse;
});
return pauriAll;
}
const larivaar = () => {
path.classList.add('larivaar');
}
const chunk = (array, start = 0, end) => {
const chunked_arr = [];
let copied = [...array];
chunked_arr.push(copied.splice(start, end));
return chunked_arr;
}
const createBaniDB = (db, baniJson, baniId = 1) => {
//Add to DB
let transaction = db.transaction(['bani'], "readwrite");
let store = transaction.objectStore("bani");
let request = store.add(baniJson, baniId);
request.onerror = function (e) {
console.log("Error", e.target.error.name);
}
request.onsuccess = function (e) {
console.log('Added Successfully');
}
}
fetchBani();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment