Skip to content

Commit

Permalink
feat: release the Kraken! 🐙
Browse files Browse the repository at this point in the history
  • Loading branch information
rbardini committed Dec 26, 2018
0 parents commit 5135eab
Show file tree
Hide file tree
Showing 13 changed files with 12,073 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"env": {
"jest": true,
"node": true
},
"extends": "standard"
}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.DS_Store
coverage
node_modules
5 changes: 5 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"semi": false,
"singleQuote": true,
"tabWidth": 2
}
14 changes: 14 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
language: node_js
node_js:
- lts/*
- node
script: npm run test:ci
jobs:
include:
- stage: release
node_js: lts/*
script: skip
deploy:
provider: script
skip_cleanup: true
script: npx semantic-release
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Rafael Bardini

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# episodic

[![npm package version](https://img.shields.io/npm/v/episodic.svg)](https://www.npmjs.com/package/episodic)
[![Build status](https://img.shields.io/travis/rbardini/episodic.svg)](https://travis-ci.org/rbardini/episodic)
[![Code coverage](https://img.shields.io/coveralls/rbardini/episodic.svg)](https://coveralls.io/r/rbardini/episodic)
[![Dependencies status](https://img.shields.io/david/rbardini/episodic.svg)](https://david-dm.org/rbardini/episodic)
[![devDependencies status](https://img.shields.io/david/dev/rbardini/episodic.svg)](https://david-dm.org/rbardini/episodic?type=dev)
[![JavaScript Standard Style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)

📺 An opinionated CLI tool to automatically rename TV show releases.

![Demo](demo.gif)

Requires a valid [OMDb API key](https://www.omdbapi.com/apikey.aspx).

## Installation

```console
$ npm install -g episodic
```

## Usage

```console
$ episodic
Usage: episodic [options] <path>

Options:
-v, --version output the version number
-k, --api-key <key> specify the OMDb API key (default: OMDB_API_KEY)
-o, --output <path> specify the output path of renamed files
-n, --no-tree don't organize files into show name/season directories
-f, --force don't ask for confirmation before renaming files
-h, --help output usage information
```

## License

MIT
22 changes: 22 additions & 0 deletions bin/episodic
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env node
const { version } = require('../package.json')
const program = require('commander')

const episodic = require('../')

program
.version(version, '-v, --version')
.usage('[options] <path>')
.option('-k, --api-key <key>', 'specify the OMDb API key (default: OMDB_API_KEY)')
.option('-o, --output <path>', 'specify the output path of renamed files')
.option('-n, --no-tree', 'don\'t organize files into show name/season directories')
.option('-f, --force', 'don\'t ask for confirmation before renaming files')
.parse(process.argv)

const [source] = program.args

if (source) {
episodic(source, program)
} else {
program.help()
}
Binary file added demo.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
127 changes: 127 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const groupBy = require('lodash.groupby')
const imdb = require('imdb-api')
const inquirer = require('inquirer')
const ora = require('ora')
const parseVideoName = require('video-name-parser')

const renameFiles = configs =>
configs.map(({ sourceName, sourcePath, targetName, targetPath }) =>
new Promise((resolve, reject) => {
const oldPath = path.join(sourcePath, sourceName)
const newPath = path.join(targetPath, targetName)

fs.mkdir(path.dirname(newPath), { recursive: true }, err => {
if (err) return reject(err)

fs.rename(oldPath, newPath, err => {
if (err) return reject(err)

resolve()
})
})
})
)

module.exports = async (source, options = {}) => {
const { apiKey = process.env.OMDB_API_KEY, force, output, tree } = options
const sourcePath = path.resolve(source)
const targetPath = output ? path.resolve(output) : sourcePath

if (apiKey == null) {
console.error(
chalk.red([
'No API key found.',
'Please specify a valid OMDb API key with the `--api-key` option or `OMDB_API_KEY` environment variable.',
`You can get one at ${chalk.blue.underline('https://www.omdbapi.com/apikey.aspx')}. See \`--help\` for more information.`
].join('\n'))
)
return process.exit(1)
}

const spinner = ora('Reading files').start()

await fs.readdir(sourcePath, async (err, filenames) => {
if (err) throw err

const metadataMap = groupBy(
filenames.map(filename => ({
...parseVideoName(filename),
filename,
extension: path.extname(filename)
})).filter(({ type }) => type === 'series'),
'name'
)

spinner.text = 'Fetching data'

const promises = Object.keys(metadataMap).map(async (name) => {
let tvShow, episodes

try {
tvShow = await imdb.get({ name }, { apiKey })
episodes = await tvShow.episodes()
} catch (err) {
return
}

const episodeMap = groupBy(episodes, 'season')

const configs = metadataMap[name].map(metadata => {
const season = episodeMap[metadata.season] || []
const episodes = season
.filter(({ episode }) => metadata.episode.includes(episode))
.sort((a, b) => a.episode - b.episode)

if (episodes.length !== metadata.episode.length) return

const episode = episodes.map(({ episode }) => episode).join('-')
const name = episodes.map(({ name }) => name).join(' | ')

const sourceName = metadata.filename
const targetName = path.join(
tree ? `${tvShow.name} (${tvShow.start_year})/Season ${metadata.season}` : '',
`${episode}. ${name}${metadata.extension}`
)

return {
sourceName,
sourcePath,
targetName,
targetPath
}
}).filter(Boolean)

return { configs, tvShow }
})

const results = (await Promise.all(promises)).filter(Boolean)
spinner.stop()

for (const result of results) {
const { configs, tvShow } = result
const changes = configs.reduce((acc, { sourceName, sourcePath, targetName, targetPath }) => (
`${acc}\t${chalk.green(`${sourceName} -> ${path.relative(sourcePath, path.join(targetPath, targetName))}`)}\n`
), `\n${chalk.bold(`${tvShow.name} (${tvShow.start_year})`)}\n${chalk.blue.underline(tvShow.imdburl)}\n\n`)

let confirmed = false

if (!force) {
console.log(changes)
const { rename } = await inquirer.prompt({
type: 'confirm',
name: 'rename',
message: 'Rename files?',
default: true
})
confirmed = rename
}

if (force || confirmed) {
await Promise.all(renameFiles(configs))
}
}
})
}
6 changes: 6 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
clearMocks: true,
collectCoverage: true,
coverageDirectory: 'coverage',
testEnvironment: 'node'
}
Loading

0 comments on commit 5135eab

Please sign in to comment.