language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function shiftEncode(str, shiftAmount = 2) { var newString = ""; var oldLetter; var newLetter; var newCharcode; for (var i = 0; i < str.length; i++) { oldLetter = str.charAt(i); if (oldLetter === " ") { newString += oldLetter; continue; } newCharcode = oldLetter.charCodeAt(0) + shiftAmount; if (newCharcode > 122) { var differ = newCharcode - 122; newCharcode = 96 + differ; } newLetter = String.fromCharCode(newCharcode); newString += newLetter; } return newString; }
function shiftEncode(str, shiftAmount = 2) { var newString = ""; var oldLetter; var newLetter; var newCharcode; for (var i = 0; i < str.length; i++) { oldLetter = str.charAt(i); if (oldLetter === " ") { newString += oldLetter; continue; } newCharcode = oldLetter.charCodeAt(0) + shiftAmount; if (newCharcode > 122) { var differ = newCharcode - 122; newCharcode = 96 + differ; } newLetter = String.fromCharCode(newCharcode); newString += newLetter; } return newString; }
JavaScript
function lookFor(searchstring, fullMatch, data, key, statblock) { for (var i = 0; i < data.length; i++) { if ((data[i].name.toLowerCase() == searchstring.toLowerCase() && fullMatch) || (data[i].name.toLowerCase().includes(searchstring.toLowerCase()) && !fullMatch)) { if (statblock != null) { foundMonster = data[i]; statblockPresenter.createStatblock(document.getElementById("statblock"), foundMonster, statblockType, true) frameHistoryButtons.unToggleButtonsExcept(data[i].name); hideOrShowStatblockButtons(); } if (key == "monsters") { $("#loaderButton").attr("title", "Load " + data[i].name + " into combat table. (ctrl + e)"); loadedMonster = foundMonster; loadedMonster.data_extra_attributes = {}; loadedMonster.data_extra_attributes.initiative = data[i].initiative ? data[i].initiative : getAbilityScoreModifier(data[i].dexterity); //Loada öll creatures. } else if (encounterIsLoaded) { loadEncounter(data[i]) } document.getElementById("iframewrapper").style.display = "block"; return true; } } return false; function hideOrShowStatblockButtons() { document.getElementById("loaderButton").classList.add("hidden"); document.getElementById("mobPanelLoadButton").classList.add("hidden"); if (key == "monsters" || key == "encounters" || key == "homebrew") { document.getElementById("loaderButton").classList.remove("hidden"); if (settings.enable.mobController && key != "encounters") { console.log(key) document.getElementById("mobPanelLoadButton").classList.remove("hidden"); } } } }
function lookFor(searchstring, fullMatch, data, key, statblock) { for (var i = 0; i < data.length; i++) { if ((data[i].name.toLowerCase() == searchstring.toLowerCase() && fullMatch) || (data[i].name.toLowerCase().includes(searchstring.toLowerCase()) && !fullMatch)) { if (statblock != null) { foundMonster = data[i]; statblockPresenter.createStatblock(document.getElementById("statblock"), foundMonster, statblockType, true) frameHistoryButtons.unToggleButtonsExcept(data[i].name); hideOrShowStatblockButtons(); } if (key == "monsters") { $("#loaderButton").attr("title", "Load " + data[i].name + " into combat table. (ctrl + e)"); loadedMonster = foundMonster; loadedMonster.data_extra_attributes = {}; loadedMonster.data_extra_attributes.initiative = data[i].initiative ? data[i].initiative : getAbilityScoreModifier(data[i].dexterity); //Loada öll creatures. } else if (encounterIsLoaded) { loadEncounter(data[i]) } document.getElementById("iframewrapper").style.display = "block"; return true; } } return false; function hideOrShowStatblockButtons() { document.getElementById("loaderButton").classList.add("hidden"); document.getElementById("mobPanelLoadButton").classList.add("hidden"); if (key == "monsters" || key == "encounters" || key == "homebrew") { document.getElementById("loaderButton").classList.remove("hidden"); if (settings.enable.mobController && key != "encounters") { console.log(key) document.getElementById("mobPanelLoadButton").classList.remove("hidden"); } } } }
JavaScript
function shareOnTwitter (urlParams = "", text, via, title) { var shareUrl = `${window.location.origin}${window.location.pathname}` var newText = stripTags(text) if (urlParams) { shareUrl += "?" + urlParams } if (newText.length > 111) { newText = newText.substring(0, 111) + "..." } const shareServiceUrl = "https://twitter.com/intent/tweet/" popUpWindow(`${shareServiceUrl}?url=${encodeURIComponent(shareUrl)}&text=${encodeURI(newText)}&via=${encodeURI(via)}`, `${encodeURI(title)}`, 450, 320) }
function shareOnTwitter (urlParams = "", text, via, title) { var shareUrl = `${window.location.origin}${window.location.pathname}` var newText = stripTags(text) if (urlParams) { shareUrl += "?" + urlParams } if (newText.length > 111) { newText = newText.substring(0, 111) + "..." } const shareServiceUrl = "https://twitter.com/intent/tweet/" popUpWindow(`${shareServiceUrl}?url=${encodeURIComponent(shareUrl)}&text=${encodeURI(newText)}&via=${encodeURI(via)}`, `${encodeURI(title)}`, 450, 320) }
JavaScript
function fetchNonprofit (ein) { return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/nonprofits/${ein}`) .then(response => { if (response.data.length && response.data[0].status === 'claimed') { // Nonprofit was found in main system (nonprofit is not generic) return resolve(response.data[0]) } else { // Nonprofit was not found in main system (nonprofit is generic) // Fetch generic resources from main system and nonprofit data from the IRS service let promises = [] promises.push(Vue.axios.get(`${IRSSearchAPI}/nonprofits/${ein}`)) promises.push(Vue.axios.get(`${cmsURL}/default`)) return Vue.axios.all(promises) .then(result => { var res = result[0].data[0] res.data = result[1].data.data return resolve(res) }) .catch(e => { console.log("e: ", e) return reject({ code: 404 }) }) } }) }) }
function fetchNonprofit (ein) { return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/nonprofits/${ein}`) .then(response => { if (response.data.length && response.data[0].status === 'claimed') { // Nonprofit was found in main system (nonprofit is not generic) return resolve(response.data[0]) } else { // Nonprofit was not found in main system (nonprofit is generic) // Fetch generic resources from main system and nonprofit data from the IRS service let promises = [] promises.push(Vue.axios.get(`${IRSSearchAPI}/nonprofits/${ein}`)) promises.push(Vue.axios.get(`${cmsURL}/default`)) return Vue.axios.all(promises) .then(result => { var res = result[0].data[0] res.data = result[1].data.data return resolve(res) }) .catch(e => { console.log("e: ", e) return reject({ code: 404 }) }) } }) }) }
JavaScript
function fetchFundraiser (id) { return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/fundraisers/${id}`) .then(response => { if (response.data.length) { return resolve(response.data[0]) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
function fetchFundraiser (id) { return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/fundraisers/${id}`) .then(response => { if (response.data.length) { return resolve(response.data[0]) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
JavaScript
function fetchFundraisers (ein, page, limit, paginated = true) { if (!paginated) { page = 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/fundraisers/nonprofit/${ein}?&_limit=${limit}&_page=${page++}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
function fetchFundraisers (ein, page, limit, paginated = true) { if (!paginated) { page = 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/fundraisers/nonprofit/${ein}?&_limit=${limit}&_page=${page++}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
JavaScript
function fetchAllFundraisers (filter, page, limit, paginated = true) { if (!paginated) { page = 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/fundraisers/all?&_limit=${limit}&_page=${page++}&_filter=${filter}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
function fetchAllFundraisers (filter, page, limit, paginated = true) { if (!paginated) { page = 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/fundraisers/all?&_limit=${limit}&_page=${page++}&_filter=${filter}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
JavaScript
function fetchAllClaimsAdmin (filter, token, page, limit, paginated = true) { if (!paginated) { page = 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/admin/claims/all?&_limit=${limit}&_page=${page++}&_filter=${filter}`, { headers: { "Authorization": `Bearer ${token}` } }) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
function fetchAllClaimsAdmin (filter, token, page, limit, paginated = true) { if (!paginated) { page = 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/admin/claims/all?&_limit=${limit}&_page=${page++}&_filter=${filter}`, { headers: { "Authorization": `Bearer ${token}` } }) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
JavaScript
function fetchAllFundraisersAdmin (filter, token, page, limit, paginated = true) { if (!paginated) { page = 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/admin/fundraisers/all?&_limit=${limit}&_page=${page++}&_filter=${filter}`, { headers: { "Authorization": `Bearer ${token}` } }) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
function fetchAllFundraisersAdmin (filter, token, page, limit, paginated = true) { if (!paginated) { page = 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/admin/fundraisers/all?&_limit=${limit}&_page=${page++}&_filter=${filter}`, { headers: { "Authorization": `Bearer ${token}` } }) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
JavaScript
function fetchAllUsersAdmin (filter, token, page, limit, paginated = true) { if (!paginated) { page = 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/admin/users/all?&_limit=${limit}&_page=${page++}&_filter=${filter}`, { headers: { "Authorization": `Bearer ${token}` } }) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
function fetchAllUsersAdmin (filter, token, page, limit, paginated = true) { if (!paginated) { page = 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/admin/users/all?&_limit=${limit}&_page=${page++}&_filter=${filter}`, { headers: { "Authorization": `Bearer ${token}` } }) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
JavaScript
function fetchExploreFundraisers (page, limit, paginated = true) { if (!paginated) { page = 1 } // TODO: create algorithm to display varied fundraisers. return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/fundraisers?&_limit=${limit}&_page=${page++}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
function fetchExploreFundraisers (page, limit, paginated = true) { if (!paginated) { page = 1 } // TODO: create algorithm to display varied fundraisers. return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/fundraisers?&_limit=${limit}&_page=${page++}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
JavaScript
function fetchCommonData (id) { return new Promise((resolve, reject) => { return Vue.axios.get(`${cmsURL}/common`) .then(response => { return resolve(response.data) }) .catch(e => { return reject(e) }) }) }
function fetchCommonData (id) { return new Promise((resolve, reject) => { return Vue.axios.get(`${cmsURL}/common`) .then(response => { return resolve(response.data) }) .catch(e => { return reject(e) }) }) }
JavaScript
function fetchUpdates (fundraiserId, page, limit, paginated = true) { if (!page) { page = 1 } if (paginated) { page += 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/updates/fundraiser/${fundraiserId}?posts_per_page=${limit}&page=${page}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
function fetchUpdates (fundraiserId, page, limit, paginated = true) { if (!page) { page = 1 } if (paginated) { page += 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/updates/fundraiser/${fundraiserId}?posts_per_page=${limit}&page=${page}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
JavaScript
function fetchComments (fundraiserId, page, limit, paginated = true) { if (!page) { page = 1 } if (paginated) { page += 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/comments/fundraiser/${fundraiserId}?posts_per_page=${limit}&page=${page}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return reject({ code: 404 }) //reject or resolve?? } }) .catch(e => { return reject(e) }) }) }
function fetchComments (fundraiserId, page, limit, paginated = true) { if (!page) { page = 1 } if (paginated) { page += 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/comments/fundraiser/${fundraiserId}?posts_per_page=${limit}&page=${page}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return reject({ code: 404 }) //reject or resolve?? } }) .catch(e => { return reject(e) }) }) }
JavaScript
function fetchDonations (query, page, limit, paginated = true, sortBy = "amountInCents") { if (!page) { page = 1 } if (paginated) { page += 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/donations/${query}?posts_per_page=${limit}&page=${page}&sort_by=${sortBy}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
function fetchDonations (query, page, limit, paginated = true, sortBy = "amountInCents") { if (!page) { page = 1 } if (paginated) { page += 1 } return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/donations/${query}?posts_per_page=${limit}&page=${page}&sort_by=${sortBy}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
JavaScript
function fetchTopFundraisers (ein, page = 1, limit, paginated = true) { return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/donations/top-fundraisers/nonprofit/${ein}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
function fetchTopFundraisers (ein, page = 1, limit, paginated = true) { return new Promise((resolve, reject) => { return Vue.axios.get(`${baseURL}/donations/top-fundraisers/nonprofit/${ein}`) .then(response => { if (response.data.length) { return resolve(response.data) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
JavaScript
function fetchHomePage () { return new Promise((resolve, reject) => { return Vue.axios.get(`${cmsURL}/pages?page_name=home`) .then(response => { if (response.data) { return resolve(response.data[0]) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
function fetchHomePage () { return new Promise((resolve, reject) => { return Vue.axios.get(`${cmsURL}/pages?page_name=home`) .then(response => { if (response.data) { return resolve(response.data[0]) } else { return resolve({ code: 404 }) } }) .catch(e => { return reject(e) }) }) }
JavaScript
function sendComment (commentBody, inReplyTo, fundraiserId, userId, honeypot, token) { return new Promise((resolve, reject) => { return Vue.axios.post( `${baseURL}/comments/fundraiser/${fundraiserId}`, { comment: commentBody, parentId: inReplyTo, userId: userId, fundraiserId: fundraiserId, fax: honeypot }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve(data.data) }) .catch(e => { return reject(e) }) }) }
function sendComment (commentBody, inReplyTo, fundraiserId, userId, honeypot, token) { return new Promise((resolve, reject) => { return Vue.axios.post( `${baseURL}/comments/fundraiser/${fundraiserId}`, { comment: commentBody, parentId: inReplyTo, userId: userId, fundraiserId: fundraiserId, fax: honeypot }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve(data.data) }) .catch(e => { return reject(e) }) }) }
JavaScript
function reportComment (commentId, userId, report, token) { return new Promise((resolve, reject) => { return Vue.axios.post( `${baseURL}/comments/report/${commentId}`, { report: report }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve(data.data) }) .catch(e => { return reject(e) }) }) }
function reportComment (commentId, userId, report, token) { return new Promise((resolve, reject) => { return Vue.axios.post( `${baseURL}/comments/report/${commentId}`, { report: report }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve(data.data) }) .catch(e => { return reject(e) }) }) }
JavaScript
function reportContent (entity, contentId, report, token) { return new Promise((resolve, reject) => { return Vue.axios.post( `${baseURL}/${entity}s/report/${contentId}`, { report: report }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve(data.data) }) .catch(e => { return reject(e) }) }) }
function reportContent (entity, contentId, report, token) { return new Promise((resolve, reject) => { return Vue.axios.post( `${baseURL}/${entity}s/report/${contentId}`, { report: report }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve(data.data) }) .catch(e => { return reject(e) }) }) }
JavaScript
function updateUserField (id, field, value, token) { return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/users/${id}/field`, { field: field, value: value }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(res => { return resolve(res) }) .catch(err => { return reject(err) }) }) }
function updateUserField (id, field, value, token) { return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/users/${id}/field`, { field: field, value: value }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(res => { return resolve(res) }) .catch(err => { return reject(err) }) }) }
JavaScript
function saveInlineField (location, value, route, token) { return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/${route.name}s/${route.name === "nonprofit" ? route.params.ein : route.params.id}/update`, { location: location, value: value }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve({ location: location, value: value }) }) .catch(e => { return reject(e) }) }) }
function saveInlineField (location, value, route, token) { return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/${route.name}s/${route.name === "nonprofit" ? route.params.ein : route.params.id}/update`, { location: location, value: value }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve({ location: location, value: value }) }) .catch(e => { return reject(e) }) }) }
JavaScript
function saveFundraiserStatus (location, value, route, token) { return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/admin/${route.name}s/${route.params.id}/update`, { location: location, value: value }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve({ location: location, value: value }) }) .catch(e => { return reject(e) }) }) }
function saveFundraiserStatus (location, value, route, token) { return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/admin/${route.name}s/${route.params.id}/update`, { location: location, value: value }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve({ location: location, value: value }) }) .catch(e => { return reject(e) }) }) }
JavaScript
function saveUserAccountType (location, value, route, token) { return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/admin/${route.name}s/${route.params.id}/update`, { value: value }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve({ location: location, value: value }) }) .catch(e => { return reject(e) }) }) }
function saveUserAccountType (location, value, route, token) { return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/admin/${route.name}s/${route.params.id}/update`, { value: value }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve({ location: location, value: value }) }) .catch(e => { return reject(e) }) }) }
JavaScript
function requestAvatarPreSignedURL ({ blob, sub, token }) { return new Promise((resolve, reject) => { return Vue.axios.get( `${baseURL}/users/get-avatar-presigned-url`, { headers: { "Authorization": `Bearer ${token}` } } ).then(data => { return resolve(data.data) }) .catch(err => { return reject(err) }) }) }
function requestAvatarPreSignedURL ({ blob, sub, token }) { return new Promise((resolve, reject) => { return Vue.axios.get( `${baseURL}/users/get-avatar-presigned-url`, { headers: { "Authorization": `Bearer ${token}` } } ).then(data => { return resolve(data.data) }) .catch(err => { return reject(err) }) }) }
JavaScript
function requestGenericPreSignedUrl ({ blob, token, id, location, filename }) { var entity = location.split('.')[0] return new Promise((resolve, reject) => { return Vue.axios.get( `${baseURL}/${entity}s/${id}/get-image-presigned-url?location=${location}&filename=${filename}`, { headers: { "Authorization": `Bearer ${token}` } } ).then(data => { return resolve(data.data) }) .catch(err => { return reject(err) }) }) }
function requestGenericPreSignedUrl ({ blob, token, id, location, filename }) { var entity = location.split('.')[0] return new Promise((resolve, reject) => { return Vue.axios.get( `${baseURL}/${entity}s/${id}/get-image-presigned-url?location=${location}&filename=${filename}`, { headers: { "Authorization": `Bearer ${token}` } } ).then(data => { return resolve(data.data) }) .catch(err => { return reject(err) }) }) }
JavaScript
function postImageToS3 (preSignedURL, blob) { var buf = new Buffer(blob.replace(/^data:image\/\w+;base64,/, ""), "base64") return new Promise((resolve, reject) => { return Vue.axios.put( preSignedURL, buf, { headers: { "Content-Type": "image/jpeg" } } ).then(data => { var postedURL = data.request.responseURL.split("?")[0] return resolve(postedURL) }).catch(err => { return reject(err) }) }) }
function postImageToS3 (preSignedURL, blob) { var buf = new Buffer(blob.replace(/^data:image\/\w+;base64,/, ""), "base64") return new Promise((resolve, reject) => { return Vue.axios.put( preSignedURL, buf, { headers: { "Content-Type": "image/jpeg" } } ).then(data => { var postedURL = data.request.responseURL.split("?")[0] return resolve(postedURL) }).catch(err => { return reject(err) }) }) }
JavaScript
function saveUserImageToBackend (sub, postedURL, token) { return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/users/${sub}/avatar`, { field: "avatar", value: postedURL }, { headers: { "Authorization": `Bearer ${token}` } } ).then(() => { return resolve(postedURL) }).catch(err => { return reject(err) }) }) }
function saveUserImageToBackend (sub, postedURL, token) { return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/users/${sub}/avatar`, { field: "avatar", value: postedURL }, { headers: { "Authorization": `Bearer ${token}` } } ).then(() => { return resolve(postedURL) }).catch(err => { return reject(err) }) }) }
JavaScript
function saveGenericImageToBackend ({ id, postedURL, token, location }) { var entity = location.split('.')[0] var target = location.split('.')[location.split('.').length - 1] return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/${entity}s/${id}/image`, { location: location, value: postedURL }, { headers: { "Authorization": `Bearer ${token}` } } ).then(() => { return resolve(postedURL) }).catch(err => { return reject(err) }) }) }
function saveGenericImageToBackend ({ id, postedURL, token, location }) { var entity = location.split('.')[0] var target = location.split('.')[location.split('.').length - 1] return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/${entity}s/${id}/image`, { location: location, value: postedURL }, { headers: { "Authorization": `Bearer ${token}` } } ).then(() => { return resolve(postedURL) }).catch(err => { return reject(err) }) }) }
JavaScript
function addNewUpdate (fundraiserId, update, userId, token) { return new Promise((resolve, reject) => { return Vue.axios.post( `${baseURL}/updates/fundraiser/${fundraiserId}`, { content: update, userId: userId }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve({ update: update }) }) .catch(e => { return reject(e) }) }) }
function addNewUpdate (fundraiserId, update, userId, token) { return new Promise((resolve, reject) => { return Vue.axios.post( `${baseURL}/updates/fundraiser/${fundraiserId}`, { content: update, userId: userId }, { headers: { "Authorization": `Bearer ${token}` } } ) .then(data => { return resolve({ update: update }) }) .catch(e => { return reject(e) }) }) }
JavaScript
function removeFixedImage (location, route, token, filename) { var entity = location.split('.')[0] var target = location.split('.')[location.split('.').length - 1] var identifier = route.name === "nonprofit" ? route.params.ein : route.params.id return new Promise((resolve, reject) => { return Vue.axios.delete( `${baseURL}/${entity}s/${identifier}/image/${target}/${filename.substring(filename.lastIndexOf('/')+1)}`, { data: { fullURL: filename }, headers: { "Authorization": `Bearer ${token}` } } ).then(filename => { return resolve(filename) }) .catch(err => { return reject(err) }) }) }
function removeFixedImage (location, route, token, filename) { var entity = location.split('.')[0] var target = location.split('.')[location.split('.').length - 1] var identifier = route.name === "nonprofit" ? route.params.ein : route.params.id return new Promise((resolve, reject) => { return Vue.axios.delete( `${baseURL}/${entity}s/${identifier}/image/${target}/${filename.substring(filename.lastIndexOf('/')+1)}`, { data: { fullURL: filename }, headers: { "Authorization": `Bearer ${token}` } } ).then(filename => { return resolve(filename) }) .catch(err => { return reject(err) }) }) }
JavaScript
function removeVideo (location, route, youTubeID, token) { var entity = location.split('.')[0] var target = location.split('.')[location.split('.').length - 1] var identifier = route.name === "nonprofit" ? route.params.ein : route.params.id return new Promise((resolve, reject) => { return Vue.axios.delete( `${baseURL}/${entity}s/${identifier}/video/${youTubeID}`, { headers: { "Authorization": `Bearer ${token}` } } ).then(data => { return resolve(data) }).catch(err => { return reject(err) }) }) }
function removeVideo (location, route, youTubeID, token) { var entity = location.split('.')[0] var target = location.split('.')[location.split('.').length - 1] var identifier = route.name === "nonprofit" ? route.params.ein : route.params.id return new Promise((resolve, reject) => { return Vue.axios.delete( `${baseURL}/${entity}s/${identifier}/video/${youTubeID}`, { headers: { "Authorization": `Bearer ${token}` } } ).then(data => { return resolve(data) }).catch(err => { return reject(err) }) }) }
JavaScript
function addVideo (location, route, youTubeID, token) { var entity = location.split('.')[0] var target = location.split('.')[location.split('.').length - 1] var identifier = route.name === "nonprofit" ? route.params.ein : route.params.id return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/${entity}s/${identifier}/video`, { location: location, value: youTubeID }, { headers: { "Authorization": `Bearer ${token}` } } ).then(data => { return resolve(data) }).catch(err => { return reject(err) }) }) }
function addVideo (location, route, youTubeID, token) { var entity = location.split('.')[0] var target = location.split('.')[location.split('.').length - 1] var identifier = route.name === "nonprofit" ? route.params.ein : route.params.id return new Promise((resolve, reject) => { return Vue.axios.put( `${baseURL}/${entity}s/${identifier}/video`, { location: location, value: youTubeID }, { headers: { "Authorization": `Bearer ${token}` } } ).then(data => { return resolve(data) }).catch(err => { return reject(err) }) }) }
JavaScript
function submitClaimForm (ein, form, token) { return new Promise((resolve, reject) => { return Vue.axios.post( `${baseURL}/nonprofits/${ein}/claim`, { form: form }, { headers: { "Authorization": `Bearer ${token}`} } ).then(data => { return resolve(data) }).catch(err => { return reject(err) }) }) }
function submitClaimForm (ein, form, token) { return new Promise((resolve, reject) => { return Vue.axios.post( `${baseURL}/nonprofits/${ein}/claim`, { form: form }, { headers: { "Authorization": `Bearer ${token}`} } ).then(data => { return resolve(data) }).catch(err => { return reject(err) }) }) }
JavaScript
function upgradeCounters() { for (var key in counters) { if (!counters.hasOwnProperty(key)) continue; for(var key2 in dummy) { if (!dummy.hasOwnProperty(key2)) continue; if(!counters[key][key2]) { counters[key][key2] = dummy[key2]; } } } }
function upgradeCounters() { for (var key in counters) { if (!counters.hasOwnProperty(key)) continue; for(var key2 in dummy) { if (!dummy.hasOwnProperty(key2)) continue; if(!counters[key][key2]) { counters[key][key2] = dummy[key2]; } } } }
JavaScript
function importClassesFromDirectories(directories, formats) { if (formats === void 0) { formats = [".js", ".ts"]; } function loadFileClasses(exported, allLoaded) { if (typeof exported === "function" || exported instanceof index_1.EntitySchema) { allLoaded.push(exported); } else if (Array.isArray(exported)) { exported.forEach(function (i) { return loadFileClasses(i, allLoaded); }); } else if (typeof exported === "object" && exported !== null) { Object.keys(exported).forEach(function (key) { return loadFileClasses(exported[key], allLoaded); }); } return allLoaded; } var allFiles = directories.reduce(function (allDirs, dir) { return allDirs.concat(PlatformTools_1.PlatformTools.load("glob").sync(PlatformTools_1.PlatformTools.pathNormalize(dir))); }, []); var dirs = allFiles .filter(function (file) { var dtsExtension = file.substring(file.length - 5, file.length); return formats.indexOf(PlatformTools_1.PlatformTools.pathExtname(file)) !== -1 && dtsExtension !== ".d.ts"; }) .map(function (file) { return PlatformTools_1.PlatformTools.load(PlatformTools_1.PlatformTools.pathResolve(file)); }); return loadFileClasses(dirs, []); }
function importClassesFromDirectories(directories, formats) { if (formats === void 0) { formats = [".js", ".ts"]; } function loadFileClasses(exported, allLoaded) { if (typeof exported === "function" || exported instanceof index_1.EntitySchema) { allLoaded.push(exported); } else if (Array.isArray(exported)) { exported.forEach(function (i) { return loadFileClasses(i, allLoaded); }); } else if (typeof exported === "object" && exported !== null) { Object.keys(exported).forEach(function (key) { return loadFileClasses(exported[key], allLoaded); }); } return allLoaded; } var allFiles = directories.reduce(function (allDirs, dir) { return allDirs.concat(PlatformTools_1.PlatformTools.load("glob").sync(PlatformTools_1.PlatformTools.pathNormalize(dir))); }, []); var dirs = allFiles .filter(function (file) { var dtsExtension = file.substring(file.length - 5, file.length); return formats.indexOf(PlatformTools_1.PlatformTools.pathExtname(file)) !== -1 && dtsExtension !== ".d.ts"; }) .map(function (file) { return PlatformTools_1.PlatformTools.load(PlatformTools_1.PlatformTools.pathResolve(file)); }); return loadFileClasses(dirs, []); }
JavaScript
function Generated(strategy) { if (strategy === void 0) { strategy = "increment"; } return function (object, propertyName) { __1.getMetadataArgsStorage().generations.push({ target: object.constructor, propertyName: propertyName, strategy: strategy }); }; }
function Generated(strategy) { if (strategy === void 0) { strategy = "increment"; } return function (object, propertyName) { __1.getMetadataArgsStorage().generations.push({ target: object.constructor, propertyName: propertyName, strategy: strategy }); }; }
JavaScript
function OneToMany(typeFunction, inverseSide, options) { return function (object, propertyName) { if (!options) options = {}; // now try to determine it its lazy relation var isLazy = options && options.lazy === true ? true : false; if (!isLazy && Reflect && Reflect.getMetadata) { // automatic determination var reflectedType = Reflect.getMetadata("design:type", object, propertyName); if (reflectedType && typeof reflectedType.name === "string" && reflectedType.name.toLowerCase() === "promise") isLazy = true; } __1.getMetadataArgsStorage().relations.push({ target: object.constructor, propertyName: propertyName, // propertyType: reflectedType, isLazy: isLazy, relationType: "one-to-many", type: typeFunction, inverseSideProperty: inverseSide, options: options }); }; }
function OneToMany(typeFunction, inverseSide, options) { return function (object, propertyName) { if (!options) options = {}; // now try to determine it its lazy relation var isLazy = options && options.lazy === true ? true : false; if (!isLazy && Reflect && Reflect.getMetadata) { // automatic determination var reflectedType = Reflect.getMetadata("design:type", object, propertyName); if (reflectedType && typeof reflectedType.name === "string" && reflectedType.name.toLowerCase() === "promise") isLazy = true; } __1.getMetadataArgsStorage().relations.push({ target: object.constructor, propertyName: propertyName, // propertyType: reflectedType, isLazy: isLazy, relationType: "one-to-many", type: typeFunction, inverseSideProperty: inverseSide, options: options }); }; }
JavaScript
function OneToOne(typeFunction, inverseSideOrOptions, options) { // normalize parameters var inverseSideProperty; if (typeof inverseSideOrOptions === "object") { options = inverseSideOrOptions; } else { inverseSideProperty = inverseSideOrOptions; } return function (object, propertyName) { if (!options) options = {}; // now try to determine it its lazy relation var isLazy = options && options.lazy === true ? true : false; if (!isLazy && Reflect && Reflect.getMetadata) { // automatic determination var reflectedType = Reflect.getMetadata("design:type", object, propertyName); if (reflectedType && typeof reflectedType.name === "string" && reflectedType.name.toLowerCase() === "promise") isLazy = true; } __1.getMetadataArgsStorage().relations.push({ target: object.constructor, propertyName: propertyName, // propertyType: reflectedType, isLazy: isLazy, relationType: "one-to-one", type: typeFunction, inverseSideProperty: inverseSideProperty, options: options }); }; }
function OneToOne(typeFunction, inverseSideOrOptions, options) { // normalize parameters var inverseSideProperty; if (typeof inverseSideOrOptions === "object") { options = inverseSideOrOptions; } else { inverseSideProperty = inverseSideOrOptions; } return function (object, propertyName) { if (!options) options = {}; // now try to determine it its lazy relation var isLazy = options && options.lazy === true ? true : false; if (!isLazy && Reflect && Reflect.getMetadata) { // automatic determination var reflectedType = Reflect.getMetadata("design:type", object, propertyName); if (reflectedType && typeof reflectedType.name === "string" && reflectedType.name.toLowerCase() === "promise") isLazy = true; } __1.getMetadataArgsStorage().relations.push({ target: object.constructor, propertyName: propertyName, // propertyType: reflectedType, isLazy: isLazy, relationType: "one-to-one", type: typeFunction, inverseSideProperty: inverseSideProperty, options: options }); }; }
JavaScript
function handleMatch(match, loopNdx, quantifierRecurse) { var currentPos = testPos; if (testPos == pos && match.matches == undefined) { matches.push({ "match": match, "locator": loopNdx.reverse() }); return true; } else if (match.matches != undefined) { if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier match = handleMatch(maskToken.matches[tndx + 1], loopNdx); if (match) return true; } else if (match.isOptional) { var optionalToken = match; match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse); if (match) { var latestMatch = matches[matches.length - 1]["match"]; var isFirstMatch = (optionalToken.matches.indexOf(latestMatch) == 0); if (isFirstMatch) { insertStop = true; //insert a stop for non greedy } //search for next possible match testPos = currentPos; } } else if (match.isAlternator) { //TODO } else if (match.isQuantifier && quantifierRecurse !== true) { var qt = match; for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) { var tokenGroup = maskToken.matches[maskToken.matches.indexOf(qt) - 1]; match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true); if (match) { //get latest match var latestMatch = matches[matches.length - 1]["match"]; if (qndx > qt.quantifier.min - 1) { //mark optionality latestMatch.optionalQuantifier = true; } var isFirstMatch = (tokenGroup.matches.indexOf(latestMatch) == 0); if (isFirstMatch) { //search for next possible match if (qndx > qt.quantifier.min - 1) { insertStop = true; testPos = pos; //match the position after the group break; //stop quantifierloop } else return true; } else { return true; } } } } else { match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse); if (match) return true; } } else testPos++; }
function handleMatch(match, loopNdx, quantifierRecurse) { var currentPos = testPos; if (testPos == pos && match.matches == undefined) { matches.push({ "match": match, "locator": loopNdx.reverse() }); return true; } else if (match.matches != undefined) { if (match.isGroup && quantifierRecurse !== true) { //when a group pass along to the quantifier match = handleMatch(maskToken.matches[tndx + 1], loopNdx); if (match) return true; } else if (match.isOptional) { var optionalToken = match; match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse); if (match) { var latestMatch = matches[matches.length - 1]["match"]; var isFirstMatch = (optionalToken.matches.indexOf(latestMatch) == 0); if (isFirstMatch) { insertStop = true; //insert a stop for non greedy } //search for next possible match testPos = currentPos; } } else if (match.isAlternator) { //TODO } else if (match.isQuantifier && quantifierRecurse !== true) { var qt = match; for (var qndx = (ndxInitializer.length > 0 && quantifierRecurse !== true) ? ndxInitializer.shift() : 0; (qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) { var tokenGroup = maskToken.matches[maskToken.matches.indexOf(qt) - 1]; match = handleMatch(tokenGroup, [qndx].concat(loopNdx), true); if (match) { //get latest match var latestMatch = matches[matches.length - 1]["match"]; if (qndx > qt.quantifier.min - 1) { //mark optionality latestMatch.optionalQuantifier = true; } var isFirstMatch = (tokenGroup.matches.indexOf(latestMatch) == 0); if (isFirstMatch) { //search for next possible match if (qndx > qt.quantifier.min - 1) { insertStop = true; testPos = pos; //match the position after the group break; //stop quantifierloop } else return true; } else { return true; } } } } else { match = ResolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse); if (match) return true; } } else testPos++; }
JavaScript
function _isValid(position, c, strict, fromSetValid) { var rslt = false; $.each(getTests(position, !strict), function (ndx, tst) { var test = tst["match"]; var loopend = c ? 1 : 0, chrs = '', buffer = getBuffer(); for (var i = test.cardinality; i > loopend; i--) { chrs += getBufferElement(position - (i - 1)); } if (c) { chrs += c; } //return is false or a json object => { pos: ??, c: ??} or true rslt = test.fn != null ? test.fn.test(chrs, buffer, position, strict, opts) : (c == test["def"] || c == opts.skipOptionalPartCharacter) && test["def"] != "" ? //non mask { c: test["def"], pos: position } : false; if (rslt !== false) { var elem = rslt.c != undefined ? rslt.c : c; elem = elem == opts.skipOptionalPartCharacter ? test["def"] : elem; var validatedPos = position; if (rslt["refreshFromBuffer"]) { var refresh = rslt["refreshFromBuffer"]; strict = true; validatedPos = rslt.pos != undefined ? rslt.pos : position; tst = getTests(validatedPos, !strict)[0]; //possible mismatch TODO if (refresh === true) { getMaskSet()["validPositions"] = {}; refreshFromBuffer(0, getBuffer().length); } else { refreshFromBuffer(refresh["start"], refresh["end"]); } } else if (rslt !== true && rslt["pos"] != position) { //their is a position offset validatedPos = rslt["pos"]; refreshFromBuffer(position, validatedPos); tst = getTests(validatedPos, !strict)[0]; //possible mismatch TODO } if (ndx > 0) { resetMaskSet(true); } if (!setValidPosition(validatedPos, $.extend({}, tst, { "input": casing(elem, test) }), strict, fromSetValid)) rslt = false; return false; //break from $.each } }); return rslt; }
function _isValid(position, c, strict, fromSetValid) { var rslt = false; $.each(getTests(position, !strict), function (ndx, tst) { var test = tst["match"]; var loopend = c ? 1 : 0, chrs = '', buffer = getBuffer(); for (var i = test.cardinality; i > loopend; i--) { chrs += getBufferElement(position - (i - 1)); } if (c) { chrs += c; } //return is false or a json object => { pos: ??, c: ??} or true rslt = test.fn != null ? test.fn.test(chrs, buffer, position, strict, opts) : (c == test["def"] || c == opts.skipOptionalPartCharacter) && test["def"] != "" ? //non mask { c: test["def"], pos: position } : false; if (rslt !== false) { var elem = rslt.c != undefined ? rslt.c : c; elem = elem == opts.skipOptionalPartCharacter ? test["def"] : elem; var validatedPos = position; if (rslt["refreshFromBuffer"]) { var refresh = rslt["refreshFromBuffer"]; strict = true; validatedPos = rslt.pos != undefined ? rslt.pos : position; tst = getTests(validatedPos, !strict)[0]; //possible mismatch TODO if (refresh === true) { getMaskSet()["validPositions"] = {}; refreshFromBuffer(0, getBuffer().length); } else { refreshFromBuffer(refresh["start"], refresh["end"]); } } else if (rslt !== true && rslt["pos"] != position) { //their is a position offset validatedPos = rslt["pos"]; refreshFromBuffer(position, validatedPos); tst = getTests(validatedPos, !strict)[0]; //possible mismatch TODO } if (ndx > 0) { resetMaskSet(true); } if (!setValidPosition(validatedPos, $.extend({}, tst, { "input": casing(elem, test) }), strict, fromSetValid)) rslt = false; return false; //break from $.each } }); return rslt; }
JavaScript
function loadFileFromWebServer(relFilePath, successCallback, errorCallback) { //assign default callback functions if none was provided. successCallback=getSuccessCallback(successCallback); errorCallback=getErrorCallback(errorCallback); var httpReq = new XMLHttpRequest(); console.log("location.origin: "+location.origin); var pathFix=''; if(Object.is(location.origin, 'https://asterics.github.io')||Object.is(location.origin, 'http://asterics.github.io')) { pathFix='/AsTeRICS'; console.log("Adding pathFix: "+pathFix); } relFilePath=location.origin+pathFix+'/'+relFilePath; console.log('Fetching file from webserver: '+relFilePath); /* //With jQuery you could use something like this to fetch the file easily, nevertheless to be independent we use the hard approach. $.get(relFilePath).then(function(response) { successCallback(response); });*/ httpReq.onreadystatechange = function() { if (httpReq.readyState === XMLHttpRequest.DONE && (httpReq.status === 404 || httpReq.status === 0)) { alert('Could not find requested file: '+relFilePath); } else if (httpReq.readyState === XMLHttpRequest.DONE && httpReq.status === 200) { //success, so call success-callback console.log('File from Webserver successfully loaded: '+relFilePath); successCallback(httpReq.responseText); } } httpReq.open('GET', relFilePath, true); httpReq.send(); }
function loadFileFromWebServer(relFilePath, successCallback, errorCallback) { //assign default callback functions if none was provided. successCallback=getSuccessCallback(successCallback); errorCallback=getErrorCallback(errorCallback); var httpReq = new XMLHttpRequest(); console.log("location.origin: "+location.origin); var pathFix=''; if(Object.is(location.origin, 'https://asterics.github.io')||Object.is(location.origin, 'http://asterics.github.io')) { pathFix='/AsTeRICS'; console.log("Adding pathFix: "+pathFix); } relFilePath=location.origin+pathFix+'/'+relFilePath; console.log('Fetching file from webserver: '+relFilePath); /* //With jQuery you could use something like this to fetch the file easily, nevertheless to be independent we use the hard approach. $.get(relFilePath).then(function(response) { successCallback(response); });*/ httpReq.onreadystatechange = function() { if (httpReq.readyState === XMLHttpRequest.DONE && (httpReq.status === 404 || httpReq.status === 0)) { alert('Could not find requested file: '+relFilePath); } else if (httpReq.readyState === XMLHttpRequest.DONE && httpReq.status === 200) { //success, so call success-callback console.log('File from Webserver successfully loaded: '+relFilePath); successCallback(httpReq.responseText); } } httpReq.open('GET', relFilePath, true); httpReq.send(); }
JavaScript
function deployModelFromWebserver(relFilePath, successCallback, errorCallback) { //assign default callback functions if none was provided. successCallback=getSuccessCallback(successCallback); errorCallback=getErrorCallback(errorCallback); loadFileFromWebServer(relFilePath, function(modelInXML) { uploadModel(successCallback, errorCallback, modelInXML); }); }
function deployModelFromWebserver(relFilePath, successCallback, errorCallback) { //assign default callback functions if none was provided. successCallback=getSuccessCallback(successCallback); errorCallback=getErrorCallback(errorCallback); loadFileFromWebServer(relFilePath, function(modelInXML) { uploadModel(successCallback, errorCallback, modelInXML); }); }
JavaScript
function deployModelFromWebserverApplySettingsAndStartModel(relFilePath, propertyMap, successCallback, errorCallback) { //assign default callback functions if none was provided. successCallback=getSuccessCallback(successCallback); errorCallback=getErrorCallback(errorCallback); deployModelFromWebserver(relFilePath, function() { setRuntimeComponentProperties( function (data, HTTPstatus){ if(JSON.parse(data).length == 0) { var errorMsg="The property settings could not be applied."; alert(errorMsg); } console.log('The following properties could be set: '+data); startModel(successCallback,errorCallback); }, errorCallback, propertyMap); }); }
function deployModelFromWebserverApplySettingsAndStartModel(relFilePath, propertyMap, successCallback, errorCallback) { //assign default callback functions if none was provided. successCallback=getSuccessCallback(successCallback); errorCallback=getErrorCallback(errorCallback); deployModelFromWebserver(relFilePath, function() { setRuntimeComponentProperties( function (data, HTTPstatus){ if(JSON.parse(data).length == 0) { var errorMsg="The property settings could not be applied."; alert(errorMsg); } console.log('The following properties could be set: '+data); startModel(successCallback,errorCallback); }, errorCallback, propertyMap); }); }
JavaScript
function storeFileFromWebserverOnARE(relFilePath, relFilePathARE, successCallback, errorCallback) { //assign default callback functions if none was provided. successCallback=getSuccessCallback(successCallback); errorCallback=getErrorCallback(errorCallback); loadFileFromWebServer(relFilePath, function(fileContentsAsString) { storeData(successCallback, errorCallback, relFilePathARE, fileContentsAsString); }); }
function storeFileFromWebserverOnARE(relFilePath, relFilePathARE, successCallback, errorCallback) { //assign default callback functions if none was provided. successCallback=getSuccessCallback(successCallback); errorCallback=getErrorCallback(errorCallback); loadFileFromWebServer(relFilePath, function(fileContentsAsString) { storeData(successCallback, errorCallback, relFilePathARE, fileContentsAsString); }); }
JavaScript
function applySettingsInXMLModelAndStart(modelFilePathOnWebserver, successCallback, errorCallback) { //assign default callback functions if none was provided. successCallback=getSuccessCallback(successCallback); errorCallback=getErrorCallback(errorCallback); loadFileFromWebServer(modelFilePathOnWebserver, function(modelInXML){ modelInXML=updateModelPropertiesFromWidgets(modelInXML); //Finally upload and start modified model. uploadModel(function(data, HTTPstatus) { startModel(function(data,HTTPStatus) { successCallback(data, HTTPStatus); },errorCallback); }, errorCallback, modelInXML); }); }
function applySettingsInXMLModelAndStart(modelFilePathOnWebserver, successCallback, errorCallback) { //assign default callback functions if none was provided. successCallback=getSuccessCallback(successCallback); errorCallback=getErrorCallback(errorCallback); loadFileFromWebServer(modelFilePathOnWebserver, function(modelInXML){ modelInXML=updateModelPropertiesFromWidgets(modelInXML); //Finally upload and start modified model. uploadModel(function(data, HTTPstatus) { startModel(function(data,HTTPStatus) { successCallback(data, HTTPStatus); },errorCallback); }, errorCallback, modelInXML); }); }
JavaScript
function updateWidgetsFromDeployedModel(successCallback, errorCallback) { //assign default callback functions if none was provided. successCallback=getSuccessCallback(successCallback); errorCallback=getErrorCallback(errorCallback); downloadDeployedModel(function(data, HTTPStatus) { //TODO: Check if the modelName is identical to the modelName of the template model, otherwise we should not //update the widgets from a wrong model. updateWidgetsFromModelProperties(data); },successCallback); }
function updateWidgetsFromDeployedModel(successCallback, errorCallback) { //assign default callback functions if none was provided. successCallback=getSuccessCallback(successCallback); errorCallback=getErrorCallback(errorCallback); downloadDeployedModel(function(data, HTTPStatus) { //TODO: Check if the modelName is identical to the modelName of the template model, otherwise we should not //update the widgets from a wrong model. updateWidgetsFromModelProperties(data); },successCallback); }
JavaScript
function saveSettingsAsAutostartModel(modelFilePathOnWebserver, successCallback, errorCallback) { //assign default callback functions if none was provided. if(typeof successCallback !== 'function') { successCallback=function(data,HTTPStatus) { alert('Successfully saved settings as autostart!'); } } errorCallback=getErrorCallback(errorCallback); loadFileFromWebServer(modelFilePathOnWebserver, function(modelInXML){ modelInXML=updateModelPropertiesFromWidgets(modelInXML); storeModel(successCallback,errorCallback,'autostart.acs',modelInXML); }); }
function saveSettingsAsAutostartModel(modelFilePathOnWebserver, successCallback, errorCallback) { //assign default callback functions if none was provided. if(typeof successCallback !== 'function') { successCallback=function(data,HTTPStatus) { alert('Successfully saved settings as autostart!'); } } errorCallback=getErrorCallback(errorCallback); loadFileFromWebServer(modelFilePathOnWebserver, function(modelInXML){ modelInXML=updateModelPropertiesFromWidgets(modelInXML); storeModel(successCallback,errorCallback,'autostart.acs',modelInXML); }); }
JavaScript
function updateModelPropertiesFromWidgets(modelInXML) { widgetIdToPropertyKeyMap=generateWidgetIdToPropertyKeyMap(); console.log("Updating "+widgetIdToPropertyKeyMap.length+" widgets from model properties."); //parse template modelInXML to document object var xmlDoc = $.parseXML( modelInXML ); //Update property values with values of input widgets. for(var i=0;i<widgetIdToPropertyKeyMap.length;i++) { var widgetVal=$(widgetIdToPropertyKeyMap[i]["widgetId"]).val(); if (typeof widgetVal != 'undefined') { console.log("Updating modelProperty <"+widgetIdToPropertyKeyMap[i]["componentKey"]+"."+widgetIdToPropertyKeyMap[i]["propertyKey"]+"="+widgetVal+">"); setPropertyValueInXMLModel(widgetIdToPropertyKeyMap[i]["componentKey"],widgetIdToPropertyKeyMap[i]["propertyKey"],widgetVal,xmlDoc); } else { console.log("widgetId <"+widgetIdToPropertyKeyMap[i]["widgetId"]+"=undefined>"); } } //Convert back XML document to XML string. modelInXML=xmlToString(xmlDoc); return modelInXML; }
function updateModelPropertiesFromWidgets(modelInXML) { widgetIdToPropertyKeyMap=generateWidgetIdToPropertyKeyMap(); console.log("Updating "+widgetIdToPropertyKeyMap.length+" widgets from model properties."); //parse template modelInXML to document object var xmlDoc = $.parseXML( modelInXML ); //Update property values with values of input widgets. for(var i=0;i<widgetIdToPropertyKeyMap.length;i++) { var widgetVal=$(widgetIdToPropertyKeyMap[i]["widgetId"]).val(); if (typeof widgetVal != 'undefined') { console.log("Updating modelProperty <"+widgetIdToPropertyKeyMap[i]["componentKey"]+"."+widgetIdToPropertyKeyMap[i]["propertyKey"]+"="+widgetVal+">"); setPropertyValueInXMLModel(widgetIdToPropertyKeyMap[i]["componentKey"],widgetIdToPropertyKeyMap[i]["propertyKey"],widgetVal,xmlDoc); } else { console.log("widgetId <"+widgetIdToPropertyKeyMap[i]["widgetId"]+"=undefined>"); } } //Convert back XML document to XML string. modelInXML=xmlToString(xmlDoc); return modelInXML; }
JavaScript
function updateWidgetsFromModelProperties(modelInXML) { widgetIdToPropertyKeyMap=generateWidgetIdToPropertyKeyMap(); console.log("Updating "+widgetIdToPropertyKeyMap.length+" widgets from model properties."); //parse template modelInXML to document object var xmlDoc = $.parseXML( modelInXML ); //Update property values with values of input widgets. for(var i=0;i<widgetIdToPropertyKeyMap.length;i++) { var propVal=getPropertyValueFromXMLModel(widgetIdToPropertyKeyMap[i]["componentKey"],widgetIdToPropertyKeyMap[i]["propertyKey"],xmlDoc); if(typeof propVal != 'undefined') { console.log("Updating widget <"+widgetIdToPropertyKeyMap[i]["widgetId"]+"="+propVal+">"); $(widgetIdToPropertyKeyMap[i]["widgetId"]).val(propVal); } } }
function updateWidgetsFromModelProperties(modelInXML) { widgetIdToPropertyKeyMap=generateWidgetIdToPropertyKeyMap(); console.log("Updating "+widgetIdToPropertyKeyMap.length+" widgets from model properties."); //parse template modelInXML to document object var xmlDoc = $.parseXML( modelInXML ); //Update property values with values of input widgets. for(var i=0;i<widgetIdToPropertyKeyMap.length;i++) { var propVal=getPropertyValueFromXMLModel(widgetIdToPropertyKeyMap[i]["componentKey"],widgetIdToPropertyKeyMap[i]["propertyKey"],xmlDoc); if(typeof propVal != 'undefined') { console.log("Updating widget <"+widgetIdToPropertyKeyMap[i]["widgetId"]+"="+propVal+">"); $(widgetIdToPropertyKeyMap[i]["widgetId"]).val(propVal); } } }
JavaScript
function generateWidgetIdToPropertyKeyMap() { var widgetIdToPropertyKeyMap=[]; var widgetList=$("["+dataAttrAstericsModelBinding+"]"); for(var i=0;i<widgetList.length;i++) { var bindings=$(widgetList[i]).data(); for(binding in bindings) { var bindingObj= { widgetId:"#"+$(widgetList[i]).attr('id'), componentKey:bindings[binding]["componentKey"], propertyKey:bindings[binding]["propertyKey"] } widgetIdToPropertyKeyMap.push(bindingObj); } } return widgetIdToPropertyKeyMap; }
function generateWidgetIdToPropertyKeyMap() { var widgetIdToPropertyKeyMap=[]; var widgetList=$("["+dataAttrAstericsModelBinding+"]"); for(var i=0;i<widgetList.length;i++) { var bindings=$(widgetList[i]).data(); for(binding in bindings) { var bindingObj= { widgetId:"#"+$(widgetList[i]).attr('id'), componentKey:bindings[binding]["componentKey"], propertyKey:bindings[binding]["propertyKey"] } widgetIdToPropertyKeyMap.push(bindingObj); } } return widgetIdToPropertyKeyMap; }
JavaScript
function xmlToString(xmlData) { var xmlString; //IE if (window.ActiveXObject){ xmlString = xmlData.xml; } // code for Mozilla, Firefox, Opera, etc. else{ xmlString = (new XMLSerializer()).serializeToString(xmlData); } return xmlString; }
function xmlToString(xmlData) { var xmlString; //IE if (window.ActiveXObject){ xmlString = xmlData.xml; } // code for Mozilla, Firefox, Opera, etc. else{ xmlString = (new XMLSerializer()).serializeToString(xmlData); } return xmlString; }
JavaScript
generate_toote_content(data) { var cardcontent = GEN("div"); //---toote body parts if (data.spoiler_text != "") { var c_spoiler = GEN("p"); c_spoiler.textContent = data.spoiler_text; cardcontent.appendChild(c_spoiler); } var c_tootetext = GEN("p"); c_tootetext.className = "toote_main"; c_tootetext.textContent = data.content; cardcontent.appendChild(c_tootetext); if (data.spoiler_text != "") { var c_btnspoiler = GEN("span"); c_btnspoiler.className = "button_spoiler"; c_btnspoiler.textContent = "..."; cardcontent.appendChild(c_btnspoiler); } return cardcontent; }
generate_toote_content(data) { var cardcontent = GEN("div"); //---toote body parts if (data.spoiler_text != "") { var c_spoiler = GEN("p"); c_spoiler.textContent = data.spoiler_text; cardcontent.appendChild(c_spoiler); } var c_tootetext = GEN("p"); c_tootetext.className = "toote_main"; c_tootetext.textContent = data.content; cardcontent.appendChild(c_tootetext); if (data.spoiler_text != "") { var c_btnspoiler = GEN("span"); c_btnspoiler.className = "button_spoiler"; c_btnspoiler.textContent = "..."; cardcontent.appendChild(c_btnspoiler); } return cardcontent; }
JavaScript
generate_toote_media(media_attachments) { var c_imagearea = GEN("div"); c_imagearea.className = "card-image"; var c_imagecarousel = GEN("div"); c_imagecarousel.className = "carousel carousel-slider center"; for (var i = 0; i < media_attachments.length; i++) { var c_imageitem = GEN("div"); c_imageitem = "carousel-item grey lighten-4 white-text"; c_imageitem.href = "#p" + i + "!"; var c_mediaimg = GEN("img"); c_mediaimg.src = media_attachments[i].preview_url; c_mediaimg.alt = media_attachments[i].description; if (media_attachments.meta.small.width >= media_attachments.meta.small.height) { c_mediaimg.className = "landscape"; }else{ c_mediaimg.className = "portrait"; } c_imageitem.appendChild(c_mediaimg); c_imagecarousel.appendChild(c_imageitem); } c_imagearea.appendChild(c_imagecarousel); return c_imagearea; }
generate_toote_media(media_attachments) { var c_imagearea = GEN("div"); c_imagearea.className = "card-image"; var c_imagecarousel = GEN("div"); c_imagecarousel.className = "carousel carousel-slider center"; for (var i = 0; i < media_attachments.length; i++) { var c_imageitem = GEN("div"); c_imageitem = "carousel-item grey lighten-4 white-text"; c_imageitem.href = "#p" + i + "!"; var c_mediaimg = GEN("img"); c_mediaimg.src = media_attachments[i].preview_url; c_mediaimg.alt = media_attachments[i].description; if (media_attachments.meta.small.width >= media_attachments.meta.small.height) { c_mediaimg.className = "landscape"; }else{ c_mediaimg.className = "portrait"; } c_imageitem.appendChild(c_mediaimg); c_imagecarousel.appendChild(c_imageitem); } c_imagearea.appendChild(c_imagecarousel); return c_imagearea; }
JavaScript
generate_replytoote(data) { var root = GEN("li"); root.className = "collection-item avatar"; var c_userimg = GEN("img"); c_userimg.src= data.account.avatar; c_userimg.width = "32"; c_userimg.height = "32"; var c_usernameBody = GEN("span"); c_usernameBody.className = "title"; c_usernameBody.title = `@${data.account.username}@${data.instance}`; c_usernameBody.textContent = data.account.display_name; }
generate_replytoote(data) { var root = GEN("li"); root.className = "collection-item avatar"; var c_userimg = GEN("img"); c_userimg.src= data.account.avatar; c_userimg.width = "32"; c_userimg.height = "32"; var c_usernameBody = GEN("span"); c_usernameBody.className = "title"; c_usernameBody.title = `@${data.account.username}@${data.instance}`; c_usernameBody.textContent = data.account.display_name; }
JavaScript
remove_notification(notifications,id) { var hit = -1; var ac = this.currentAccount; if (typeof id == "number") { //---AccountNotification.account.notifications index (Number) hit = id; }else{ //---Notification's id (String) for (var i = 0; i < notifications.length; i++) { if (notifications[i].id == id) { hit = i; break; } } } //NOT AccountNotification.notifications !!! //IS AccountNotification.account.notifications !!! if (hit > -1) notifications.splice(hit,1); MYAPP.commonvue.nav_sel_account.checkAccountsNotification(); }
remove_notification(notifications,id) { var hit = -1; var ac = this.currentAccount; if (typeof id == "number") { //---AccountNotification.account.notifications index (Number) hit = id; }else{ //---Notification's id (String) for (var i = 0; i < notifications.length; i++) { if (notifications[i].id == id) { hit = i; break; } } } //NOT AccountNotification.notifications !!! //IS AccountNotification.account.notifications !!! if (hit > -1) notifications.splice(hit,1); MYAPP.commonvue.nav_sel_account.checkAccountsNotification(); }
JavaScript
push_notification(account,datas,options) { for (var i = 0; i < datas.length; i++) { //console.log(i,datas[i]); var data = datas[i]; //data.account = [data.account]; var ismerge = this.merge_notification(account,data); //console.log("merge=",ismerge,account,data); if (!ismerge) { if ("since_id" in options.api) { account.notifications.unshift(data); }else{ account.notifications.push(data); } } } //this.save_notification(); }
push_notification(account,datas,options) { for (var i = 0; i < datas.length; i++) { //console.log(i,datas[i]); var data = datas[i]; //data.account = [data.account]; var ismerge = this.merge_notification(account,data); //console.log("merge=",ismerge,account,data); if (!ismerge) { if ("since_id" in options.api) { account.notifications.unshift(data); }else{ account.notifications.push(data); } } } //this.save_notification(); }
JavaScript
merge_notification(account,data) { var ret = false; var cons_statusable = ["reblog","favourite","mention"]; //---reblog, favourite, mention if (cons_statusable.indexOf(data.type) > -1) { for (var i = 0; i < account.notifications.length; i++) { var notif = account.notifications[i]; if (notif["status"]) { //---insert account to same status notification if ((notif.status.id == data.status.id) && (notif.type == data.type) ) { var ishitacc = notif.account.filter(e=>{ if (data.account[0].id == e.id) { return true; } return false; }); if (ishitacc.length == 0) { notif.account.push(data.account[0]); ret = true; break; } } } } }else{ //---follow ret = false; } return ret; }
merge_notification(account,data) { var ret = false; var cons_statusable = ["reblog","favourite","mention"]; //---reblog, favourite, mention if (cons_statusable.indexOf(data.type) > -1) { for (var i = 0; i < account.notifications.length; i++) { var notif = account.notifications[i]; if (notif["status"]) { //---insert account to same status notification if ((notif.status.id == data.status.id) && (notif.type == data.type) ) { var ishitacc = notif.account.filter(e=>{ if (data.account[0].id == e.id) { return true; } return false; }); if (ishitacc.length == 0) { notif.account.push(data.account[0]); ret = true; break; } } } } }else{ //---follow ret = false; } return ret; }
JavaScript
function genIcon(type, cb, shouldDeprecate) { var _this = this; if (shouldDeprecate === void 0) { shouldDeprecate = true; } var icon = this[type + "Icon"]; var eventName = "click:" + Object(_util_helpers__WEBPACK_IMPORTED_MODULE_7__["kebabCase"])(type); cb = cb || this[type + "IconCb"]; if (shouldDeprecate && type && cb) { Object(_util_console__WEBPACK_IMPORTED_MODULE_8__["deprecate"])(":" + type + "-icon-cb", "@" + eventName, this); } var data = { props: { color: this.validationState, dark: this.dark, disabled: this.disabled, light: this.light }, on: !(this.$listeners[eventName] || cb) ? undefined : { click: function click(e) { e.preventDefault(); e.stopPropagation(); _this.$emit(eventName, e); cb && cb(e); }, // Container has mouseup event that will // trigger menu open if enclosed mouseup: function mouseup(e) { e.preventDefault(); e.stopPropagation(); } } }; return this.$createElement('div', { staticClass: "v-input__icon v-input__icon--" + Object(_util_helpers__WEBPACK_IMPORTED_MODULE_7__["kebabCase"])(type), key: "" + type + icon }, [this.$createElement(_VIcon__WEBPACK_IMPORTED_MODULE_1__["default"], data, icon)]); }
function genIcon(type, cb, shouldDeprecate) { var _this = this; if (shouldDeprecate === void 0) { shouldDeprecate = true; } var icon = this[type + "Icon"]; var eventName = "click:" + Object(_util_helpers__WEBPACK_IMPORTED_MODULE_7__["kebabCase"])(type); cb = cb || this[type + "IconCb"]; if (shouldDeprecate && type && cb) { Object(_util_console__WEBPACK_IMPORTED_MODULE_8__["deprecate"])(":" + type + "-icon-cb", "@" + eventName, this); } var data = { props: { color: this.validationState, dark: this.dark, disabled: this.disabled, light: this.light }, on: !(this.$listeners[eventName] || cb) ? undefined : { click: function click(e) { e.preventDefault(); e.stopPropagation(); _this.$emit(eventName, e); cb && cb(e); }, // Container has mouseup event that will // trigger menu open if enclosed mouseup: function mouseup(e) { e.preventDefault(); e.stopPropagation(); } } }; return this.$createElement('div', { staticClass: "v-input__icon v-input__icon--" + Object(_util_helpers__WEBPACK_IMPORTED_MODULE_7__["kebabCase"])(type), key: "" + type + icon }, [this.$createElement(_VIcon__WEBPACK_IMPORTED_MODULE_1__["default"], data, icon)]); }
JavaScript
function breakpoint(opts) { if (opts === void 0) { opts = {}; } if (!opts) { opts = {}; } return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({ data: function data() { return __assign({ clientHeight: getClientHeight(), clientWidth: getClientWidth(), resizeTimeout: undefined }, BREAKPOINTS_DEFAULTS, opts); }, computed: { breakpoint: function breakpoint() { var xs = this.clientWidth < this.thresholds.xs; var sm = this.clientWidth < this.thresholds.sm && !xs; var md = this.clientWidth < this.thresholds.md - this.scrollbarWidth && !(sm || xs); var lg = this.clientWidth < this.thresholds.lg - this.scrollbarWidth && !(md || sm || xs); var xl = this.clientWidth >= this.thresholds.lg - this.scrollbarWidth; var xsOnly = xs; var smOnly = sm; var smAndDown = (xs || sm) && !(md || lg || xl); var smAndUp = !xs && (sm || md || lg || xl); var mdOnly = md; var mdAndDown = (xs || sm || md) && !(lg || xl); var mdAndUp = !(xs || sm) && (md || lg || xl); var lgOnly = lg; var lgAndDown = (xs || sm || md || lg) && !xl; var lgAndUp = !(xs || sm || md) && (lg || xl); var xlOnly = xl; var name; switch (true) { case xs: name = 'xs'; break; case sm: name = 'sm'; break; case md: name = 'md'; break; case lg: name = 'lg'; break; default: name = 'xl'; break; } return { // Definite breakpoint. xs: xs, sm: sm, md: md, lg: lg, xl: xl, // Useful e.g. to construct CSS class names dynamically. name: name, // Breakpoint ranges. xsOnly: xsOnly, smOnly: smOnly, smAndDown: smAndDown, smAndUp: smAndUp, mdOnly: mdOnly, mdAndDown: mdAndDown, mdAndUp: mdAndUp, lgOnly: lgOnly, lgAndDown: lgAndDown, lgAndUp: lgAndUp, xlOnly: xlOnly, // For custom breakpoint logic. width: this.clientWidth, height: this.clientHeight, thresholds: this.thresholds, scrollbarWidth: this.scrollbarWidth }; } }, created: function created() { if (typeof window === 'undefined') return; window.addEventListener('resize', this.onResize, { passive: true }); }, beforeDestroy: function beforeDestroy() { if (typeof window === 'undefined') return; window.removeEventListener('resize', this.onResize); }, methods: { onResize: function onResize() { clearTimeout(this.resizeTimeout); // Added debounce to match what // v-resize used to do but was // removed due to a memory leak // https://github.com/vuetifyjs/vuetify/pull/2997 this.resizeTimeout = window.setTimeout(this.setDimensions, 200); }, setDimensions: function setDimensions() { this.clientHeight = getClientHeight(); this.clientWidth = getClientWidth(); } } }); }
function breakpoint(opts) { if (opts === void 0) { opts = {}; } if (!opts) { opts = {}; } return vue__WEBPACK_IMPORTED_MODULE_0___default.a.extend({ data: function data() { return __assign({ clientHeight: getClientHeight(), clientWidth: getClientWidth(), resizeTimeout: undefined }, BREAKPOINTS_DEFAULTS, opts); }, computed: { breakpoint: function breakpoint() { var xs = this.clientWidth < this.thresholds.xs; var sm = this.clientWidth < this.thresholds.sm && !xs; var md = this.clientWidth < this.thresholds.md - this.scrollbarWidth && !(sm || xs); var lg = this.clientWidth < this.thresholds.lg - this.scrollbarWidth && !(md || sm || xs); var xl = this.clientWidth >= this.thresholds.lg - this.scrollbarWidth; var xsOnly = xs; var smOnly = sm; var smAndDown = (xs || sm) && !(md || lg || xl); var smAndUp = !xs && (sm || md || lg || xl); var mdOnly = md; var mdAndDown = (xs || sm || md) && !(lg || xl); var mdAndUp = !(xs || sm) && (md || lg || xl); var lgOnly = lg; var lgAndDown = (xs || sm || md || lg) && !xl; var lgAndUp = !(xs || sm || md) && (lg || xl); var xlOnly = xl; var name; switch (true) { case xs: name = 'xs'; break; case sm: name = 'sm'; break; case md: name = 'md'; break; case lg: name = 'lg'; break; default: name = 'xl'; break; } return { // Definite breakpoint. xs: xs, sm: sm, md: md, lg: lg, xl: xl, // Useful e.g. to construct CSS class names dynamically. name: name, // Breakpoint ranges. xsOnly: xsOnly, smOnly: smOnly, smAndDown: smAndDown, smAndUp: smAndUp, mdOnly: mdOnly, mdAndDown: mdAndDown, mdAndUp: mdAndUp, lgOnly: lgOnly, lgAndDown: lgAndDown, lgAndUp: lgAndUp, xlOnly: xlOnly, // For custom breakpoint logic. width: this.clientWidth, height: this.clientHeight, thresholds: this.thresholds, scrollbarWidth: this.scrollbarWidth }; } }, created: function created() { if (typeof window === 'undefined') return; window.addEventListener('resize', this.onResize, { passive: true }); }, beforeDestroy: function beforeDestroy() { if (typeof window === 'undefined') return; window.removeEventListener('resize', this.onResize); }, methods: { onResize: function onResize() { clearTimeout(this.resizeTimeout); // Added debounce to match what // v-resize used to do but was // removed due to a memory leak // https://github.com/vuetifyjs/vuetify/pull/2997 this.resizeTimeout = window.setTimeout(this.setDimensions, 200); }, setDimensions: function setDimensions() { this.clientHeight = getClientHeight(); this.clientWidth = getClientWidth(); } } }); }
JavaScript
function runDelay(type, cb) { var _this = this; this.clearDelay(); var delay = parseInt(this[type + "Delay"], 10); this[type + "Timeout"] = setTimeout(cb || function () { _this.isActive = { open: true, close: false }[type]; }, delay); }
function runDelay(type, cb) { var _this = this; this.clearDelay(); var delay = parseInt(this[type + "Delay"], 10); this[type + "Timeout"] = setTimeout(cb || function () { _this.isActive = { open: true, close: false }[type]; }, delay); }
JavaScript
function removeOverlay(showScroll) { var _this = this; if (showScroll === void 0) { showScroll = true; } if (!this.overlay) { return showScroll && this.showScroll(); } this.overlay.classList.remove('v-overlay--active'); this.overlayTimeout = setTimeout(function () { // IE11 Fix try { if (_this.overlay && _this.overlay.parentNode) { _this.overlay.parentNode.removeChild(_this.overlay); } _this.overlay = null; showScroll && _this.showScroll(); } catch (e) { console.log(e); } clearTimeout(_this.overlayTimeout); _this.overlayTimeout = null; }, this.overlayTransitionDuration); }
function removeOverlay(showScroll) { var _this = this; if (showScroll === void 0) { showScroll = true; } if (!this.overlay) { return showScroll && this.showScroll(); } this.overlay.classList.remove('v-overlay--active'); this.overlayTimeout = setTimeout(function () { // IE11 Fix try { if (_this.overlay && _this.overlay.parentNode) { _this.overlay.parentNode.removeChild(_this.overlay); } _this.overlay = null; showScroll && _this.showScroll(); } catch (e) { console.log(e); } clearTimeout(_this.overlayTimeout); _this.overlayTimeout = null; }, this.overlayTransitionDuration); }
JavaScript
function appAlert(message,callback){ if (curLocale.environment.platform == "windowsapp") { var msg = new Windows.UI.Popups.MessageDialog(message); msg.commands.append(new Windows.UI.Popups.UICommand(_T("cons_close"), null, 1)); msg.defaultCommandIndex = 1; try { msg.showAsync(); } catch (e) { console.log(e); } }else{ alertify.alert(MYAPP.appinfo.name,message,callback); } }
function appAlert(message,callback){ if (curLocale.environment.platform == "windowsapp") { var msg = new Windows.UI.Popups.MessageDialog(message); msg.commands.append(new Windows.UI.Popups.UICommand(_T("cons_close"), null, 1)); msg.defaultCommandIndex = 1; try { msg.showAsync(); } catch (e) { console.log(e); } }else{ alertify.alert(MYAPP.appinfo.name,message,callback); } }
JavaScript
merge_notification(data) { var ret = false; var cons_statusable = ["reblog","favourite","mention"]; //---reblog, favourite, mention if (cons_statusable.indexOf(data.type) > -1) { for (var i = 0; i < this.currentAccount.notifications.length; i++) { var notif = this.currentAccount.notifications[i]; if (notif["status"]) { //---insert account to same status notification if ((notif.status.id == data.status.id) && (notif.type == data.type) ) { var ishitacc = notif.account.filter(e=>{ if (data.account[0].id == e.id) { return true; } return false; }); if (ishitacc.length == 0) { notif.account.push(data.account[0]); ret = true; break; } } } } }else{ //---follow ret = false; } return ret; }
merge_notification(data) { var ret = false; var cons_statusable = ["reblog","favourite","mention"]; //---reblog, favourite, mention if (cons_statusable.indexOf(data.type) > -1) { for (var i = 0; i < this.currentAccount.notifications.length; i++) { var notif = this.currentAccount.notifications[i]; if (notif["status"]) { //---insert account to same status notification if ((notif.status.id == data.status.id) && (notif.type == data.type) ) { var ishitacc = notif.account.filter(e=>{ if (data.account[0].id == e.id) { return true; } return false; }); if (ishitacc.length == 0) { notif.account.push(data.account[0]); ret = true; break; } } } } }else{ //---follow ret = false; } return ret; }
JavaScript
uploadMedia(account,data,options) { var def = new Promise((resolve, reject)=>{ if (!account) { reject(false); return; } var fnlopt = { api : {}, app : {} }; if ("comment" in options) { fnlopt.api["description"] = options["comment"]; } if ("focus" in options) { fnlopt.api["focus"] = options["focus"]; } fnlopt.api["file"] = data; //console.log("fnlopt=",fnlopt); //---test /*resolve({ "filename" : data.name, "account" : account, "data" : {"id":"dummy","url":"hogehoge"} });*/ //---test var bkupac = MYAPP.sns._accounts; MYAPP.sns.setAccount(account); MYAPP.sns.postMedia(fnlopt) .then(result=>{ resolve({ "filename" : options.filename, "account" : account, "data" : result }); },error=>{ console.log(error); }) .catch(error=>{ alertify.error("Failed: Update media file."); reject(error); }) .finally( ()=>{ MYAPP.sns.setAccount(bkupac); }); }); return def; }
uploadMedia(account,data,options) { var def = new Promise((resolve, reject)=>{ if (!account) { reject(false); return; } var fnlopt = { api : {}, app : {} }; if ("comment" in options) { fnlopt.api["description"] = options["comment"]; } if ("focus" in options) { fnlopt.api["focus"] = options["focus"]; } fnlopt.api["file"] = data; //console.log("fnlopt=",fnlopt); //---test /*resolve({ "filename" : data.name, "account" : account, "data" : {"id":"dummy","url":"hogehoge"} });*/ //---test var bkupac = MYAPP.sns._accounts; MYAPP.sns.setAccount(account); MYAPP.sns.postMedia(fnlopt) .then(result=>{ resolve({ "filename" : options.filename, "account" : account, "data" : result }); },error=>{ console.log(error); }) .catch(error=>{ alertify.error("Failed: Update media file."); reject(error); }) .finally( ()=>{ MYAPP.sns.setAccount(bkupac); }); }); return def; }
JavaScript
addInstance(instance_name) { /* At this function, created Account object is not meaning. effective register point is afterAddInstance */ var acc = new Account(); var arr = instance_name.toLowerCase().split("@"); if (arr.length == 1) { //---only instance name acc.instance = arr[0]; }else{ //---if it includes username (ex: [email protected] ) //---split @, indicate last index element. acc.instance = arr[arr.length-1]; } //acc.instance = instance_name; acc.api = new MastodonAPI({ instance: acc.getBaseURL() }); var tmpaccount = { "instance": acc.instance, "siteinfo": {} }; var callbackurl = window.location.origin + MYAPP.appinfo.firstPath + MYAPP.siteinfo.redirect_uri; var def = new Promise((resolve, reject) => { MYAPP.sns.getInstanceInfo(acc.instance) .then(result=>{ console.log("instance info=",result); }); acc.api.registerApplication( MYAPP.appinfo.name, callbackurl, MYAPP.siteinfo.scopes, MYAPP.siteinfo.appurl, function (data) { tmpaccount.siteinfo["key"] = data.client_id; tmpaccount.siteinfo["secret"] = data.client_secret; tmpaccount.siteinfo["redirect_uri"] = data.redirect_uri; localStorage.setItem("tmpaccount", JSON.stringify(tmpaccount)); var url = acc.api.generateAuthLink( tmpaccount.siteinfo.key, tmpaccount.siteinfo.redirect_uri, "code", MYAPP.siteinfo.scopes ); window.location.href = url; //resolve(url); /* Next step is redirected step in window.onload */ } ); }); return def; }
addInstance(instance_name) { /* At this function, created Account object is not meaning. effective register point is afterAddInstance */ var acc = new Account(); var arr = instance_name.toLowerCase().split("@"); if (arr.length == 1) { //---only instance name acc.instance = arr[0]; }else{ //---if it includes username (ex: [email protected] ) //---split @, indicate last index element. acc.instance = arr[arr.length-1]; } //acc.instance = instance_name; acc.api = new MastodonAPI({ instance: acc.getBaseURL() }); var tmpaccount = { "instance": acc.instance, "siteinfo": {} }; var callbackurl = window.location.origin + MYAPP.appinfo.firstPath + MYAPP.siteinfo.redirect_uri; var def = new Promise((resolve, reject) => { MYAPP.sns.getInstanceInfo(acc.instance) .then(result=>{ console.log("instance info=",result); }); acc.api.registerApplication( MYAPP.appinfo.name, callbackurl, MYAPP.siteinfo.scopes, MYAPP.siteinfo.appurl, function (data) { tmpaccount.siteinfo["key"] = data.client_id; tmpaccount.siteinfo["secret"] = data.client_secret; tmpaccount.siteinfo["redirect_uri"] = data.redirect_uri; localStorage.setItem("tmpaccount", JSON.stringify(tmpaccount)); var url = acc.api.generateAuthLink( tmpaccount.siteinfo.key, tmpaccount.siteinfo.redirect_uri, "code", MYAPP.siteinfo.scopes ); window.location.href = url; //resolve(url); /* Next step is redirected step in window.onload */ } ); }); return def; }
JavaScript
save() { if (curLocale.environment.platform == "windowsapp") { var folder = Windows.Storage.ApplicationData.current.localFolder; folder.getFileAsync(this.setting.NAME) .then(function (file) { Windows.Storage.FileIO.writeTextAsync(file, JSON.stringify(this.items[i])); }, function (data) { folder.createFileAsync(this.setting.NAME) .then(function (file) { Windows.Storage.FileIO.writeTextAsync(file, JSON.stringify(this.items[i])); }); }); } else { var tmparr = []; for (var i = 0; i < this.items.length; i++) { tmparr.push(this.items[i].getRaw()); } AppStorage.set(this.setting.NAME, tmparr); var tmpinst = {}; for (var obj in this.instances) { tmpinst[obj] = Object.assign(this.instances[obj]); delete tmpinst[obj].emoji; } AppStorage.set(this.setting.INSTANCEEMOJI,tmpinst); } }
save() { if (curLocale.environment.platform == "windowsapp") { var folder = Windows.Storage.ApplicationData.current.localFolder; folder.getFileAsync(this.setting.NAME) .then(function (file) { Windows.Storage.FileIO.writeTextAsync(file, JSON.stringify(this.items[i])); }, function (data) { folder.createFileAsync(this.setting.NAME) .then(function (file) { Windows.Storage.FileIO.writeTextAsync(file, JSON.stringify(this.items[i])); }); }); } else { var tmparr = []; for (var i = 0; i < this.items.length; i++) { tmparr.push(this.items[i].getRaw()); } AppStorage.set(this.setting.NAME, tmparr); var tmpinst = {}; for (var obj in this.instances) { tmpinst[obj] = Object.assign(this.instances[obj]); delete tmpinst[obj].emoji; } AppStorage.set(this.setting.INSTANCEEMOJI,tmpinst); } }
JavaScript
load() { var def = new Promise((resolve, reject) => { this.items.splice(0, this.items.length); if (curLocale.environment.platform == "windowsapp") { var folder = Windows.Storage.ApplicationData.current.localFolder; folder.getFileAsync(this.setting.NAME) .then((file) => { var reader = new FileReader(); reader.onload = (e) => { var text = reader.result; this.items = JSON.parse(text); resolve(this.items); }; reader.onerror = (e) => { appAlert("not valid file!!"); reject("error"); }; reader.readAsText(file); }, function (data) { console.log("AccountManager.load: not found ini file."); }); } else { var fdata = AppStorage.get(this.setting.NAME, null); if (fdata && (fdata.length > 0)) { if (!docCookies.getItem(MYAPP.siteinfo.cke)) { docCookies.setItem(MYAPP.siteinfo.cke,"1"); } var promises = []; var emojitest = AppStorage.get(this.setting.INSTANCEEMOJI, null); if (emojitest) { var values = (emojitest); this.instances = values; for (var i = 0; i < fdata.length; i++) { var ac = new Account(); ac.load(fdata[i]); //console.log("ac.api=",ac.api,values[ac.instance]); ac.api.setConfig("stream_url",values[ac.instance].info.urls.streaming_api); if ((location.pathname != "/toot/new") && (location.pathname != "/") && (location.pathname != "/arch")) { ac.stream.start(); ac.direct.start(); } this.items.push(ac); this.backupItems.push(ac); //console.log(ac.instance); } /*for (var iv = 0; iv < values.length; iv++) { this.instances[values[iv].instance] = { emoji : values[iv] }; }*/ resolve(this.items); }else{ for (var i = 0; i < fdata.length; i++) { var ac = new Account(); ac.load(fdata[i]); this.items.push(ac); this.backupItems.push(ac); //console.log(ac.instance); //var pro = MYAPP.sns.getInstanceEmoji(ac.instance); //promises.push(pro); promises.push( MYAPP.sns.getInstanceInfo(ac.instance) .then(result=> { //---no neccesary https// (add automatically) result.uri = result.uri.replace("https://",""); this.instances[result.uri] = { info : result, instance : result.uri }; for (var ainx = 0; ainx < this.items.length; ainx++) { if (this.items[ainx].instance == result.uri) { this.items[ainx].token["stream_url"] = result.urls.streaming_api; this.items[ainx].api.setConfig("stream_url",result.urls.streaming_api); } } return {data:this.instances[result.uri], instance : result.uri }; }) .then(result2=> { return MYAPP.sns.getInstanceEmoji(result2.instance) .then(emojiresult => { return result2.data["emoji"] = emojiresult; }); }) ); } //resolve(this.items); Promise.all(promises) .then(values => { //console.log("values=",values); /*for (var iv = 0; iv < values.length; iv++) { this.instances[values[iv].instance] = { emoji : values[iv] }; }*/ AppStorage.set(this.setting.INSTANCEEMOJI,this.instances); }) .finally(()=>{ this.items.forEach(e=>{ e.stream.start(); e.direct.start(); }); resolve(this.items); }); } } else { reject(false); } } }); return def; }
load() { var def = new Promise((resolve, reject) => { this.items.splice(0, this.items.length); if (curLocale.environment.platform == "windowsapp") { var folder = Windows.Storage.ApplicationData.current.localFolder; folder.getFileAsync(this.setting.NAME) .then((file) => { var reader = new FileReader(); reader.onload = (e) => { var text = reader.result; this.items = JSON.parse(text); resolve(this.items); }; reader.onerror = (e) => { appAlert("not valid file!!"); reject("error"); }; reader.readAsText(file); }, function (data) { console.log("AccountManager.load: not found ini file."); }); } else { var fdata = AppStorage.get(this.setting.NAME, null); if (fdata && (fdata.length > 0)) { if (!docCookies.getItem(MYAPP.siteinfo.cke)) { docCookies.setItem(MYAPP.siteinfo.cke,"1"); } var promises = []; var emojitest = AppStorage.get(this.setting.INSTANCEEMOJI, null); if (emojitest) { var values = (emojitest); this.instances = values; for (var i = 0; i < fdata.length; i++) { var ac = new Account(); ac.load(fdata[i]); //console.log("ac.api=",ac.api,values[ac.instance]); ac.api.setConfig("stream_url",values[ac.instance].info.urls.streaming_api); if ((location.pathname != "/toot/new") && (location.pathname != "/") && (location.pathname != "/arch")) { ac.stream.start(); ac.direct.start(); } this.items.push(ac); this.backupItems.push(ac); //console.log(ac.instance); } /*for (var iv = 0; iv < values.length; iv++) { this.instances[values[iv].instance] = { emoji : values[iv] }; }*/ resolve(this.items); }else{ for (var i = 0; i < fdata.length; i++) { var ac = new Account(); ac.load(fdata[i]); this.items.push(ac); this.backupItems.push(ac); //console.log(ac.instance); //var pro = MYAPP.sns.getInstanceEmoji(ac.instance); //promises.push(pro); promises.push( MYAPP.sns.getInstanceInfo(ac.instance) .then(result=> { //---no neccesary https// (add automatically) result.uri = result.uri.replace("https://",""); this.instances[result.uri] = { info : result, instance : result.uri }; for (var ainx = 0; ainx < this.items.length; ainx++) { if (this.items[ainx].instance == result.uri) { this.items[ainx].token["stream_url"] = result.urls.streaming_api; this.items[ainx].api.setConfig("stream_url",result.urls.streaming_api); } } return {data:this.instances[result.uri], instance : result.uri }; }) .then(result2=> { return MYAPP.sns.getInstanceEmoji(result2.instance) .then(emojiresult => { return result2.data["emoji"] = emojiresult; }); }) ); } //resolve(this.items); Promise.all(promises) .then(values => { //console.log("values=",values); /*for (var iv = 0; iv < values.length; iv++) { this.instances[values[iv].instance] = { emoji : values[iv] }; }*/ AppStorage.set(this.setting.INSTANCEEMOJI,this.instances); }) .finally(()=>{ this.items.forEach(e=>{ e.stream.start(); e.direct.start(); }); resolve(this.items); }); } } else { reject(false); } } }); return def; }
JavaScript
function exportToHTML (view) { const title = renderTitle(ui.area.markdown) const filename = `${renderFilename(ui.area.markdown)}.html` const src = generateCleanHTML(view) // generate toc const toc = $('#ui-toc').clone() toc.find('*').removeClass('active').find("a[href^='#'][smoothhashscroll]").removeAttr('smoothhashscroll') const tocAffix = $('#ui-toc-affix').clone() tocAffix.find('*').removeClass('active').find("a[href^='#'][smoothhashscroll]").removeAttr('smoothhashscroll') // generate html via template $.get(`${serverurl}/build/html.min.css`, css => { $.get(`${serverurl}/views/html.hbs`, data => { const template = window.Handlebars.compile(data) const context = { url: serverurl, title, css, html: src[0].outerHTML, 'ui-toc': toc.html(), 'ui-toc-affix': tocAffix.html(), lang: (md && md.meta && md.meta.lang) ? `lang="${md.meta.lang}"` : null, dir: (md && md.meta && md.meta.dir) ? `dir="${md.meta.dir}"` : null } const html = template(context) // console.log(html); const blob = new Blob([html], { type: 'text/html;charset=utf-8' }) saveAs(blob, filename, true) }) }) }
function exportToHTML (view) { const title = renderTitle(ui.area.markdown) const filename = `${renderFilename(ui.area.markdown)}.html` const src = generateCleanHTML(view) // generate toc const toc = $('#ui-toc').clone() toc.find('*').removeClass('active').find("a[href^='#'][smoothhashscroll]").removeAttr('smoothhashscroll') const tocAffix = $('#ui-toc-affix').clone() tocAffix.find('*').removeClass('active').find("a[href^='#'][smoothhashscroll]").removeAttr('smoothhashscroll') // generate html via template $.get(`${serverurl}/build/html.min.css`, css => { $.get(`${serverurl}/views/html.hbs`, data => { const template = window.Handlebars.compile(data) const context = { url: serverurl, title, css, html: src[0].outerHTML, 'ui-toc': toc.html(), 'ui-toc-affix': tocAffix.html(), lang: (md && md.meta && md.meta.lang) ? `lang="${md.meta.lang}"` : null, dir: (md && md.meta && md.meta.dir) ? `dir="${md.meta.dir}"` : null } const html = template(context) // console.log(html); const blob = new Blob([html], { type: 'text/html;charset=utf-8' }) saveAs(blob, filename, true) }) }) }
JavaScript
function assert(b, msg) { if (!b) { throw new Error(msg || "assertion error"); } }
function assert(b, msg) { if (!b) { throw new Error(msg || "assertion error"); } }
JavaScript
function secure (socket, next) { try { var handshakeData = socket.request if (handshakeData.headers.cookie) { handshakeData.cookie = cookie.parse(handshakeData.headers.cookie) handshakeData.sessionID = cookieParser.signedCookie(handshakeData.cookie[config.sessionname], config.sessionsecret) if (handshakeData.sessionID && handshakeData.cookie[config.sessionname] && handshakeData.cookie[config.sessionname] !== handshakeData.sessionID) { if (config.debug) { logger.info('AUTH success cookie: ' + handshakeData.sessionID) } return next() } else { next(new Error('AUTH failed: Cookie is invalid.')) } } else { next(new Error('AUTH failed: No cookie transmitted.')) } } catch (ex) { next(new Error('AUTH failed:' + JSON.stringify(ex))) } }
function secure (socket, next) { try { var handshakeData = socket.request if (handshakeData.headers.cookie) { handshakeData.cookie = cookie.parse(handshakeData.headers.cookie) handshakeData.sessionID = cookieParser.signedCookie(handshakeData.cookie[config.sessionname], config.sessionsecret) if (handshakeData.sessionID && handshakeData.cookie[config.sessionname] && handshakeData.cookie[config.sessionname] !== handshakeData.sessionID) { if (config.debug) { logger.info('AUTH success cookie: ' + handshakeData.sessionID) } return next() } else { next(new Error('AUTH failed: Cookie is invalid.')) } } else { next(new Error('AUTH failed: No cookie transmitted.')) } } catch (ex) { next(new Error('AUTH failed:' + JSON.stringify(ex))) } }
JavaScript
function show(options) { var currentDate = new Date(); defaults = { initialYear: currentDate.getFullYear(), initialMonth: currentDate.getMonth(), eventsUrl: 'events-data.json', extractEvents: function extractEvents(data) { return data.data; }, eventList: [], monthNames: [], dayNames: [], dayNamesAbbreviated: [], dayNamesMinimum: [], dayNamesShort: [], classContainer: 'bec-container', classDay: 'bec-day', classDayLabel: 'bec-day-label', classDaysContainer: 'bec-days-container', classDaysHeader: 'bec-days-header', classDaysList: 'bec-days', classEvent: 'bec-event', classEventsList: 'bec-events', classMonthNext: 'bec-button-next', classMonthPrevious: 'bec-button-prev', classWeek: 'bec-week', markupDayHeaderSunday: function markupDayHeaderSunday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexSunday); }, markupDayHeaderMonday: function markupDayHeaderMonday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexMonday); }, markupDayHeaderTuesday: function markupDayHeaderTuesday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexTuesday); }, markupDayHeaderWednesday: function markupDayHeaderWednesday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexWednesday); }, markupDayHeaderThursday: function markupDayHeaderThursday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexThursday); }, markupDayHeaderFriday: function markupDayHeaderFriday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexFriday); }, markupDayHeaderSaturday: function markupDayHeaderSaturday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexSaturday); }, markupEvent: getDefaultRenderEvent }; settings = Object.assign({}, defaults, (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' && options); if (settings.monthNames.length === 12) { dateHelper.monthNames = settings.monthNames; } if (settings.dayNames.length === 7) { dateHelper.dayNames = settings.dayNames; } if (settings.dayNamesAbbreviated.length === 7) { dateHelper.dayNamesAbbreviated = settings.dayNamesAbbreviated; } if (settings.dayNamesMinimum.length === 7) { dateHelper.dayNamesMinimum = settings.dayNamesMinimum; } if (settings.dayNamesShort.length === 7) { dateHelper.dayNamesShort = settings.dayNamesShort; } var doFetch = 'yes'; if (Array.isArray(settings.eventList) && settings.eventList.length > 0) { doFetch = 'no'; } renderMonth(settings.initialYear, settings.initialMonth, doFetch); }
function show(options) { var currentDate = new Date(); defaults = { initialYear: currentDate.getFullYear(), initialMonth: currentDate.getMonth(), eventsUrl: 'events-data.json', extractEvents: function extractEvents(data) { return data.data; }, eventList: [], monthNames: [], dayNames: [], dayNamesAbbreviated: [], dayNamesMinimum: [], dayNamesShort: [], classContainer: 'bec-container', classDay: 'bec-day', classDayLabel: 'bec-day-label', classDaysContainer: 'bec-days-container', classDaysHeader: 'bec-days-header', classDaysList: 'bec-days', classEvent: 'bec-event', classEventsList: 'bec-events', classMonthNext: 'bec-button-next', classMonthPrevious: 'bec-button-prev', classWeek: 'bec-week', markupDayHeaderSunday: function markupDayHeaderSunday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexSunday); }, markupDayHeaderMonday: function markupDayHeaderMonday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexMonday); }, markupDayHeaderTuesday: function markupDayHeaderTuesday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexTuesday); }, markupDayHeaderWednesday: function markupDayHeaderWednesday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexWednesday); }, markupDayHeaderThursday: function markupDayHeaderThursday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexThursday); }, markupDayHeaderFriday: function markupDayHeaderFriday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexFriday); }, markupDayHeaderSaturday: function markupDayHeaderSaturday() { return getDefaultDayHeaderMarkup(dateHelper.dayIndexSaturday); }, markupEvent: getDefaultRenderEvent }; settings = Object.assign({}, defaults, (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' && options); if (settings.monthNames.length === 12) { dateHelper.monthNames = settings.monthNames; } if (settings.dayNames.length === 7) { dateHelper.dayNames = settings.dayNames; } if (settings.dayNamesAbbreviated.length === 7) { dateHelper.dayNamesAbbreviated = settings.dayNamesAbbreviated; } if (settings.dayNamesMinimum.length === 7) { dateHelper.dayNamesMinimum = settings.dayNamesMinimum; } if (settings.dayNamesShort.length === 7) { dateHelper.dayNamesShort = settings.dayNamesShort; } var doFetch = 'yes'; if (Array.isArray(settings.eventList) && settings.eventList.length > 0) { doFetch = 'no'; } renderMonth(settings.initialYear, settings.initialMonth, doFetch); }
JavaScript
function attachDayClickHandler() { (0, _jquery2.default)('.' + settings.classDay) // add 'selected day' styling .on('click', function (event) { (0, _jquery2.default)('.' + settings.classDay).removeClass('active'); (0, _jquery2.default)(event.target).addClass('active'); }) // display events for day .on('click', function (event) { var $target = (0, _jquery2.default)(event.target); var eventYear = $target.data('year'); var eventMonth = $target.data('month'); var eventDay = $target.data('day'); displayEventsForDay(settings.classEvent, eventYear, eventMonth, eventDay); }); }
function attachDayClickHandler() { (0, _jquery2.default)('.' + settings.classDay) // add 'selected day' styling .on('click', function (event) { (0, _jquery2.default)('.' + settings.classDay).removeClass('active'); (0, _jquery2.default)(event.target).addClass('active'); }) // display events for day .on('click', function (event) { var $target = (0, _jquery2.default)(event.target); var eventYear = $target.data('year'); var eventMonth = $target.data('month'); var eventDay = $target.data('day'); displayEventsForDay(settings.classEvent, eventYear, eventMonth, eventDay); }); }
JavaScript
function attachNextMonthClickHandler(classSelector, currentYear, currentMonth) { (0, _jquery2.default)('.' + classSelector).on('click', function (event) { event.preventDefault(); var nextMonth = dateHelper.getNextMonth(currentYear, currentMonth); renderMonth(nextMonth.year, nextMonth.month, 'yes'); }); }
function attachNextMonthClickHandler(classSelector, currentYear, currentMonth) { (0, _jquery2.default)('.' + classSelector).on('click', function (event) { event.preventDefault(); var nextMonth = dateHelper.getNextMonth(currentYear, currentMonth); renderMonth(nextMonth.year, nextMonth.month, 'yes'); }); }
JavaScript
function attachPreviousMonthClickHandler(classSelector, currentYear, currentMonth) { (0, _jquery2.default)('.' + classSelector).on('click', function (event) { event.preventDefault(); var previousMonth = dateHelper.getPreviousMonth(currentYear, currentMonth); renderMonth(previousMonth.year, previousMonth.month, 'yes'); }); }
function attachPreviousMonthClickHandler(classSelector, currentYear, currentMonth) { (0, _jquery2.default)('.' + classSelector).on('click', function (event) { event.preventDefault(); var previousMonth = dateHelper.getPreviousMonth(currentYear, currentMonth); renderMonth(previousMonth.year, previousMonth.month, 'yes'); }); }
JavaScript
function displayEventsForDay(classSelector, year, month, day) { (0, _jquery2.default)('.' + classSelector).slideUp('slow'); var selector = '.' + classSelector + '[data-year="' + year + '"][data-month="' + month + '"][data-day="' + day + '"]'; (0, _jquery2.default)(selector).slideDown('slow'); }
function displayEventsForDay(classSelector, year, month, day) { (0, _jquery2.default)('.' + classSelector).slideUp('slow'); var selector = '.' + classSelector + '[data-year="' + year + '"][data-month="' + month + '"][data-day="' + day + '"]'; (0, _jquery2.default)(selector).slideDown('slow'); }
JavaScript
function markCurrentDay(displayYear, displayMonth) { var today = new Date(); var todayYear = today.getFullYear(); var todayMonth = today.getMonth(); var todayDay = today.getDate(); if (parseInt(displayYear, 10) === todayYear) { if (parseInt(displayMonth, 10) === todayMonth) { var $days = (0, _jquery2.default)('.' + settings.classDay); $days.filter('[data-day="' + todayDay + '"]').addClass('current-day'); } } }
function markCurrentDay(displayYear, displayMonth) { var today = new Date(); var todayYear = today.getFullYear(); var todayMonth = today.getMonth(); var todayDay = today.getDate(); if (parseInt(displayYear, 10) === todayYear) { if (parseInt(displayMonth, 10) === todayMonth) { var $days = (0, _jquery2.default)('.' + settings.classDay); $days.filter('[data-day="' + todayDay + '"]').addClass('current-day'); } } }
JavaScript
function markEventDays(displayYear, displayMonth) { (0, _jquery2.default)('.' + settings.classEvent).each(function (index, element) { var year = (0, _jquery2.default)(element).data('year'); var month = (0, _jquery2.default)(element).data('month'); if (parseInt(year, 10) === parseInt(displayYear, 10) && parseInt(month, 10) === parseInt(displayMonth, 10)) { var day = (0, _jquery2.default)(element).data('day'); var selector = '.' + settings.classDay + '[data-year="' + year + '"][data-month="' + month + '"][data-day="' + day + '"]'; (0, _jquery2.default)(selector).addClass('event'); } }); }
function markEventDays(displayYear, displayMonth) { (0, _jquery2.default)('.' + settings.classEvent).each(function (index, element) { var year = (0, _jquery2.default)(element).data('year'); var month = (0, _jquery2.default)(element).data('month'); if (parseInt(year, 10) === parseInt(displayYear, 10) && parseInt(month, 10) === parseInt(displayMonth, 10)) { var day = (0, _jquery2.default)(element).data('day'); var selector = '.' + settings.classDay + '[data-year="' + year + '"][data-month="' + month + '"][data-day="' + day + '"]'; (0, _jquery2.default)(selector).addClass('event'); } }); }
JavaScript
function renderBase() { var markupHeaderPrevious = '<a class="' + settings.classMonthPrevious + '" href="#" title="Previous month" role="button">&lsaquo;</a>'; var markupHeaderNext = '<a class="' + settings.classMonthNext + '" href="#" title="Next month" role="button">&rsaquo;</a>'; var markupHeader = '<header>' + markupHeaderPrevious + '<h1></h1>' + markupHeaderNext + '</header>'; var markupDaysHeader = '<div class="' + settings.classDaysHeader + '"></div>'; var weekNumbers = [1, 2, 3, 4, 5, 6]; var markupDaysList = (0, _html2.default)(_templateObject, settings.classDaysList, weekNumbers.map(function (weekNumber) { return '<div class="' + settings.classWeek + '" data-week="' + weekNumber + '"></div>'; })); var markupEvents = '<div class="' + settings.classEventsList + '"></div>'; var markup = '\n <section>\n <div class="' + settings.classDaysContainer + '">\n ' + markupHeader + '\n ' + markupDaysHeader + '\n ' + markupDaysList + '\n </div>\n ' + markupEvents + '\n </section>'; clearCalendar(settings); (0, _jquery2.default)('.' + settings.classContainer).append(markup); }
function renderBase() { var markupHeaderPrevious = '<a class="' + settings.classMonthPrevious + '" href="#" title="Previous month" role="button">&lsaquo;</a>'; var markupHeaderNext = '<a class="' + settings.classMonthNext + '" href="#" title="Next month" role="button">&rsaquo;</a>'; var markupHeader = '<header>' + markupHeaderPrevious + '<h1></h1>' + markupHeaderNext + '</header>'; var markupDaysHeader = '<div class="' + settings.classDaysHeader + '"></div>'; var weekNumbers = [1, 2, 3, 4, 5, 6]; var markupDaysList = (0, _html2.default)(_templateObject, settings.classDaysList, weekNumbers.map(function (weekNumber) { return '<div class="' + settings.classWeek + '" data-week="' + weekNumber + '"></div>'; })); var markupEvents = '<div class="' + settings.classEventsList + '"></div>'; var markup = '\n <section>\n <div class="' + settings.classDaysContainer + '">\n ' + markupHeader + '\n ' + markupDaysHeader + '\n ' + markupDaysList + '\n </div>\n ' + markupEvents + '\n </section>'; clearCalendar(settings); (0, _jquery2.default)('.' + settings.classContainer).append(markup); }
JavaScript
function renderEvents(events) { events.forEach(function (element) { var markup = settings.markupEvent()(element); (0, _jquery2.default)('.' + settings.classEventsList).append(markup); }); }
function renderEvents(events) { events.forEach(function (element) { var markup = settings.markupEvent()(element); (0, _jquery2.default)('.' + settings.classEventsList).append(markup); }); }
JavaScript
function onNewParticipant(channel, extra) { if (!channel || !!participants[channel] || channel == self.userid) return; participants[channel] = channel; var new_channel = root.token(); newPrivateSocket({ channel: new_channel, extra: extra || {} }); defaultSocket.send({ participant: true, userid: self.userid, targetUser: channel, channel: new_channel, extra: root.extra }); }
function onNewParticipant(channel, extra) { if (!channel || !!participants[channel] || channel == self.userid) return; participants[channel] = channel; var new_channel = root.token(); newPrivateSocket({ channel: new_channel, extra: extra || {} }); defaultSocket.send({ participant: true, userid: self.userid, targetUser: channel, channel: new_channel, extra: root.extra }); }
JavaScript
function SoundMeter(config) { var root = config.root; var context = config.context; this.context = context; this.volume = 0.0; this.slow_volume = 0.0; this.clip = 0.0; // Legal values are (256, 512, 1024, 2048, 4096, 8192, 16384) this.script = context.createScriptProcessor(256, 1, 1); that = this; this.script.onaudioprocess = function (event) { var input = event.inputBuffer.getChannelData(0); var i; var sum = 0.0; var clipcount = 0; for (i = 0; i < input.length; ++i) { sum += input[i] * input[i]; if (Math.abs(input[i]) > 0.99) { clipcount += 1; } } that.volume = Math.sqrt(sum / input.length); var volume = that.volume.toFixed(2); if (volume >= .1 && root.onspeaking) { root.onspeaking(config.event); } if (volume < .1 && root.onsilence) { root.onsilence(config.event); } }; }
function SoundMeter(config) { var root = config.root; var context = config.context; this.context = context; this.volume = 0.0; this.slow_volume = 0.0; this.clip = 0.0; // Legal values are (256, 512, 1024, 2048, 4096, 8192, 16384) this.script = context.createScriptProcessor(256, 1, 1); that = this; this.script.onaudioprocess = function (event) { var input = event.inputBuffer.getChannelData(0); var i; var sum = 0.0; var clipcount = 0; for (i = 0; i < input.length; ++i) { sum += input[i] * input[i]; if (Math.abs(input[i]) > 0.99) { clipcount += 1; } } that.volume = Math.sqrt(sum / input.length); var volume = that.volume.toFixed(2); if (volume >= .1 && root.onspeaking) { root.onspeaking(config.event); } if (volume < .1 && root.onsilence) { root.onsilence(config.event); } }; }
JavaScript
function createOffer(to) { var _options = options; _options.to = to; _options.stream = root.stream; peers[to] = Offer.createOffer(_options); }
function createOffer(to) { var _options = options; _options.to = to; _options.stream = root.stream; peers[to] = Offer.createOffer(_options); }
JavaScript
function repeatedlyCreateOffer() { var firstParticipant = signaler.participants[0]; if (!firstParticipant) return; signaler.creatingOffer = true; createOffer(firstParticipant); // delete "firstParticipant" and swap array delete signaler.participants[0]; signaler.participants = swap(signaler.participants); setTimeout(function() { signaler.creatingOffer = false; if (signaler.participants[0]) repeatedlyCreateOffer(); }, 1000); }
function repeatedlyCreateOffer() { var firstParticipant = signaler.participants[0]; if (!firstParticipant) return; signaler.creatingOffer = true; createOffer(firstParticipant); // delete "firstParticipant" and swap array delete signaler.participants[0]; signaler.participants = swap(signaler.participants); setTimeout(function() { signaler.creatingOffer = false; if (signaler.participants[0]) repeatedlyCreateOffer(); }, 1000); }
JavaScript
function _serialize(mLine) { if (!mLines[mLine]) { mLines[mLine] = { line: line, attributes: [], payload: { }, ssrc: [], crypto: { } }; // get all available payload types in current m-line if(line.indexOf('RTP/SAVPF')!=-1) { var payloads = line.split('RTP/SAVPF ')[1].split(' '); for (var p = 0; p < payloads.length; p++) { mLines[mLine].payload[payloads[p]] = ''; } } } else { if (line == 'a=mid:' + mLine) { var prevLine = splitted[i - 1]; if (prevLine) { mLines[mLine].direction = prevLine.split('a=')[1]; // remove "direction" attribute mLines[mLine].attributes.pop(1); } isMidLine = true; mLines[mLine]['a=mid:' + mLine] = { line: line, attributes: [] }; } else if (isMidLine) { if (line.indexOf('a=crypto:') == 0) { mLines[mLine].crypto[line.split('AES_CM_128_HMAC_SHA1_')[1].split(' ')[0]] = line; } else if (line.indexOf('a=rtpmap:') == 0) { var _splitted = line.split('a=rtpmap:')[1].split(' '); mLines[mLine].payload[_splitted[0]] = _splitted[1]; // a single payload can contain multiple attributes (function selfInvoker() { line = splitted[i + 1]; if (line && line.indexOf('a=rtpmap:') == -1 && line.indexOf('m=') == -1) { if (line.indexOf('a=ssrc') == -1) { mLines[mLine].payload[_splitted[0]] += '\r\n' + line; } // media-lines if (line.indexOf('a=ssrc') != -1) { mLines[mLine].ssrc.push(line); } i++; selfInvoker(); } })(); } else { mLines[mLine]['a=mid:' + mLine].attributes.push(line); } } else { mLines[mLine].attributes.push(line); } } }
function _serialize(mLine) { if (!mLines[mLine]) { mLines[mLine] = { line: line, attributes: [], payload: { }, ssrc: [], crypto: { } }; // get all available payload types in current m-line if(line.indexOf('RTP/SAVPF')!=-1) { var payloads = line.split('RTP/SAVPF ')[1].split(' '); for (var p = 0; p < payloads.length; p++) { mLines[mLine].payload[payloads[p]] = ''; } } } else { if (line == 'a=mid:' + mLine) { var prevLine = splitted[i - 1]; if (prevLine) { mLines[mLine].direction = prevLine.split('a=')[1]; // remove "direction" attribute mLines[mLine].attributes.pop(1); } isMidLine = true; mLines[mLine]['a=mid:' + mLine] = { line: line, attributes: [] }; } else if (isMidLine) { if (line.indexOf('a=crypto:') == 0) { mLines[mLine].crypto[line.split('AES_CM_128_HMAC_SHA1_')[1].split(' ')[0]] = line; } else if (line.indexOf('a=rtpmap:') == 0) { var _splitted = line.split('a=rtpmap:')[1].split(' '); mLines[mLine].payload[_splitted[0]] = _splitted[1]; // a single payload can contain multiple attributes (function selfInvoker() { line = splitted[i + 1]; if (line && line.indexOf('a=rtpmap:') == -1 && line.indexOf('m=') == -1) { if (line.indexOf('a=ssrc') == -1) { mLines[mLine].payload[_splitted[0]] += '\r\n' + line; } // media-lines if (line.indexOf('a=ssrc') != -1) { mLines[mLine].ssrc.push(line); } i++; selfInvoker(); } })(); } else { mLines[mLine]['a=mid:' + mLine].attributes.push(line); } } else { mLines[mLine].attributes.push(line); } } }
JavaScript
function order(payload, position, mLine) { // if invalid payload type if (!mLines[mLine] || mLines[mLine].line.indexOf(payload) == -1) return; if(mLines[mLine].line.indexOf('RTP/SAVPF')==-1) return; var payloads = mLines[mLine].line.split('RTP/SAVPF ')[1].split(' '); var arr = []; for (var i = 0; i < payloads.length; i++) { if (payloads[i] == payload) { arr[position] = payloads[i]; delete payloads[i]; payloads = swap(payloads); } } for (var i = 0; i < payloads.length; i++) { if (i < position) arr[i] = payloads[i]; if (i >= position) arr[i + 1] = payloads[i]; } // to remove NULL entries arr = swap(arr); mLines[mLine].line = mLines[mLine].line.split('RTP/SAVPF ')[0] + 'RTP/SAVPF ' + arr.join(' '); }
function order(payload, position, mLine) { // if invalid payload type if (!mLines[mLine] || mLines[mLine].line.indexOf(payload) == -1) return; if(mLines[mLine].line.indexOf('RTP/SAVPF')==-1) return; var payloads = mLines[mLine].line.split('RTP/SAVPF ')[1].split(' '); var arr = []; for (var i = 0; i < payloads.length; i++) { if (payloads[i] == payload) { arr[position] = payloads[i]; delete payloads[i]; payloads = swap(payloads); } } for (var i = 0; i < payloads.length; i++) { if (i < position) arr[i] = payloads[i]; if (i >= position) arr[i + 1] = payloads[i]; } // to remove NULL entries arr = swap(arr); mLines[mLine].line = mLines[mLine].line.split('RTP/SAVPF ')[0] + 'RTP/SAVPF ' + arr.join(' '); }
JavaScript
function toWebM(frames) { var info = checkFrames(frames); var counter = 0; var EBML = [ { "id": 0x1a45dfa3, // EBML "data": [ { "data": 1, "id": 0x4286 // EBMLVersion }, { "data": 1, "id": 0x42f7 // EBMLReadVersion }, { "data": 4, "id": 0x42f2 // EBMLMaxIDLength }, { "data": 8, "id": 0x42f3 // EBMLMaxSizeLength }, { "data": "webm", "id": 0x4282 // DocType }, { "data": 2, "id": 0x4287 // DocTypeVersion }, { "data": 2, "id": 0x4285 // DocTypeReadVersion } ] }, { "id": 0x18538067, // Segment "data": [ { "id": 0x1549a966, // Info "data": [ { "data": 1e6, //do things in millisecs (num of nanosecs for duration scale) "id": 0x2ad7b1 // TimecodeScale }, { "data": "whammy", "id": 0x4d80 // MuxingApp }, { "data": "whammy", "id": 0x5741 // WritingApp }, { "data": doubleToString(info.duration), "id": 0x4489 // Duration } ] }, { "id": 0x1654ae6b, // Tracks "data": [ { "id": 0xae, // TrackEntry "data": [ { "data": 1, "id": 0xd7 // TrackNumber }, { "data": 1, "id": 0x63c5 // TrackUID }, { "data": 0, "id": 0x9c // FlagLacing }, { "data": "und", "id": 0x22b59c // Language }, { "data": "V_VP8", "id": 0x86 // CodecID }, { "data": "VP8", "id": 0x258688 // CodecName }, { "data": 1, "id": 0x83 // TrackType }, { "id": 0xe0, // Video "data": [ { "data": info.width, "id": 0xb0 // PixelWidth }, { "data": info.height, "id": 0xba // PixelHeight } ] } ] } ] }, { "id": 0x1f43b675, // Cluster "data": [ { "data": 0, "id": 0xe7 // Timecode } ].concat(frames.map(function(webp) { var block = makeSimpleBlock({ discardable: 0, frame: webp.data.slice(4), invisible: 0, keyframe: 1, lacing: 0, trackNum: 1, timecode: Math.round(counter) }); counter += webp.duration; return { data: block, id: 0xa3 }; })) } ] } ]; return generateEBML(EBML); }
function toWebM(frames) { var info = checkFrames(frames); var counter = 0; var EBML = [ { "id": 0x1a45dfa3, // EBML "data": [ { "data": 1, "id": 0x4286 // EBMLVersion }, { "data": 1, "id": 0x42f7 // EBMLReadVersion }, { "data": 4, "id": 0x42f2 // EBMLMaxIDLength }, { "data": 8, "id": 0x42f3 // EBMLMaxSizeLength }, { "data": "webm", "id": 0x4282 // DocType }, { "data": 2, "id": 0x4287 // DocTypeVersion }, { "data": 2, "id": 0x4285 // DocTypeReadVersion } ] }, { "id": 0x18538067, // Segment "data": [ { "id": 0x1549a966, // Info "data": [ { "data": 1e6, //do things in millisecs (num of nanosecs for duration scale) "id": 0x2ad7b1 // TimecodeScale }, { "data": "whammy", "id": 0x4d80 // MuxingApp }, { "data": "whammy", "id": 0x5741 // WritingApp }, { "data": doubleToString(info.duration), "id": 0x4489 // Duration } ] }, { "id": 0x1654ae6b, // Tracks "data": [ { "id": 0xae, // TrackEntry "data": [ { "data": 1, "id": 0xd7 // TrackNumber }, { "data": 1, "id": 0x63c5 // TrackUID }, { "data": 0, "id": 0x9c // FlagLacing }, { "data": "und", "id": 0x22b59c // Language }, { "data": "V_VP8", "id": 0x86 // CodecID }, { "data": "VP8", "id": 0x258688 // CodecName }, { "data": 1, "id": 0x83 // TrackType }, { "id": 0xe0, // Video "data": [ { "data": info.width, "id": 0xb0 // PixelWidth }, { "data": info.height, "id": 0xba // PixelHeight } ] } ] } ] }, { "id": 0x1f43b675, // Cluster "data": [ { "data": 0, "id": 0xe7 // Timecode } ].concat(frames.map(function(webp) { var block = makeSimpleBlock({ discardable: 0, frame: webp.data.slice(4), invisible: 0, keyframe: 1, lacing: 0, trackNum: 1, timecode: Math.round(counter) }); counter += webp.duration; return { data: block, id: 0xa3 }; })) } ] } ]; return generateEBML(EBML); }
JavaScript
function checkFrames(frames) { var width = frames[0].width, height = frames[0].height, duration = frames[0].duration; for (var i = 1; i < frames.length; i++) { if (frames[i].width != width) throw "Frame " + (i + 1) + " has a different width"; if (frames[i].height != height) throw "Frame " + (i + 1) + " has a different height"; if (frames[i].duration < 0) throw "Frame " + (i + 1) + " has a weird duration"; duration += frames[i].duration; } return { duration: duration, width: width, height: height }; }
function checkFrames(frames) { var width = frames[0].width, height = frames[0].height, duration = frames[0].duration; for (var i = 1; i < frames.length; i++) { if (frames[i].width != width) throw "Frame " + (i + 1) + " has a different width"; if (frames[i].height != height) throw "Frame " + (i + 1) + " has a different height"; if (frames[i].duration < 0) throw "Frame " + (i + 1) + " has a weird duration"; duration += frames[i].duration; } return { duration: duration, width: width, height: height }; }
JavaScript
function bitsToBuffer(bits) { var data = []; var pad = (bits.length % 8) ? (new Array(1 + 8 - (bits.length % 8))).join('0') : ''; bits = pad + bits; for (var i = 0; i < bits.length; i += 8) { data.push(parseInt(bits.substr(i, 8), 2)); } return new Uint8Array(data); }
function bitsToBuffer(bits) { var data = []; var pad = (bits.length % 8) ? (new Array(1 + 8 - (bits.length % 8))).join('0') : ''; bits = pad + bits; for (var i = 0; i < bits.length; i += 8) { data.push(parseInt(bits.substr(i, 8), 2)); } return new Uint8Array(data); }
JavaScript
function makeSimpleBlock(data) { var flags = 0; if (data.keyframe) flags |= 128; if (data.invisible) flags |= 8; if (data.lacing) flags |= (data.lacing << 1); if (data.discardable) flags |= 1; if (data.trackNum > 127) { throw "TrackNumber > 127 not supported"; } var out = [data.trackNum | 0x80, data.timecode >> 8, data.timecode & 0xff, flags].map(function(e) { return String.fromCharCode(e); }).join('') + data.frame; return out; }
function makeSimpleBlock(data) { var flags = 0; if (data.keyframe) flags |= 128; if (data.invisible) flags |= 8; if (data.lacing) flags |= (data.lacing << 1); if (data.discardable) flags |= 1; if (data.trackNum > 127) { throw "TrackNumber > 127 not supported"; } var out = [data.trackNum | 0x80, data.timecode >> 8, data.timecode & 0xff, flags].map(function(e) { return String.fromCharCode(e); }).join('') + data.frame; return out; }
JavaScript
function parseRIFF(string) { var offset = 0; var chunks = { }; while (offset < string.length) { var id = string.substr(offset, 4); var len = parseInt(string.substr(offset + 4, 4).split('').map(function(i) { var unpadded = i.charCodeAt(0).toString(2); return (new Array(8 - unpadded.length + 1)).join('0') + unpadded; }).join(''), 2); var data = string.substr(offset + 4 + 4, len); offset += 4 + 4 + len; chunks[id] = chunks[id] || []; if (id == 'RIFF' || id == 'LIST') { chunks[id].push(parseRIFF(data)); } else { chunks[id].push(data); } } return chunks; }
function parseRIFF(string) { var offset = 0; var chunks = { }; while (offset < string.length) { var id = string.substr(offset, 4); var len = parseInt(string.substr(offset + 4, 4).split('').map(function(i) { var unpadded = i.charCodeAt(0).toString(2); return (new Array(8 - unpadded.length + 1)).join('0') + unpadded; }).join(''), 2); var data = string.substr(offset + 4 + 4, len); offset += 4 + 4 + len; chunks[id] = chunks[id] || []; if (id == 'RIFF' || id == 'LIST') { chunks[id].push(parseRIFF(data)); } else { chunks[id].push(data); } } return chunks; }
JavaScript
function doubleToString(num) { return [].slice.call( new Uint8Array( ( new Float64Array([num]) // create a float64 array // extract the array buffer ).buffer), 0) // convert the Uint8Array into a regular array .map(function(e) { // since it's a regular array, we can now use map return String.fromCharCode(e); // encode all the bytes individually }) .reverse() // correct the byte endianness (assume it's little endian for now) .join(''); // join the bytes in holy matrimony as a string }
function doubleToString(num) { return [].slice.call( new Uint8Array( ( new Float64Array([num]) // create a float64 array // extract the array buffer ).buffer), 0) // convert the Uint8Array into a regular array .map(function(e) { // since it's a regular array, we can now use map return String.fromCharCode(e); // encode all the bytes individually }) .reverse() // correct the byte endianness (assume it's little endian for now) .join(''); // join the bytes in holy matrimony as a string }
JavaScript
function prepareInit(callback) { if (!self.openSignalingChannel) { // https://github.com/muaz-khan/WebRTC-Experiment/blob/master/socketio-over-nodejs // https://github.com/muaz-khan/WebRTC-Experiment/blob/master/websocket-over-nodejs self.openSignalingChannel = function(config) { config.channel = config.channel || self.channel || location.hash.substr(1); var websocket = new WebSocket('wss://www.webrtc-experiment.com:8563'); websocket.channel = config.channel; websocket.onopen = function() { websocket.push(JSON.stringify({ open: true, channel: config.channel })); if (config.callback) config.callback(websocket); }; websocket.onmessage = function(event) { config.onmessage(JSON.parse(event.data)); }; websocket.push = websocket.send; websocket.send = function(data) { if (websocket.readyState != 1) return setTimeout(function() { websocket.send(data); }, 500); websocket.push(JSON.stringify({ data: data, channel: config.channel })); }; }; callback(); } else callback(); }
function prepareInit(callback) { if (!self.openSignalingChannel) { // https://github.com/muaz-khan/WebRTC-Experiment/blob/master/socketio-over-nodejs // https://github.com/muaz-khan/WebRTC-Experiment/blob/master/websocket-over-nodejs self.openSignalingChannel = function(config) { config.channel = config.channel || self.channel || location.hash.substr(1); var websocket = new WebSocket('wss://www.webrtc-experiment.com:8563'); websocket.channel = config.channel; websocket.onopen = function() { websocket.push(JSON.stringify({ open: true, channel: config.channel })); if (config.callback) config.callback(websocket); }; websocket.onmessage = function(event) { config.onmessage(JSON.parse(event.data)); }; websocket.push = websocket.send; websocket.send = function(data) { if (websocket.readyState != 1) return setTimeout(function() { websocket.send(data); }, 500); websocket.push(JSON.stringify({ data: data, channel: config.channel })); }; }; callback(); } else callback(); }
JavaScript
function captureUserMedia(callback, _session) { var session = _session || self.session; if (self.dontAttachStream) return callback(); if (isData(session) || (!self.isInitiator && session.oneway)) { self.attachStreams = []; return callback(); } var constraints = { audio: !!session.audio, video: !!session.video }; var screen_constraints = { audio: false, video: { mandatory: { chromeMediaSource: 'screen' }, optional: [] } }; if (session.screen) { _captureUserMedia(screen_constraints, constraints.audio || constraints.video ? function() { _captureUserMedia(constraints, callback); } : callback); } else _captureUserMedia(constraints, callback, session.audio && !session.video); function _captureUserMedia(forcedConstraints, forcedCallback, isRemoveVideoTracks) { var mediaConfig = { onsuccess: function(stream, returnBack) { if (returnBack) return forcedCallback && forcedCallback(stream); if (isRemoveVideoTracks && !moz) { stream = new window.webkitMediaStream(stream.getAudioTracks()); } var mediaElement = getMediaElement(stream, session); mediaElement.muted = true; stream.onended = function() { if (self.onstreamended) self.onstreamended(streamedObject); else if (mediaElement.parentNode) mediaElement.parentNode.removeChild(mediaElement); }; var streamedObject = { stream: stream, streamid: stream.label, mediaElement: mediaElement, blobURL: mediaElement.mozSrcObject || mediaElement.src, type: 'local', userid: self.userid || 'self', extra: self.extra }; var sObject = { stream: stream, userid: self.userid, type: 'local', streamObject: streamedObject, mediaElement: mediaElement }; self.attachStreams.push(stream); self.__attachStreams.push(sObject); self.streams[stream.label] = self._getStream(sObject); self.onstream(streamedObject); if (forcedCallback) forcedCallback(stream); }, onerror: function() { var error; if (session.audio && !session.video) error = 'Microphone access is denied.'; else if (session.screen) { if (location.protocol === 'http:') error = '<https> is mandatory to capture screen.'; else error = 'Multi-capturing of screen is not allowed. Capturing process is denied. Are you enabled flag: "Enable screen capture support in getUserMedia"?'; } else error = 'Webcam access is denied.'; if (!self.onMediaError) throw error; self.onMediaError(error); }, mediaConstraints: self.mediaConstraints || { } }; mediaConfig.constraints = forcedConstraints || constraints; mediaConfig.media = self.media; getUserMedia(mediaConfig); } }
function captureUserMedia(callback, _session) { var session = _session || self.session; if (self.dontAttachStream) return callback(); if (isData(session) || (!self.isInitiator && session.oneway)) { self.attachStreams = []; return callback(); } var constraints = { audio: !!session.audio, video: !!session.video }; var screen_constraints = { audio: false, video: { mandatory: { chromeMediaSource: 'screen' }, optional: [] } }; if (session.screen) { _captureUserMedia(screen_constraints, constraints.audio || constraints.video ? function() { _captureUserMedia(constraints, callback); } : callback); } else _captureUserMedia(constraints, callback, session.audio && !session.video); function _captureUserMedia(forcedConstraints, forcedCallback, isRemoveVideoTracks) { var mediaConfig = { onsuccess: function(stream, returnBack) { if (returnBack) return forcedCallback && forcedCallback(stream); if (isRemoveVideoTracks && !moz) { stream = new window.webkitMediaStream(stream.getAudioTracks()); } var mediaElement = getMediaElement(stream, session); mediaElement.muted = true; stream.onended = function() { if (self.onstreamended) self.onstreamended(streamedObject); else if (mediaElement.parentNode) mediaElement.parentNode.removeChild(mediaElement); }; var streamedObject = { stream: stream, streamid: stream.label, mediaElement: mediaElement, blobURL: mediaElement.mozSrcObject || mediaElement.src, type: 'local', userid: self.userid || 'self', extra: self.extra }; var sObject = { stream: stream, userid: self.userid, type: 'local', streamObject: streamedObject, mediaElement: mediaElement }; self.attachStreams.push(stream); self.__attachStreams.push(sObject); self.streams[stream.label] = self._getStream(sObject); self.onstream(streamedObject); if (forcedCallback) forcedCallback(stream); }, onerror: function() { var error; if (session.audio && !session.video) error = 'Microphone access is denied.'; else if (session.screen) { if (location.protocol === 'http:') error = '<https> is mandatory to capture screen.'; else error = 'Multi-capturing of screen is not allowed. Capturing process is denied. Are you enabled flag: "Enable screen capture support in getUserMedia"?'; } else error = 'Webcam access is denied.'; if (!self.onMediaError) throw error; self.onMediaError(error); }, mediaConstraints: self.mediaConstraints || { } }; mediaConfig.constraints = forcedConstraints || constraints; mediaConfig.media = self.media; getUserMedia(mediaConfig); } }
JavaScript
function voiceActivityDetection(peer) { if (moz) return; peer.getStats(function(stats) { var output = { }; var sr = stats.result(); for (var i = 0; i < sr.length; i++) { var obj = sr[i].remote; if (obj) { var nspk = 0.0; var nmic = 0.0; if (obj.stat('audioInputLevel')) { nmic = obj.stat('audioInputLevel'); } if (nmic > 0.0) { output.mic = Math.floor(Math.max((Math.LOG2E * Math.log(nmic) - 4.0), 0.0)); } if (obj.stat('audioOutputLevel')) { nspk = obj.stat('audioOutputLevel'); } if (nspk > 0.0) { output.speaker = Math.floor(Math.max((Math.LOG2E * Math.log(nspk) - 4.0), 0.0)); } } } log('mic intensity:', output.mic); log('speaker intensity:', output.speaker); log('Type <window.skipRTCMultiConnectionLogs=true> to stop this logger.'); }); if (!window.skipRTCMultiConnectionLogs) setTimeout(function() { voiceActivityDetection(peer); }, 2000); }
function voiceActivityDetection(peer) { if (moz) return; peer.getStats(function(stats) { var output = { }; var sr = stats.result(); for (var i = 0; i < sr.length; i++) { var obj = sr[i].remote; if (obj) { var nspk = 0.0; var nmic = 0.0; if (obj.stat('audioInputLevel')) { nmic = obj.stat('audioInputLevel'); } if (nmic > 0.0) { output.mic = Math.floor(Math.max((Math.LOG2E * Math.log(nmic) - 4.0), 0.0)); } if (obj.stat('audioOutputLevel')) { nspk = obj.stat('audioOutputLevel'); } if (nspk > 0.0) { output.speaker = Math.floor(Math.max((Math.LOG2E * Math.log(nspk) - 4.0), 0.0)); } } } log('mic intensity:', output.mic); log('speaker intensity:', output.speaker); log('Type <window.skipRTCMultiConnectionLogs=true> to stop this logger.'); }); if (!window.skipRTCMultiConnectionLogs) setTimeout(function() { voiceActivityDetection(peer); }, 2000); }
JavaScript
function RecordRTC(mediaStream, config) { config = config || { }; if (!mediaStream) throw 'MediaStream is mandatory.'; if (!config.type) config.type = 'audio'; function startRecording() { console.debug('started recording stream.'); // Media Stream Recording API has not been implemented in chrome yet; // That's why using WebAudio API to record stereo audio in WAV format var Recorder = IsChrome ? window.StereoRecorder : window.MediaStreamRecorder; // video recorder (in WebM format) if (config.type == 'video') Recorder = window.WhammyRecorder; // video recorder (in Gif format) if (config.type == 'gif') Recorder = window.GifRecorder; mediaRecorder = new Recorder(mediaStream); // Merge all data-types except "function" mediaRecorder = mergeProps(mediaRecorder, config); mediaRecorder.record(); } function stopRecording(callback) { console.warn('stopped recording stream.'); mediaRecorder.stop(); if (callback && mediaRecorder) { var url = URL.createObjectURL(mediaRecorder.recordedBlob); callback(url); } } var mediaRecorder; return { startRecording: startRecording, stopRecording: stopRecording, getBlob: function() { if (!mediaRecorder) return console.warn('RecordRTC is idle.'); return mediaRecorder.recordedBlob; }, getDataURL: function(callback) { if (!mediaRecorder) return console.warn('RecordRTC is idle.'); var reader = new FileReader(); reader.readAsDataURL(mediaRecorder.recordedBlob); reader.onload = function(event) { if (callback) callback(event.target.result); }; }, toURL: function() { if (!mediaRecorder) return console.warn('RecordRTC is idle.'); return URL.createObjectURL(mediaRecorder.recordedBlob); }, save: function() { if (!mediaRecorder) return console.warn('RecordRTC is idle.'); console.log('saving recorded stream to disk!'); // bug: should we use "getBlob" instead; to handle aww-snaps! this.getDataURL(function(dataURL) { var hyperlink = document.createElement('a'); hyperlink.href = dataURL; hyperlink.target = '_blank'; hyperlink.download = (Math.round(Math.random() * 9999999999) + 888888888) + '.' + mediaRecorder.recordedBlob.type.split('/')[1]; var evt = new MouseEvent('click', { view: window, bubbles: true, cancelable: true }); hyperlink.dispatchEvent(evt); (window.URL || window.webkitURL).revokeObjectURL(hyperlink.href); }); } }; }
function RecordRTC(mediaStream, config) { config = config || { }; if (!mediaStream) throw 'MediaStream is mandatory.'; if (!config.type) config.type = 'audio'; function startRecording() { console.debug('started recording stream.'); // Media Stream Recording API has not been implemented in chrome yet; // That's why using WebAudio API to record stereo audio in WAV format var Recorder = IsChrome ? window.StereoRecorder : window.MediaStreamRecorder; // video recorder (in WebM format) if (config.type == 'video') Recorder = window.WhammyRecorder; // video recorder (in Gif format) if (config.type == 'gif') Recorder = window.GifRecorder; mediaRecorder = new Recorder(mediaStream); // Merge all data-types except "function" mediaRecorder = mergeProps(mediaRecorder, config); mediaRecorder.record(); } function stopRecording(callback) { console.warn('stopped recording stream.'); mediaRecorder.stop(); if (callback && mediaRecorder) { var url = URL.createObjectURL(mediaRecorder.recordedBlob); callback(url); } } var mediaRecorder; return { startRecording: startRecording, stopRecording: stopRecording, getBlob: function() { if (!mediaRecorder) return console.warn('RecordRTC is idle.'); return mediaRecorder.recordedBlob; }, getDataURL: function(callback) { if (!mediaRecorder) return console.warn('RecordRTC is idle.'); var reader = new FileReader(); reader.readAsDataURL(mediaRecorder.recordedBlob); reader.onload = function(event) { if (callback) callback(event.target.result); }; }, toURL: function() { if (!mediaRecorder) return console.warn('RecordRTC is idle.'); return URL.createObjectURL(mediaRecorder.recordedBlob); }, save: function() { if (!mediaRecorder) return console.warn('RecordRTC is idle.'); console.log('saving recorded stream to disk!'); // bug: should we use "getBlob" instead; to handle aww-snaps! this.getDataURL(function(dataURL) { var hyperlink = document.createElement('a'); hyperlink.href = dataURL; hyperlink.target = '_blank'; hyperlink.download = (Math.round(Math.random() * 9999999999) + 888888888) + '.' + mediaRecorder.recordedBlob.type.split('/')[1]; var evt = new MouseEvent('click', { view: window, bubbles: true, cancelable: true }); hyperlink.dispatchEvent(evt); (window.URL || window.webkitURL).revokeObjectURL(hyperlink.href); }); } }; }
JavaScript
function MediaStreamRecorder(mediaStream) { var self = this; this.record = function() { // http://dxr.mozilla.org/mozilla-central/source/content/media/MediaRecorder.cpp // https://wiki.mozilla.org/Gecko:MediaRecorder mediaRecorder = new MediaRecorder(mediaStream); mediaRecorder.ondataavailable = function(e) { // pull #118 if(self.recordedBlob) self.recordedBlob = new Blob([self.recordedBlob, e.data], { type: 'audio/ogg' }); else self.recordedBlob = new Blob([e.data], { type: 'audio/ogg' }); }; mediaRecorder.start(0); }; this.stop = function() { if (mediaRecorder.state == 'recording') { mediaRecorder.requestData(); mediaRecorder.stop(); } }; // Reference to "MediaRecorder" object var mediaRecorder; }
function MediaStreamRecorder(mediaStream) { var self = this; this.record = function() { // http://dxr.mozilla.org/mozilla-central/source/content/media/MediaRecorder.cpp // https://wiki.mozilla.org/Gecko:MediaRecorder mediaRecorder = new MediaRecorder(mediaStream); mediaRecorder.ondataavailable = function(e) { // pull #118 if(self.recordedBlob) self.recordedBlob = new Blob([self.recordedBlob, e.data], { type: 'audio/ogg' }); else self.recordedBlob = new Blob([e.data], { type: 'audio/ogg' }); }; mediaRecorder.start(0); }; this.stop = function() { if (mediaRecorder.state == 'recording') { mediaRecorder.requestData(); mediaRecorder.stop(); } }; // Reference to "MediaRecorder" object var mediaRecorder; }
JavaScript
function toWebM(frames, outputAsArray){ var info = checkFrames(frames); //max duration by cluster in milliseconds var CLUSTER_MAX_DURATION = 30000; var EBML = [ { "id": 0x1a45dfa3, // EBML "data": [ { "data": 1, "id": 0x4286 // EBMLVersion }, { "data": 1, "id": 0x42f7 // EBMLReadVersion }, { "data": 4, "id": 0x42f2 // EBMLMaxIDLength }, { "data": 8, "id": 0x42f3 // EBMLMaxSizeLength }, { "data": "webm", "id": 0x4282 // DocType }, { "data": 2, "id": 0x4287 // DocTypeVersion }, { "data": 2, "id": 0x4285 // DocTypeReadVersion } ] }, { "id": 0x18538067, // Segment "data": [ { "id": 0x1549a966, // Info "data": [ { "data": 1e6, //do things in millisecs (num of nanosecs for duration scale) "id": 0x2ad7b1 // TimecodeScale }, { "data": "whammy", "id": 0x4d80 // MuxingApp }, { "data": "whammy", "id": 0x5741 // WritingApp }, { "data": doubleToString(info.duration), "id": 0x4489 // Duration } ] }, { "id": 0x1654ae6b, // Tracks "data": [ { "id": 0xae, // TrackEntry "data": [ { "data": 1, "id": 0xd7 // TrackNumber }, { "data": 1, "id": 0x63c5 // TrackUID }, { "data": 0, "id": 0x9c // FlagLacing }, { "data": "und", "id": 0x22b59c // Language }, { "data": "V_VP8", "id": 0x86 // CodecID }, { "data": "VP8", "id": 0x258688 // CodecName }, { "data": 1, "id": 0x83 // TrackType }, { "id": 0xe0, // Video "data": [ { "data": info.width, "id": 0xb0 // PixelWidth }, { "data": info.height, "id": 0xba // PixelHeight } ] } ] } ] }, //cluster insertion point ] } ]; //Generate clusters (max duration) var frameNumber = 0; var clusterTimecode = 0; while(frameNumber < frames.length){ var clusterFrames = []; var clusterDuration = 0; do { clusterFrames.push(frames[frameNumber]); clusterDuration += frames[frameNumber].duration; frameNumber++; }while(frameNumber < frames.length && clusterDuration < CLUSTER_MAX_DURATION); var clusterCounter = 0; var cluster = { "id": 0x1f43b675, // Cluster "data": [ { "data": clusterTimecode, "id": 0xe7 // Timecode } ].concat(clusterFrames.map(function(webp){ var block = makeSimpleBlock({ discardable: 0, frame: webp.data.slice(4), invisible: 0, keyframe: 1, lacing: 0, trackNum: 1, timecode: Math.round(clusterCounter) }); clusterCounter += webp.duration; return { data: block, id: 0xa3 }; })) } //Add cluster to segment EBML[1].data.push(cluster); clusterTimecode += clusterDuration; } return generateEBML(EBML, outputAsArray) }
function toWebM(frames, outputAsArray){ var info = checkFrames(frames); //max duration by cluster in milliseconds var CLUSTER_MAX_DURATION = 30000; var EBML = [ { "id": 0x1a45dfa3, // EBML "data": [ { "data": 1, "id": 0x4286 // EBMLVersion }, { "data": 1, "id": 0x42f7 // EBMLReadVersion }, { "data": 4, "id": 0x42f2 // EBMLMaxIDLength }, { "data": 8, "id": 0x42f3 // EBMLMaxSizeLength }, { "data": "webm", "id": 0x4282 // DocType }, { "data": 2, "id": 0x4287 // DocTypeVersion }, { "data": 2, "id": 0x4285 // DocTypeReadVersion } ] }, { "id": 0x18538067, // Segment "data": [ { "id": 0x1549a966, // Info "data": [ { "data": 1e6, //do things in millisecs (num of nanosecs for duration scale) "id": 0x2ad7b1 // TimecodeScale }, { "data": "whammy", "id": 0x4d80 // MuxingApp }, { "data": "whammy", "id": 0x5741 // WritingApp }, { "data": doubleToString(info.duration), "id": 0x4489 // Duration } ] }, { "id": 0x1654ae6b, // Tracks "data": [ { "id": 0xae, // TrackEntry "data": [ { "data": 1, "id": 0xd7 // TrackNumber }, { "data": 1, "id": 0x63c5 // TrackUID }, { "data": 0, "id": 0x9c // FlagLacing }, { "data": "und", "id": 0x22b59c // Language }, { "data": "V_VP8", "id": 0x86 // CodecID }, { "data": "VP8", "id": 0x258688 // CodecName }, { "data": 1, "id": 0x83 // TrackType }, { "id": 0xe0, // Video "data": [ { "data": info.width, "id": 0xb0 // PixelWidth }, { "data": info.height, "id": 0xba // PixelHeight } ] } ] } ] }, //cluster insertion point ] } ]; //Generate clusters (max duration) var frameNumber = 0; var clusterTimecode = 0; while(frameNumber < frames.length){ var clusterFrames = []; var clusterDuration = 0; do { clusterFrames.push(frames[frameNumber]); clusterDuration += frames[frameNumber].duration; frameNumber++; }while(frameNumber < frames.length && clusterDuration < CLUSTER_MAX_DURATION); var clusterCounter = 0; var cluster = { "id": 0x1f43b675, // Cluster "data": [ { "data": clusterTimecode, "id": 0xe7 // Timecode } ].concat(clusterFrames.map(function(webp){ var block = makeSimpleBlock({ discardable: 0, frame: webp.data.slice(4), invisible: 0, keyframe: 1, lacing: 0, trackNum: 1, timecode: Math.round(clusterCounter) }); clusterCounter += webp.duration; return { data: block, id: 0xa3 }; })) } //Add cluster to segment EBML[1].data.push(cluster); clusterTimecode += clusterDuration; } return generateEBML(EBML, outputAsArray) }
JavaScript
function bitsToBuffer(bits){ var data = []; var pad = (bits.length % 8) ? (new Array(1 + 8 - (bits.length % 8))).join('0') : ''; bits = pad + bits; for(var i = 0; i < bits.length; i+= 8){ data.push(parseInt(bits.substr(i,8),2)) } return new Uint8Array(data); }
function bitsToBuffer(bits){ var data = []; var pad = (bits.length % 8) ? (new Array(1 + 8 - (bits.length % 8))).join('0') : ''; bits = pad + bits; for(var i = 0; i < bits.length; i+= 8){ data.push(parseInt(bits.substr(i,8),2)) } return new Uint8Array(data); }
JavaScript
function makeSimpleBlock(data){ var flags = 0; if (data.keyframe) flags |= 128; if (data.invisible) flags |= 8; if (data.lacing) flags |= (data.lacing << 1); if (data.discardable) flags |= 1; if (data.trackNum > 127) { throw "TrackNumber > 127 not supported"; } var out = [data.trackNum | 0x80, data.timecode >> 8, data.timecode & 0xff, flags].map(function(e){ return String.fromCharCode(e) }).join('') + data.frame; return out; }
function makeSimpleBlock(data){ var flags = 0; if (data.keyframe) flags |= 128; if (data.invisible) flags |= 8; if (data.lacing) flags |= (data.lacing << 1); if (data.discardable) flags |= 1; if (data.trackNum > 127) { throw "TrackNumber > 127 not supported"; } var out = [data.trackNum | 0x80, data.timecode >> 8, data.timecode & 0xff, flags].map(function(e){ return String.fromCharCode(e) }).join('') + data.frame; return out; }