Adding YT

This commit is contained in:
Jyotirmoy Bandyopadhayaya 2022-02-03 23:16:51 +05:30
commit 1c0928c405
26 changed files with 8271 additions and 0 deletions

9
.babelrc Normal file
View File

@ -0,0 +1,9 @@
{
"presets": [
"@babel/preset-env"
],
"plugins": [
"@babel/plugin-transform-runtime",
"@babel/plugin-proposal-export-default-from"
]
}

20
.editorconfig Normal file
View File

@ -0,0 +1,20 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# Change these settings to your own preference
indent_style = space
indent_size = 2
# We recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false

1
.env.example Normal file
View File

@ -0,0 +1 @@
MASTER_KEY=masterKey

10
.eslintrc Normal file
View File

@ -0,0 +1,10 @@
{
"parser": "babel-eslint",
"extends": [
"standard"
],
"env": {
"jest": true,
"jasmine": true
}
}

13
.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
.DS_Store
node_modules
public
.tmp
.idea
.log
dist
docs
.env
npm-debug.log
.nyc_output
coverage
cassettes

18
.travis.yml Normal file
View File

@ -0,0 +1,18 @@
language: node_js
node_js:
- v4
- v5
- v6
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- gcc-4.8
- g++-4.8
script:
- npm test -- -i --coverage
env:
global:
- CXX=g++-4.8
- MASTER_KEY=masterKey

7
.yo-rc.json Normal file
View File

@ -0,0 +1,7 @@
{
"generator-rest": {
"srcDir": "src",
"apiDir": "api",
"authMethods": []
}
}

179
README.md Normal file
View File

