{"size": 5256, "ext": "js", "max_stars_repo_path": "src/api/fetch.js", "max_stars_repo_name": "chaos87/backtube", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/api/fetch.js", "max_issues_repo_name": "chaos87/backtube", "max_issues_repo_issues_event_min_datetime": "2020-12-06T13:18:31.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-08T03:12:25.000Z", "max_forks_repo_path": "src/api/fetch.js", "max_forks_repo_name": "chaos87/backtube", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 23, "max_forks_count": null, "avg_line_length": 34.5789473684, "max_line_length": 133, "alphanum_fraction": 0.5426179604}
import { baseURL, ytURL, bandcampURL } from '../config/urls';
import { pad } from '../services/utils';
import { addMosaicToObject } from '../services/utils';

export const makeYoutubeSearchApiCall = async searchInput => {
  const searchUrl = ytURL + `/search/yt`;
  let response = await fetch(searchUrl, {method: 'POST',
      headers: {
          'Content-Type': 'application/json'
      },
      body: JSON.stringify({"query": searchInput})})
    .then(response => {
      return response.json();
    })
    .catch(error => {
        return error;
    })
    return response;
};

export const makeBandcampSearchApiCall = async searchInput => {
  const searchUrl = bandcampURL + `/bandcamp/search`;
  let response = await fetch(searchUrl, {method: 'POST',
          headers: {
              'Content-Type': 'application/json'
          },
          body: JSON.stringify({"query": searchInput})}
      ).then(res => {
          return res.json();
      }).catch(error => {
          return error
      });

  const uniqueObjects = [...new Map(response.map(item => [item.url, item])).values()]
  const tmpArtistAlbums = await searchBCartistAlbums(bandcampURL, uniqueObjects.filter(x => x.type === "artist").map(x => x.url));
  const artistAlbums = tmpArtistAlbums.flat().filter(x => !x.includes('?action=download'));
  const nearlyAllAlbums = artistAlbums.concat(uniqueObjects.filter(x => x.type === "album").map(x => x.url));
  const trackAlbums = await searchBCtrack4Album(bandcampURL, nearlyAllAlbums.filter(x => x.includes('/track/')));
  const allAlbumsDuplicated = nearlyAllAlbums.filter(x => !x.includes('/track/')).concat(trackAlbums.filter(x => x));
  const allAlbums = [...new Set(allAlbumsDuplicated)];
  const results = await searchBCalbumDetails(bandcampURL, allAlbums);
  return {
          albums: results.filter(x => x).filter(x => x.tracks.length > 0)
      };
};

const searchBCalbumDetails = (bandcampURL, url) => {
  const fetches = [];
  for (let i = 0; i < url.length; i++) {
    fetches.push(
      fetch(bandcampURL + '/bandcamp/songs', {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json'
          },
          body: JSON.stringify({"url": url[i]})
      })
      .then(res => {return res.json(); })
      .then(res => {
          let tracks = res["raw"]["trackinfo"].filter(x => x.file);
          let tracks_updated = tracks.map(function(o) {
                                      o.artist = res["artist"];
                                      o.thumbnail = res["imageUrl"];
                                      o._id = o.track_id;
                                      o.url = url[i].split("/album/")[0] + o.title_link;
                                      return o;
                                    })
          let releaseDate = new Date(Date.parse(res["raw"]["current"]["release_date"]));
          releaseDate = releaseDate.getFullYear() + "-" + pad((releaseDate.getMonth() + 1), 2) + "-" + pad(releaseDate.getDate(), 2);
          const result = {
              "url": res["url"],
              "_id": res["url"],
              "artist": res["artist"],
              "title": res["title"],
              "thumbnail": res["imageUrl"],
              "releaseDate": releaseDate,
              "tracks": tracks_updated,
          }
          return result
      })
      .catch(err => {return console.log(err);})
    );
  }
 return Promise.all(fetches)
}

const searchBCtrack4Album = (bandcampURL, url) => {
  const fetches = [];
  for (let i = 0; i < url.length; i++) {
    fetches.push(
      fetch(bandcampURL + '/bandcamp/songs', {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json'
          },
          body: JSON.stringify({"url": url[i]})
      })
      .then(res => {return res.json(); })
      .then(res => {
          return res["raw"]["packages"] ? res["raw"]["packages"][0]["album_url"] : null
      })
      .catch(err => {return console.log(err);})
    );
  }
 return Promise.all(fetches)
}

const searchBCartistAlbums = async (bandcampURL, artists) => {
  const fetches = [];
  for (let i = 0; i < artists.length; i++) {
    fetches.push(
      fetch(bandcampURL + '/bandcamp/albums', {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json'
          },
          body: JSON.stringify({"url": artists[i]})
      })
      .then(res => {return res.json(); })
      .catch(err => {return console.log(err);})
    );
  }
 return Promise.all(fetches)
}

export const searchPlaylistsApi = async (userInfo) => {
    const accessToken = userInfo.accessToken;
    const query = userInfo.searchString
    const postUrl = baseURL + `/api/playlist/search`;
    let playlists = await fetch(postUrl, { method: 'POST',
        headers: {
          'accessToken': accessToken,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({"searchString": query})

    })
    .then(res => {
        return res.json();
    })
    .then(res => {
        // Add field for covers mosaic
        if (res) {
            return res.map(el => addMosaicToObject(el))
        } else { return res; }
    })
    .catch(err => {
        return err
    })
    return playlists;
}
