diff --git a/nix/shell.nix b/nix/shell.nix index 1072b319..d3637ad1 100644 --- a/nix/shell.nix +++ b/nix/shell.nix @@ -9,27 +9,6 @@ rustc = rust; }; - # Trying to fix an issue with `watchexec` on MacOS - # https://github.com/h4llow3En/mac-notification-sys/issues/28 - # Nix uses old Apple SDKs? Not sure, but definitely a Nix issue. - watchexec = rustPlatform.buildRustPackage rec { - pname = "watchexec"; - version = "1.20.4"; - - cargoSha256 = "sha256-YM+Zm3wFp3Lsx5LmyjGwZywV/SZjriL6JMDO1l0tNf4="; - - src = fetchFromGitHub { - owner = pname; - repo = pname; - rev = "cli-v${version}"; - sha256 = "sha256-se3iqz+qjwf71wvHQhCWYryEdUc+kY0Q0ZTg4i1ayNI="; - }; - - nativeBuildInputs = lib.optionals - stdenv.isDarwin - (with darwin.apple_sdk_11_0.frameworks; [ Cocoa Foundation ]); - }; - # Wraps # ----- # Inspired by https://www.tweag.io/blog/2022-06-02-haskell-stack-nix-shell/ diff --git a/src/Applications/Brain/Sources/Processing/Steps.elm b/src/Applications/Brain/Sources/Processing/Steps.elm index 9fb9d94f..71196fa2 100644 --- a/src/Applications/Brain/Sources/Processing/Steps.elm +++ b/src/Applications/Brain/Sources/Processing/Steps.elm @@ -80,7 +80,7 @@ takeFirstStep origin currentTime source = takePrepareStep : Context -> String -> Time.Posix -> Cmd Brain.Msg takePrepareStep context response currentTime = context - |> handlePreparationResponse response + |> handlePreparationResponse response currentTime |> intoPreparationCommands currentTime @@ -149,13 +149,14 @@ prepare context currentTime = makeTree context currentTime -handlePreparationResponse : String -> Context -> Context -handlePreparationResponse response context = +handlePreparationResponse : String -> Time.Posix -> Context -> Context +handlePreparationResponse response currentTime context = let answer = Services.parsePreparationResponse context.source.service response + currentTime context.source.data context.preparationMarker diff --git a/src/Javascript/Brain/artwork.js b/src/Javascript/Brain/artwork.js index de636dab..f5ca6116 100644 --- a/src/Javascript/Brain/artwork.js +++ b/src/Javascript/Brain/artwork.js @@ -10,7 +10,7 @@ import * as processing from "../processing" const REJECT = () => Promise.reject("No artwork found") -export function find(prep) { +export function find(prep, app) { return findUsingTags(prep) .then(a => a ? a : findUsingMusicBrainz(prep)) .then(a => a ? a : findUsingLastFm(prep)) @@ -28,10 +28,11 @@ function decodeCacheKey(cacheKey) { // 1. TAGS -function findUsingTags(prep) { +function findUsingTags(prep, app) { return Promise.all( - [ transformUrl(prep.trackHeadUrl) - , transformUrl(prep.trackGetUrl) + [ + transformUrl(prep.trackHeadUrl, app), + transformUrl(prep.trackGetUrl, app) ] ).then(([ headUrl, getUrl ]) => processing.getTags( @@ -55,8 +56,8 @@ function findUsingTags(prep) { function findUsingMusicBrainz(prep) { const parts = decodeCacheKey(prep.cacheKey).split(" --- ") - const artist = parts[0] - const album = parts[1] || parts[0] + const artist = parts[ 0 ] + const album = parts[ 1 ] || parts[ 0 ] const query = `release:"${album}"` + (prep.variousArtists === "t" ? `` : ` AND artist:"${artist}"`) const encodedQuery = encodeURIComponent(query) @@ -68,7 +69,7 @@ function findUsingMusicBrainz(prep) { function musicBrainzCover(remainingReleases) { - const release = remainingReleases[0] + const release = remainingReleases[ 0 ] if (!release) return null return fetch( @@ -99,12 +100,12 @@ function findUsingLastFm(prep) { function lastFmCover(remainingMatches) { - const album = remainingMatches[0] - const url = album ? album.image[album.image.length - 1]["#text"] : null + const album = remainingMatches[ 0 ] + const url = album ? album.image[ album.image.length - 1 ][ "#text" ] : null return url && url !== "" ? fetch(url) - .then(r => r.blob()) - .catch(_ => lastFmCover(remainingMatches.slice(1))) + .then(r => r.blob()) + .catch(_ => lastFmCover(remainingMatches.slice(1))) : album && lastFmCover(remainingMatches.slice(1)) } diff --git a/src/Javascript/Brain/index.js b/src/Javascript/Brain/index.js index ad58ef47..557e1566 100644 --- a/src/Javascript/Brain/index.js +++ b/src/Javascript/Brain/index.js @@ -26,8 +26,8 @@ const flags = location .substr(1) .split("&") .reduce((acc, flag) => { - const [k, v] = flag.split("=") - return { ...acc, [k]: v } + const [ k, v ] = flag.split("=") + return { ...acc, [ k ]: v } }, {}) @@ -56,9 +56,11 @@ self.onmessage = event => { } -function handleAction(action, data) { switch (action) { - case "DOWNLOAD_ARTWORK": return downloadArtwork(data) -}} +function handleAction(action, data) { + switch (action) { + case "DOWNLOAD_ARTWORK": return downloadArtwork(data) + } +} @@ -67,7 +69,7 @@ function handleAction(action, data) { switch (action) { app.ports.removeCache.subscribe(event => { removeCache(event.tag) - .catch( reportError(app, event) ) + .catch(reportError(app, event)) }) @@ -77,8 +79,8 @@ app.ports.requestCache.subscribe(event => { : event.tag fromCache(key) - .then( sendData(app, event) ) - .catch( reportError(app, event) ) + .then(sendData(app, event)) + .catch(reportError(app, event)) }) @@ -90,10 +92,10 @@ app.ports.toCache.subscribe(event => { toCache(key, event.data.data || event.data) .then( event.tag === "AUTH_ANONYMOUS" - ? storageCallback(app, event) - : identity + ? storageCallback(app, event) + : identity ) - .catch( reportError(app, event) ) + .catch(reportError(app, event)) }) @@ -105,7 +107,7 @@ let artworkQueue = [] function downloadArtwork(list) { - const exe = !artworkQueue[0] + const exe = !artworkQueue[ 0 ] artworkQueue = artworkQueue.concat(list) if (exe) shiftArtworkQueue() } @@ -127,7 +129,7 @@ function shiftArtworkQueue() { app.ports.provideArtworkTrackUrls.subscribe(prep => { artwork - .find(prep) + .find(prep, app) .then(blob => { const url = URL.createObjectURL(blob) @@ -139,10 +141,17 @@ app.ports.provideArtworkTrackUrls.subscribe(prep => { return toCache(`coverCache.${prep.cacheKey}`, blob) }) - .catch(_ => { - // Indicate that we've tried to find artwork, - // so that we don't try to find it each time we launch the app. - return toCache(`coverCache.${prep.cacheKey}`, "TRIED") + .catch(err => { + if (err === "No artwork found") { + // Indicate that we've tried to find artwork, + // so that we don't try to find it each time we launch the app. + return toCache(`coverCache.${prep.cacheKey}`, "TRIED") + + } else { + // Something went wrong + reportError(app, { tag: "REPORT_ERROR" })(err) + + } }) .finally(shiftArtworkQueue) }) @@ -159,7 +168,7 @@ app.ports.removeTracksFromCache.subscribe(trackIds => { ).catch( _ => reportError - ({ tag: "REMOVE_TRACKS_FROM_CACHE" }) + (app, { tag: "REMOVE_TRACKS_FROM_CACHE" }) ("Failed to remove tracks from cache") ) @@ -168,10 +177,11 @@ app.ports.removeTracksFromCache.subscribe(trackIds => { app.ports.storeTracksInCache.subscribe(list => { list.reduce( - (acc, item) => { return acc - .then(_ => fetch(item.url)) - .then(r => r.blob()) - .then(b => db.setInIndex({ key: item.trackId, data: b, store: db.storeNames.tracks })) + (acc, item) => { + return acc + .then(_ => fetch(item.url)) + .then(r => r.blob()) + .then(b => db.setInIndex({ key: item.trackId, data: b, store: db.storeNames.tracks })) }, Promise.resolve() @@ -245,14 +255,14 @@ search.onmessage = event => { // ---- app.ports.requestTags.subscribe(context => { - processing.processContext(context).then(newContext => { + processing.processContext(context, app).then(newContext => { app.ports.receiveTags.send(newContext) }) }) app.ports.syncTags.subscribe(context => { - processing.processContext(context).then(newContext => { + processing.processContext(context, app).then(newContext => { app.ports.replaceTags.send(newContext) }) }) diff --git a/src/Javascript/audio-engine.js b/src/Javascript/audio-engine.js index 92dbece7..0d79dd06 100644 --- a/src/Javascript/audio-engine.js +++ b/src/Javascript/audio-engine.js @@ -15,7 +15,7 @@ import { transformUrl } from "./urls" const IS_SAFARI = !!navigator.platform.match(/iPhone|iPod|iPad/) || - navigator.vendor === "Apple Computer, Inc." + navigator.vendor === "Apple Computer, Inc." @@ -38,9 +38,9 @@ const audioElementsContainer = (() => { let c let styles = [ "height: 0" - , "width: 0" - , "visibility: hidden" - , "pointer-events: none" + , "width: 0" + , "visibility: hidden" + , "pointer-events: none" ] c = document.createElement("div") @@ -117,7 +117,7 @@ export function insertTrack(orchestrion, queueItem, maybeArtwork) { // initial promise const initialPromise = queueItem.isCached ? db.getFromIndex({ key: queueItem.trackId, store: db.storeNames.tracks }).then(blobUrl) - : transformUrl(queueItem.url) + : transformUrl(queueItem.url, orchestrion.app) // find or create audio node let audioNode @@ -215,7 +215,7 @@ export function preloadAudioElement(orchestrion, queueItem) { ) // audio element remains valid for 2 hours - transformUrl(queueItem.url).then(url => { + transformUrl(queueItem.url, orchestrion.app).then(url => { const queueItemWithTransformedUrl = Object.assign({}, queueItem, { url: url }) @@ -285,22 +285,22 @@ function audioErrorEvent(event) { } - function showNetworkErrorNotification() { - if (showedNoNetworkError) return - showedNoNetworkError = true - this.app.ports.showErrorNotification.send( - navigator.onLine - ? "I can't play this track because of a network error. I'll try to reconnect." - : "I can't play this track because we're offline. I'll try to reconnect." - ) - } +function showNetworkErrorNotification() { + if (showedNoNetworkError) return + showedNoNetworkError = true + this.app.ports.showErrorNotification.send( + navigator.onLine + ? "I can't play this track because of a network error. I'll try to reconnect." + : "I can't play this track because we're offline. I'll try to reconnect." + ) +} - function showUnsupportedSrcErrorNotification() { - this.app.ports.showErrorNotification.send( - "__I can't play this track because your browser didn't recognize it.__ Try checking your developer console for a warning to find out why." - ) - } +function showUnsupportedSrcErrorNotification() { + this.app.ports.showErrorNotification.send( + "__I can't play this track because your browser didn't recognize it.__ Try checking your developer console for a warning to find out why." + ) +} function audioStalledEvent(event, notifyAppImmediately) { @@ -426,8 +426,8 @@ function isActiveAudioElement(orchestrion, node) { !node || node.getAttribute("data-preload") === "t" ) - ? false - : orchestrion.activeQueueItem.trackId === audioElementTrackId(node) + ? false + : orchestrion.activeQueueItem.trackId === audioElementTrackId(node) } @@ -492,10 +492,10 @@ export function setMediaSessionMetadata(queueItem, maybeArtwork) { let artwork = [] if (maybeArtwork && typeof maybeArtwork !== "string") { - artwork = [{ + artwork = [ { src: URL.createObjectURL(maybeArtwork), type: maybeArtwork.type - }] + } ] } navigator.mediaSession.metadata = new MediaMetadata({ diff --git a/src/Javascript/index.js b/src/Javascript/index.js index 28d5239a..0cf24be9 100644 --- a/src/Javascript/index.js +++ b/src/Javascript/index.js @@ -1,5 +1,4 @@ // -// Elm loader // | (• ◡•)| (❍ᴥ❍ʋ) // // The bit where we launch the Elm app, @@ -17,6 +16,7 @@ import * as audioEngine from "./audio-engine" import * as db from "./indexed-db" import { version } from '../../package.json' import { WEBNATIVE_STAGING_ENV, WEBNATIVE_STAGING_MODE, debounce, fileExtension } from "./common" +import { transformUrl } from "./urls" @@ -35,13 +35,13 @@ if (location.hostname.endsWith("diffuse.sh") && location.protocol === "http:") { location.href = location.href.replace("http://", "https://") failure("Just a moment, redirecting to HTTPS.") -// Not a secure context + // Not a secure context } else if (!self.isSecureContext) { failure(` This app only works on a secure context, HTTPS & localhost, and modern browsers. `) -// Service worker + // Service worker } else if ("serviceWorker" in navigator) { window.addEventListener("load", () => { navigator.serviceWorker @@ -193,10 +193,12 @@ wire.brain = () => { } -function handleAction(action, data, _ports) { switch (action) { - case "DOWNLOAD_TRACKS": return downloadTracks(data) - case "FINISHED_DOWNLOADING_ARTWORK": return finishedDownloadingArtwork() -}} +function handleAction(action, data, _ports) { + switch (action) { + case "DOWNLOAD_TRACKS": return downloadTracks(data) + case "FINISHED_DOWNLOADING_ARTWORK": return finishedDownloadingArtwork() + } +} @@ -257,10 +259,10 @@ function activeQueueItemChanged(item) { // 🎵 if (item) { const coverPrep = { - cacheKey: btoa(unescape(encodeURIComponent(item.trackTags.artist + " --- " + item.trackTags.album))), - trackFilename: item.trackPath.split("/").reverse()[0], - trackPath: item.trackPath, - trackSourceId: item.sourceId, + cacheKey: btoa(unescape(encodeURIComponent(item.trackTags.artist + " --- " + item.trackTags.album))), + trackFilename: item.trackPath.split("/").reverse()[ 0 ], + trackPath: item.trackPath, + trackSourceId: item.sourceId, variousArtists: "f" } @@ -285,7 +287,7 @@ function activeQueueItemChanged(item) { }) }) - // ✋ + // ✋ } else { app.ports.setAudioIsPlaying.send(false) app.ports.setAudioPosition.send(0) @@ -388,9 +390,9 @@ function averageColorOfImage(img) { const color = { r: 0, g: 0, b: 0 } for (let i = 0, l = imageData.data.length; i < l; i += 4) { - color.r += imageData.data[i] - color.g += imageData.data[i + 1] - color.b += imageData.data[i + 2] + color.r += imageData.data[ i ] + color.g += imageData.data[ i + 1 ] + color.b += imageData.data[ i + 2 ] } color.r = Math.floor(color.r / (imageData.data.length / 4)) @@ -432,12 +434,25 @@ wire.broadcastChannel = () => { // --------- wire.clipboard = () => { - app.ports.copyToClipboard.subscribe(copyToClipboard) + app.ports.copyToClipboard.subscribe(text => { + // TODO: Find a better solution for this + const adjustedText = (() => { + if (text.startsWith("dropbox://")) { + return transformUrl(text) + } else if (text.startsWith("google://")) { + return transformUrl(text) + } else { + return text + + } + })() + + copyToClipboard(copyToClipboard) + }) } function copyToClipboard(text) { - // Insert a textarea element const el = document.createElement("textarea") @@ -465,7 +480,6 @@ function copyToClipboard(text) { document.getSelection().removeAllRanges() document.getSelection().addRange(selected) } - } @@ -491,13 +505,13 @@ function gotCachedCover({ key, url }) { const item = orchestrion.activeQueueItem if (item && orchestrion.coverPrep && key === orchestrion.coverPrep.key && url) { - let artwork = [{ src: url }] + let artwork = [ { src: url } ] if (typeof url !== "string") { - artwork = [{ + artwork = [ { src: URL.createObjectURL(url), type: url.type - }] + } ] } navigator.mediaSession.metadata = new MediaMetadata({ @@ -524,10 +538,10 @@ function loadAlbumCoversFromDom({ coverView, list } = {}) { if (!nodes.length) return; const coverPrepList = nodes.map(node => ({ - cacheKey: node.getAttribute("data-key"), - trackFilename: node.getAttribute("data-filename"), - trackPath: node.getAttribute("data-path"), - trackSourceId: node.getAttribute("data-source-id"), + cacheKey: node.getAttribute("data-key"), + trackFilename: node.getAttribute("data-filename"), + trackPath: node.getAttribute("data-path"), + trackSourceId: node.getAttribute("data-source-id"), variousArtists: node.getAttribute("data-various-artists") })) @@ -566,7 +580,7 @@ function cachedCovers(keys) { const cacheKey = key.slice(11) if (blob && typeof blob !== "string") { - cache[cacheKey] = URL.createObjectURL(blob) + cache[ cacheKey ] = URL.createObjectURL(blob) } return cache @@ -618,16 +632,17 @@ function downloadTracks(group) { const folder = zip.folder("Diffuse - " + group.name) return group.tracks.reduce( - (acc, track) => { return acc - .then(_ => fetch(track.url)) - .then(r => { - const mimeType = r.headers.get("content-type") - const fileExt = fileExtension(mimeType) || "unknown" - - return r.blob().then( - b => folder.file(track.filename + "." + fileExt, b) - ) - }) + (acc, track) => { + return acc + .then(_ => fetch(track.url)) + .then(r => { + const mimeType = r.headers.get("content-type") + const fileExt = fileExtension(mimeType) || "unknown" + + return r.blob().then( + b => folder.file(track.filename + "." + fileExt, b) + ) + }) }, Promise.resolve() @@ -863,9 +878,9 @@ function touchPointerEvent(eventType, touchEvent, touch) { // Simulate `pointerenter` and `pointerleave` event for non-touch devices if (!self.PointerEvent) { document.addEventListener("mouseover", event => { - const section = document.body.querySelector("section") - const isDragging = section && section.classList.contains("dragging-something") - const node = isDragging && document.elementFromPoint(event.clientX, event.clientY) + const section = document.body.querySelector("section") + const isDragging = section && section.classList.contains("dragging-something") + const node = isDragging && document.elementFromPoint(event.clientX, event.clientY) if (node && node != enteredElement) { enteredElement && enteredElement.dispatchEvent(mousePointerEvent("pointerleave", event)) @@ -878,10 +893,10 @@ if (!self.PointerEvent) { // Simulate `pointerenter` and `pointerleave` event for touch devices document.body.addEventListener("touchmove", event => { - const section = document.body.querySelector("section") - const isDragging = section && section.classList.contains("dragging-something") + const section = document.body.querySelector("section") + const isDragging = section && section.classList.contains("dragging-something") - let touch = event.touches[0] + let touch = event.touches[ 0 ] let node if (isDragging && touch) { diff --git a/src/Javascript/processing.js b/src/Javascript/processing.js index 9edf26ec..ee74e834 100644 --- a/src/Javascript/processing.js +++ b/src/Javascript/processing.js @@ -15,21 +15,21 @@ import { transformUrl } from "./urls" // Contexts // -------- -export function processContext(context) { +export function processContext(context, app) { const initialPromise = Promise.resolve([]) return context.urlsForTags.reduce((accumulator, urls, idx) => { return accumulator.then(col => { const filename = context - .receivedFilePaths[idx] + .receivedFilePaths[ idx ] .split("/") - .reverse()[0] + .reverse()[ 0 ] return Promise.all([ - transformUrl(urls.headUrl), - transformUrl(urls.getUrl) + transformUrl(urls.headUrl, app), + transformUrl(urls.getUrl, app) - ]).then(([headUrl, getUrl]) => { + ]).then(([ headUrl, getUrl ]) => { return getTags(headUrl, getUrl, filename, { skipCovers: true }) }).then(r => { @@ -63,7 +63,7 @@ const parserConfiguration = Object.assign( export function getTags(headUrl, getUrl, filename, options) { const fileExtMatch = filename.match(/\.(\w+)$/) - const fileExt = fileExtMatch && fileExtMatch[1] + const fileExt = fileExtMatch && fileExtMatch[ 1 ] const overrideContentType = ( getUrl.includes("googleapis.com") || @@ -109,9 +109,9 @@ function pickTags(filename, result) { album: tags.album && tags.album.length ? tags.album : "Unknown", artist: artist || "Unknown", title: title ? title : (artist ? "Unknown" : filename.replace(/\.\w+$/, "")), - genre: (tags.genre && tags.genre[0]) || null, + genre: (tags.genre && tags.genre[ 0 ]) || null, year: tags.year || null, - picture: tags.picture ? tags.picture[0] : null + picture: tags.picture ? tags.picture[ 0 ] : null } } diff --git a/src/Javascript/urls.js b/src/Javascript/urls.js index 1fc54cc3..50aa9c3a 100644 --- a/src/Javascript/urls.js +++ b/src/Javascript/urls.js @@ -5,21 +5,27 @@ // Some URLs are special you know. -export function transformUrl(url) { +const EXPIRED_ACCESS_TOKENS = { + GOOGLE: {} +} + + +export async function transformUrl(url, app) { const parts = url.split("://") - switch (parts[0]) { + switch (parts[ 0 ]) { case "dropbox": { - const dropboxBits = parts[1].split("@") - const accessToken = dropboxBits[0] - const filePath = dropboxBits[1] + const dropboxBits = parts[ 1 ].split("@") + const accessToken = dropboxBits[ 0 ] + const filePath = dropboxBits[ 1 ] return fetch( "https://api.dropboxapi.com/2/files/get_temporary_link", - { method: "POST" - , body: JSON.stringify({ path: filePath }) - , headers: new Headers({ + { + method: "POST" + , body: JSON.stringify({ path: filePath }) + , headers: new Headers({ "Authorization": "Bearer " + accessToken, "Content-Type": "application/json" }) @@ -31,8 +37,73 @@ export function transformUrl(url) { ) } + case "google": { + let finalAccessToken + + const googleBits = parts[ 1 ].split("@") + const [ accessToken, expiresAtString, refreshToken, clientId, clientSecret ] = googleBits[ 0 ].split(":") + const fileId = googleBits[ 1 ] + + // Unix timestamp in milliseconds + const in15minutes = Date.now() + 15 * 60 * 1000 + const expiresAt = parseInt(expiresAtString, 10) + const isAlmostExpired = expiresAt <= in15minutes + + if (EXPIRED_ACCESS_TOKENS.GOOGLE[ accessToken ]) { + const replacement = EXPIRED_ACCESS_TOKENS.GOOGLE[ accessToken ] + + if (replacement.newExpiresAt <= in15minutes) { + finalAccessToken = await refreshGoogleAccessToken({ + clientId, clientSecret, refreshToken, oldToken: accessToken + }) + } else { + finalAccessToken = replacement.newToken + } + + } else if (isAlmostExpired) { + finalAccessToken = await refreshGoogleAccessToken({ + clientId, clientSecret, refreshToken, oldToken: accessToken + }) + + } else { + finalAccessToken = accessToken + + } + + return Promise.resolve( + `https://www.googleapis.com/drive/v3/files/${encodeURIComponent(fileId)}?alt=media&bearer_token=${encodeURIComponent(finalAccessToken)}` + ) + } + default: return Promise.resolve(url) } } + + + +// GOOGLE + + +async function refreshGoogleAccessToken({ clientId, clientSecret, oldToken, refreshToken }) { + console.log("🔐 Refreshing Google Drive access token") + + const url = new URL("https://www.googleapis.com/oauth2/v4/token") + + url.searchParams.set("client_id", clientId) + url.searchParams.set("client_secret", clientSecret) + url.searchParams.set("refresh_token", refreshToken) + url.searchParams.set("grant_type", "refresh_token") + + const serverResponse = await fetch(url, { method: "POST" }).then(r => r.json()) + + EXPIRED_ACCESS_TOKENS.GOOGLE[ oldToken ] = { + oldToken, + newToken: serverResponse.access_token, + newExpiresAt: Date.now() + (serverResponse.expires_in * 1000), + refreshToken + } + + return serverResponse.access_token +} diff --git a/src/Library/Sources/Services.elm b/src/Library/Sources/Services.elm index c36b361a..dc2213ae 100644 --- a/src/Library/Sources/Services.elm +++ b/src/Library/Sources/Services.elm @@ -139,7 +139,7 @@ parseErrorResponse service = WebDav.parseErrorResponse -parsePreparationResponse : Service -> String -> SourceData -> Marker -> PrepationAnswer Marker +parsePreparationResponse : Service -> String -> Time.Posix -> SourceData -> Marker -> PrepationAnswer Marker parsePreparationResponse service = case service of AmazonS3 -> diff --git a/src/Library/Sources/Services/AmazonS3.elm b/src/Library/Sources/Services/AmazonS3.elm index a3c74d95..05416d6c 100644 --- a/src/Library/Sources/Services/AmazonS3.elm +++ b/src/Library/Sources/Services/AmazonS3.elm @@ -146,7 +146,7 @@ makeTree srcData marker currentTime resultMsg = {-| Re-export parser functions. -} -parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker +parsePreparationResponse : String -> Time.Posix -> SourceData -> Marker -> PrepationAnswer Marker parsePreparationResponse = noPrep diff --git a/src/Library/Sources/Services/AzureBlob.elm b/src/Library/Sources/Services/AzureBlob.elm index 1da75d20..8e59ab3c 100644 --- a/src/Library/Sources/Services/AzureBlob.elm +++ b/src/Library/Sources/Services/AzureBlob.elm @@ -124,7 +124,7 @@ makeTree srcData marker currentTime resultMsg = {-| Re-export parser functions. -} -parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker +parsePreparationResponse : String -> Time.Posix -> SourceData -> Marker -> PrepationAnswer Marker parsePreparationResponse = noPrep diff --git a/src/Library/Sources/Services/AzureFile.elm b/src/Library/Sources/Services/AzureFile.elm index 56a87dca..37b7a2e4 100644 --- a/src/Library/Sources/Services/AzureFile.elm +++ b/src/Library/Sources/Services/AzureFile.elm @@ -128,7 +128,7 @@ makeTree srcData marker currentTime resultMsg = {-| Re-export parser functions. -} -parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker +parsePreparationResponse : String -> Time.Posix -> SourceData -> Marker -> PrepationAnswer Marker parsePreparationResponse = noPrep diff --git a/src/Library/Sources/Services/Common.elm b/src/Library/Sources/Services/Common.elm index a8487a51..286e3e47 100644 --- a/src/Library/Sources/Services/Common.elm +++ b/src/Library/Sources/Services/Common.elm @@ -3,6 +3,7 @@ module Sources.Services.Common exposing (cleanPath, noPrep) import Sources exposing (..) import Sources.Processing exposing (..) import String.Ext as String +import Time @@ -43,6 +44,6 @@ cleanPath dirtyPath = -- PARSING -noPrep : String -> SourceData -> Marker -> PrepationAnswer Marker -noPrep _ srcData _ = +noPrep : String -> Time.Posix -> SourceData -> Marker -> PrepationAnswer Marker +noPrep _ _ srcData _ = { sourceData = srcData, marker = TheEnd } diff --git a/src/Library/Sources/Services/Dropbox.elm b/src/Library/Sources/Services/Dropbox.elm index a130e066..0b98b58c 100644 --- a/src/Library/Sources/Services/Dropbox.elm +++ b/src/Library/Sources/Services/Dropbox.elm @@ -187,7 +187,7 @@ getProperDirectoryPath srcData = {-| Re-export parser functions. -} -parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker +parsePreparationResponse : String -> Time.Posix -> SourceData -> Marker -> PrepationAnswer Marker parsePreparationResponse = noPrep diff --git a/src/Library/Sources/Services/Google.elm b/src/Library/Sources/Services/Google.elm index 78056c00..6773a93e 100644 --- a/src/Library/Sources/Services/Google.elm +++ b/src/Library/Sources/Services/Google.elm @@ -250,7 +250,7 @@ makeTree srcData marker _ resultMsg = {-| Re-export parser functions. -} -parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker +parsePreparationResponse : String -> Time.Posix -> SourceData -> Marker -> PrepationAnswer Marker parsePreparationResponse = Parser.parsePreparationResponse @@ -289,7 +289,7 @@ We need this to play the track. -} makeTrackUrl : Time.Posix -> SourceData -> HttpMethod -> String -> String -makeTrackUrl _ srcData _ path = +makeTrackUrl currentTime srcData _ path = let file = String.Path.file path @@ -300,12 +300,23 @@ makeTrackUrl _ srcData _ path = |> List.head |> Maybe.withDefault file - accessToken = - Dict.fetch "accessToken" "" srcData + now = + Time.posixToMillis currentTime + + expiresAt = + Dict.fetch "expiresAt" (String.fromInt now) srcData in String.concat - [ "https://www.googleapis.com/drive/v3/files/" - , Url.percentEncode fileId - , "?alt=media&bearer_token=" - , Url.percentEncode accessToken + [ "google://" + , Dict.fetch "accessToken" "" srcData + , ":" + , expiresAt + , ":" + , Dict.fetch "refreshToken" "" srcData + , ":" + , Dict.fetch "clientId" "" srcData + , ":" + , Dict.fetch "clientSecret" "" srcData + , "@" + , fileId ] diff --git a/src/Library/Sources/Services/Google/Parser.elm b/src/Library/Sources/Services/Google/Parser.elm index d2f0def6..ed2ad27a 100755 --- a/src/Library/Sources/Services/Google/Parser.elm +++ b/src/Library/Sources/Services/Google/Parser.elm @@ -9,20 +9,33 @@ import Sources.Pick import Sources.Processing exposing (Marker(..), PrepationAnswer, TreeAnswer) import Sources.Services.Google.Marker as Marker import String.Path +import Time -- PREPARATION -parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker -parsePreparationResponse response srcData _ = +parsePreparationResponse : String -> Time.Posix -> SourceData -> Marker -> PrepationAnswer Marker +parsePreparationResponse response currentTimePosix srcData _ = let newAccessToken = response |> decodeString (field "access_token" string) |> Result.withDefault "" + currentTime = + -- Current time in milliseconds + Time.posixToMillis currentTimePosix + + expiresAt = + -- Unix timestamp in milliseconds + response + |> decodeString (field "expires_in" int) + -- time in seconds + |> Result.withDefault 2500 + |> (\s -> currentTime + s * 1000) + maybeRefreshToken = response |> decodeString (maybe <| field "refresh_token" string) @@ -39,6 +52,7 @@ parsePreparationResponse response srcData _ = in srcData |> Dict.insert "accessToken" newAccessToken + |> Dict.insert "expiresAt" (String.fromInt expiresAt) |> refreshTokenUpdater |> Dict.remove "authCode" |> (\s -> { sourceData = s, marker = TheEnd }) diff --git a/src/Library/Sources/Services/Ipfs.elm b/src/Library/Sources/Services/Ipfs.elm index 8d7a3e0f..aa28d076 100644 --- a/src/Library/Sources/Services/Ipfs.elm +++ b/src/Library/Sources/Services/Ipfs.elm @@ -209,7 +209,7 @@ ipnsResolver response = {-| Re-export parser functions. -} -parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker +parsePreparationResponse : String -> Time.Posix -> SourceData -> Marker -> PrepationAnswer Marker parsePreparationResponse = Parser.parseDnsLookup diff --git a/src/Library/Sources/Services/Ipfs/Parser.elm b/src/Library/Sources/Services/Ipfs/Parser.elm index 29975186..8175f757 100755 --- a/src/Library/Sources/Services/Ipfs/Parser.elm +++ b/src/Library/Sources/Services/Ipfs/Parser.elm @@ -7,14 +7,15 @@ import Sources.Pick exposing (isMusicFile) import Sources.Processing exposing (Marker(..), PrepationAnswer, TreeAnswer) import Sources.Services.Ipfs.Marker as Marker import String.Ext as String +import Time -- PREPARATION -parseDnsLookup : String -> SourceData -> Marker -> PrepationAnswer Marker -parseDnsLookup response srcData _ = +parseDnsLookup : String -> Time.Posix -> SourceData -> Marker -> PrepationAnswer Marker +parseDnsLookup response _ srcData _ = case decodeString dnsResultDecoder response of Ok path -> srcData diff --git a/src/Library/Sources/Services/WebDav.elm b/src/Library/Sources/Services/WebDav.elm index 85003d97..045c8f4b 100644 --- a/src/Library/Sources/Services/WebDav.elm +++ b/src/Library/Sources/Services/WebDav.elm @@ -130,7 +130,7 @@ makeTree srcData marker _ resultMsg = {-| Re-export parser functions. -} -parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker +parsePreparationResponse : String -> Time.Posix -> SourceData -> Marker -> PrepationAnswer Marker parsePreparationResponse = noPrep