@ -0,0 +1,179 @@
# Osu Spotify Yt Rest
A RESTful API generated by [generator-rest](https://github.com/diegohaz/generator-rest).
See the API's [documentation](DOCS.md).
## Commands
After you generate your project, these commands are available in `package.json`.
```bash
npm test # test using Jest
npm run coverage # test and open the coverage report in the browser
npm run lint # lint using ESLint
npm run dev # run the API in development mode
npm run prod # run the API in production mode
npm run docs # generate API docs
```
## Playing locally
First, you will need to install and run [MongoDB](https://www.mongodb.com/) in another terminal instance.
```bash
$ mongod
```
Then, run the server in development mode.
```bash
$ npm run dev
Express server listening on http://0.0.0.0:9000, in development mode
```
If you choose to generate the authentication API, you can start to play with it.
> Note that creating and authenticating users needs a master key (which is defined in the `.env` file)
Create a user (sign up):
```bash
curl -X POST http://0.0.0.0:9000/users -i -d "email=test@example.com&password=123456&access_token=MASTER_KEY_HERE"
```
It will return something like:
```bash
HTTP/1.1 201 Created
...
{
"id": "57d8160eabfa186c7887a8d3",
"name": "test",
"picture":"https://gravatar.com/avatar/55502f40dc8b7c769880b10874abc9d0?d=identicon",
"email": "test@example.com",
"createdAt": "2016-09-13T15:06:54.633Z"
}
```
Authenticate the user (sign in):
```bash
curl -X POST http://0.0.0.0:9000/auth -i -u test@example.com:123456 -d "access_token=MASTER_KEY_HERE"
```
It will return something like:
```bash
HTTP/1.1 201 Created
...
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",
"user": {
"id": "57d8160eabfa186c7887a8d3",
"name": "test",
"picture": "https://gravatar.com/avatar/55502f40dc8b7c769880b10874abc9d0?d=identicon",
"email": "test@example.com",
"createdAt":"2016-09-13T15:06:54.633Z"
}
}
```
Now you can use the `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9` token (it's usually greater than this) to call user protected APIs. For example, you can create a new `article` API using `yo rest:api` and make the `POST /articles` endpoint only accessible to authenticated users. Then, to create a new article you must pass the `access_token` parameter.
```bash
curl -X POST http://0.0.0.0:9000/articles -i -d "title=Awesome Article&content=Yeah Baby&access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
```
It will return something like:
```bash
HTTP/1.1 201 Created
...
{
"id": "57d819bfabfa186c7887a8d6",
"title": "Awesome Article",
"content": "Yeah Baby",
"createdAt": "2016-09-13T15:22:39.846Z",
"updatedAt":"2016-09-13T15:22:39.846Z"
}
```
> Some endpoints are only accessible by admin users. To create an admin user, just pass the `role=admin` along to other data when calling `POST /users`.
## Deploy
Here is an example on how to deploy to [Heroku](https://heroku.com) using [Heroku CLI](https://devcenter.heroku.com/articles/heroku-command-line):
```bash
# start a new local git repository
git init
# create a new heroku app
heroku apps:create my-new-app
# add heroku remote reference to the local repository
heroku git:remote --app my-new-app
# add the MongoLab addon to the heroku app
heroku addons:create mongolab
# set the environment variables to the heroku app (see the .env file in root directory)
heroku config:set MASTER_KEY=masterKey JWT_SECRET=jwtSecret
# commit and push the files
git add -A
git commit -m "Initial commit"
git push heroku master
# open the deployed app in the browser
heroku open
```
The second time you deploy, you just need to:
```bash
git add -A
git commit -m "Update code"
git push heroku master
```
## Directory structure
### Overview
You can customize the `src` and `api` directories.
```
src/
├─ api/
│ ├─ user/
│ │ ├─ controller.js
│ │ ├─ index.js
│ │ ├─ index.test.js
│ │ ├─ model.js
│ │ └─ model.test.js
│ └─ index.js
├─ services/
│ ├─ express/
│ ├─ facebook/
│ ├─ mongoose/
│ ├─ passport/
│ ├─ sendgrid/
│ └─ your-service/
├─ app.js
├─ config.js
└─ index.js
```
### src/api/
Here is where the API endpoints are defined. Each API has its own folder.
#### src/api/some-endpoint/model.js
It defines the Mongoose schema and model for the API endpoint. Any changes to the data model should be done here.
#### src/api/some-endpoint/controller.js
This is the API controller file. It defines the main router middlewares which use the API model.
#### src/api/some-endpoint/index.js
This is the entry file of the API. It defines the routes using, along other middlewares (like session, validation etc.), the middlewares defined in the `some-endpoint.controller.js` file.
### services/
Here you can put `helpers`, `libraries` and other types of modules which you want to use in your APIs.

70
package.json Normal file
View File

@ -0,0 +1,70 @@
{
"name": "osu-spotify-yt-rest",
"version": "0.1.0",
"main": "src",
"private": true,
"scripts": {
"start": "node .",
"test": "jest",
"coverage": "npm test -- --coverage",
"postcoverage": "opn coverage/lcov-report/index.html",
"dev": "nodemon -i \"*.test.js\" .",
"prod": "cross-env NODE_ENV=production nodemon -i \"*.test.js\" -r dotenv-safe/config .",
"lint": "eslint src",
"docs": "apidoc -i src -o docs && apidoc-markdown -p docs -o DOCS.md",
"postdocs": "open-cli docs/index.html"
},
"jest": {
"testEnvironment": "node",
"setupFilesAfterEnv": [
"<rootDir>/test/setup.js"
]
},
"devDependencies": {
"apidoc": "^0.20.0",
"apidoc-markdown": "^0.2.1",
"babel-eslint": "^10.1.0",
"babel-jest": "^25.1.0",
"cross-env": "^7.0.2",
"dotenv-safe": "^8.2.0",
"eslint": "^6.8.0",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-import": "^2.20.0",
"eslint-plugin-node": "^11.0.0",
"eslint-plugin-promise": "^4.2.0",
"eslint-plugin-standard": "^4.0.1",
"jest-cli": "^25.1.0",
"mongodb-memory-server": "^6.3.3",
"nock": "^12.0.2",
"nodemon": "^2.0.2",
"open-cli": "^6.0.0",
"sinon": "^4.0.1",
"supertest": "^4.0.2"
},
"dependencies": {
"@babel/core": "^7.9.0",
"@babel/plugin-proposal-export-default-from": "^7.9.0",
"@babel/plugin-transform-runtime": "^7.9.0",
"@babel/preset-env": "^7.9.0",
"@babel/register": "^7.9.0",
"@babel/runtime": "^7.9.0",
"axios": "^0.25.0",
"bluebird": "^3.7.2",
"body-parser": "^1.19.0",
"bodymen": "^1.1.1",
"compression": "^1.7.4",
"cors": "^2.8.5",
"express": "^4.17.1",
"mongoose": "^5.9.4",
"mongoose-keywords": "^0.4.0",
"morgan": "^1.9.1",
"osu-api-extended": "^2.0.8",
"qs": "^6.10.3",
"querymen": "^2.1.4",
"request": "^2.88.2",
"request-promise": "^4.2.5",
"spotify-to-youtube": "^1.0.2",
"spotify-web-api-node": "^5.0.2",
"ytube-api": "^1.4.5"
}
}

34
src/api/index.js Normal file
View File

@ -0,0 +1,34 @@
import { Router } from 'express'
import youtube from './youtube'
import spotify from './spotify'
const router = new Router()
router.use('/yt', youtube)
router.use('/spot', spotify)
/**
* @apiDefine master Master access only
* You must pass `access_token` parameter or a Bearer Token authorization header
* to access this endpoint.
*/
/**
* @apiDefine admin Admin access only
* You must pass `access_token` parameter or a Bearer Token authorization header
* to access this endpoint.
*/
/**
* @apiDefine user User access only
* You must pass `access_token` parameter or a Bearer Token authorization header
* to access this endpoint.
*/
/**
* @apiDefine listParams
* @apiParam {String} [q] Query to search.
* @apiParam {Number{1..30}} [page=1] Page number.
* @apiParam {Number{1..100}} [limit=30] Amount of returned items.
* @apiParam {String[]} [sort=-createdAt] Order of returned items.
* @apiParam {String[]} [fields] Fields to be returned.
*/
export default router

View File

@ -0,0 +1,3 @@
export const show = ({ params }, res, next) => {
res.status(200).json({});
};

17
src/api/spotify/index.js Normal file
View File

@ -0,0 +1,17 @@
import { Router } from 'express'
import { show } from './controller'
const router = new Router()
/**
* @api {get} /spot/:id Retrieve spotify
* @apiName RetrieveSpotify
* @apiGroup Spotify
* @apiSuccess {Object} spotify Spotify's data.
* @apiError {Object} 400 Some parameters may contain invalid values.
* @apiError 404 Spotify not found.
*/
router.get('/:id',
show)
export default router

View File

@ -0,0 +1,6 @@
import request from 'supertest'
import { apiRoot } from '../../config'
import express from '../../services/express'
import routes from '.'
const app = () => express(apiRoot, routes)

View File

@ -0,0 +1,35 @@
var axios = require("axios");
const { v2 } = require("osu-api-extended");
v2.login(process.env.OSU_API_CLIENT_ID, process.env.OSU_API_CLIENT_SECRET);
export const show = ({ params }, res, next) => {
var config = {
method: "get",
url: `https://bravo68web-api.herokuapp.com/api/private/yt/video/${params.id}`,
headers: {
apikey: process.env.B68W_API_KEY,
email: process.env.B68W_API_EMAIL,
},
};
axios(config)
.then(async function (response) {
var videoTitle = response.data.snippet.title; //original title
var title = videoTitle;
if (title.includes("-")) title.substring(title.indexOf("-") + 1);
if (title.includes(" | ")) {
title = title.substring(0, title.indexOf("|"));
}
if (title.includes("(")) {
var bracketIndex = videoTitle.indexOf("(");
title = videoTitle.substring(0, bracketIndex);
}
const data = await v2.beatmaps.search({ query: title });
console.log(title);
res.json(data);
})
.catch(function (error) {
console.log(error);
});
};

17
src/api/youtube/index.js Normal file
View File

@ -0,0 +1,17 @@
import { Router } from 'express'
import { show } from './controller'
const router = new Router()
/**
* @api {get} /yt/:id Retrieve youtube
* @apiName RetrieveYoutube
* @apiGroup Youtube
* @apiSuccess {Object} youtube Youtube's data.
* @apiError {Object} 400 Some parameters may contain invalid values.
* @apiError 404 Youtube not found.
*/
router.get('/:id',
show)
export default router

View File

@ -0,0 +1,6 @@
import request from 'supertest'
import { apiRoot } from '../../config'
import express from '../../services/express'
import routes from '.'
const app = () => express(apiRoot, routes)

21
src/app.js Normal file
View File

@ -0,0 +1,21 @@
import http from 'http'
import { env, mongo, port, ip, apiRoot } from './config'
import mongoose from './services/mongoose'
import express from './services/express'
import api from './api'
const app = express(apiRoot, api)
const server = http.createServer(app)
if (mongo.uri) {
mongoose.connect(mongo.uri)
}
mongoose.Promise = Promise
setImmediate(() => {
server.listen(port, ip, () => {
console.log('Express server listening on http://%s:%d, in %s mode', ip, port, env)
})
})
export default app

57
src/config.js Normal file
View File

@ -0,0 +1,57 @@
/* eslint-disable no-unused-vars */
import path from 'path'
import merge from 'lodash/merge'
/* istanbul ignore next */
const requireProcessEnv = (name) => {
if (!process.env[name]) {
throw new Error('You must set the ' + name + ' environment variable')
}
return process.env[name]
}
/* istanbul ignore next */
if (process.env.NODE_ENV !== 'production') {
const dotenv = require('dotenv-safe')
dotenv.config({
path: path.join(__dirname, '../.env'),
example: path.join(__dirname, '../.env.example')
})
}
const config = {
all: {
env: process.env.NODE_ENV || 'development',
root: path.join(__dirname, '..'),
port: process.env.PORT || 9000,
ip: process.env.IP || '0.0.0.0',
apiRoot: process.env.API_ROOT || '',
masterKey: requireProcessEnv('MASTER_KEY'),
mongo: {
options: {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true
}
}
},
test: { },
development: {
mongo: {
uri: 'mongodb://localhost/osu-spotify-yt-rest-dev',
options: {
debug: true
}
}
},
production: {
ip: process.env.IP || undefined,
port: process.env.PORT || 8080,
mongo: {
uri: process.env.MONGODB_URI || 'mongodb://localhost/osu-spotify-yt-rest'
}
}
}
module.exports = merge(config.all, config[config.all.env])
export default module.exports

3
src/index.js Normal file
View File

@ -0,0 +1,3 @@
require('@babel/register')
exports = module.exports = require('./app')

View File

@ -0,0 +1,27 @@
import express from 'express'
import cors from 'cors'
import compression from 'compression'
import morgan from 'morgan'
import bodyParser from 'body-parser'
import { errorHandler as queryErrorHandler } from 'querymen'
import { errorHandler as bodyErrorHandler } from 'bodymen'
import { env } from '../../config'
export default (apiRoot, routes) => {
const app = express()
/* istanbul ignore next */
if (env === 'production' || env === 'development') {
app.use(cors())
app.use(compression())
app.use(morgan('dev'))
}
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(apiRoot, routes)
app.use(queryErrorHandler())
app.use(bodyErrorHandler())
return app
}

View File

@ -0,0 +1,21 @@
import Promise from 'bluebird'
import mongoose from 'mongoose'
import { mongo } from '../../config'
Object.keys(mongo.options || { }).forEach((key) => {
mongoose.set(key, mongo.options[key])
})
mongoose.Promise = Promise
/* istanbul ignore next */
mongoose.Types.ObjectId.prototype.view = function () {
return { id: this.toString() }
}
/* istanbul ignore next */
mongoose.connection.on('error', (err) => {
console.error('MongoDB connection error: ' + err)
process.exit(-1)
})
export default mongoose

View File

@ -0,0 +1,26 @@
export const success = (res, status) => (entity) => {
if (entity) {
res.status(status || 200).json(entity)
}
return null
}
export const notFound = (res) => (entity) => {
if (entity) {
return entity
}
res.status(404).end()
return null
}
export const authorOrAdmin = (res, user, userField) => (entity) => {
if (entity) {
const isAdmin = user.role === 'admin'
const isAuthor = entity[userField] && entity[userField].equals(user.id)
if (isAuthor || isAdmin) {
return entity
}
res.status(401).end()
}
return null
}

View File

@ -0,0 +1,83 @@
import * as response from '.'
let res
beforeEach(() => {
res = {
status: jest.fn(() => res),
json: jest.fn(() => res),
end: jest.fn(() => res)
}
})
describe('success', () => {
it('responds with passed object and status 200', () => {
expect(response.success(res)({ prop: 'value' })).toBeNull()
expect(res.status).toBeCalledWith(200)
expect(res.json).toBeCalledWith({ prop: 'value' })
})
it('responds with passed object and status 201', () => {
expect(response.success(res, 201)({ prop: 'value' })).toBeNull()
expect(res.status).toBeCalledWith(201)
expect(res.json).toBeCalledWith({ prop: 'value' })
})
it('does not send any response when object has not been passed', () => {
expect(response.success(res, 201)()).toBeNull()
expect(res.status).not.toBeCalled()
})
})
describe('notFound', () => {
it('responds with status 404 when object has not been passed', () => {
expect(response.notFound(res)()).toBeNull()
expect(res.status).toBeCalledWith(404)
expect(res.end).toHaveBeenCalledTimes(1)
})
it('returns the passed object and does not send any response', () => {
expect(response.notFound(res)({ prop: 'value' })).toEqual({ prop: 'value' })
expect(res.status).not.toBeCalled()
expect(res.end).not.toBeCalled()
})
})
describe('authorOrAdmin', () => {
let user, entity
beforeEach(() => {
user = {
id: 1,
role: 'user'
}
entity = {
author: {
id: 1,
equals (id) {
return id === this.id
}
}
}
})
it('returns the passed entity when author is the same', () => {
expect(response.authorOrAdmin(res, user, 'author')(entity)).toEqual(entity)
})
it('returns the passed entity when author is admin', () => {
user.role = 'admin'
expect(response.authorOrAdmin(res, user, 'user')(entity)).toEqual(entity)
})
it('responds with status 401 when author is not the same or admin', () => {
user.id = 2
expect(response.authorOrAdmin(res, user, 'author')(entity)).toBeNull()
expect(res.status).toBeCalledWith(401)
expect(res.end).toHaveBeenCalledTimes(1)
})
it('returns null without sending response when entity has not been passed', () => {
expect(response.authorOrAdmin(res, user, 'author')()).toBeNull()
})
})

46
test/setup.js Normal file
View File

@ -0,0 +1,46 @@
import { EventEmitter } from 'events'
import MongodbMemoryServer from 'mongodb-memory-server'
import mongoose from '../src/services/mongoose'
EventEmitter.defaultMaxListeners = Infinity
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000
global.Array = Array
global.Date = Date
global.Function = Function
global.Math = Math
global.Number = Number
global.Object = Object
global.RegExp = RegExp
global.String = String
global.Uint8Array = Uint8Array
global.WeakMap = WeakMap
global.Set = Set
global.Error = Error
global.TypeError = TypeError
global.parseInt = parseInt
global.parseFloat = parseFloat
let mongoServer
beforeAll(async () => {
mongoServer = new MongodbMemoryServer()
const mongoUri = await mongoServer.getUri()
await mongoose.connect(mongoUri, undefined, (err) => {
if (err) console.error(err)
})
})
afterAll(async () => {
await mongoose.disconnect()
await mongoServer.stop()
})
afterEach(async () => {
const { collections } = mongoose.connection
const promises = []
Object.keys(collections).forEach((collection) => {
promises.push(collections[collection].deleteMany({}))
})
await Promise.all(promises)
})

17
testBox.js Normal file
View File

@ -0,0 +1,17 @@
const { v2 } = require("osu-api-extended");
const main = async () => {
// Auth via client
await v2.login("12442", "gEiWsyXCFb3rpfsYl2sVIGGsQG7FslEXJCqI6dau");
// Auth via lazer credentials
// await v2.login_lazer("bravo68web", "Jeet@27032003");
// Auth via oauth2
// await v2.authorize("CLIENT_ID", "CLIENT_SECRET", "CALLBACK_URL");
const data = await v2.beatmaps.search({ query: "Samurai (Spirix Remix)" });
console.log(data);
};
main();

7525
yarn.lock Normal file

File diff suppressed because it is too large Load Diff