Commit 9ddc22b3 authored by Sapphic Sara's avatar Sapphic Sara Committed by Sara Marcondes

Initial commit

parents
.env
.vscode/*
out/*
node_modules/*
yarn-error.log
\ No newline at end of file
Copyright 2019 Sapphic Sara
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.
# Running
Create a `.env` file with the properties listed in `src/env.ts`.
Run `yarn install`.
Now you can run it with `yarn make-post`.
If you want it to run on a regular basis, regular old cron is a good option.
{
"requires": true,
"lockfileVersion": 1,
"dependencies": {
"@types/dotenv": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/@types/dotenv/-/dotenv-6.1.0.tgz",
"integrity": "sha512-gmbNb7V1LbJQA4MmH0hVFgqY1cyKsa6RvKC1Xrq0WBnZ0JuuvXKciXx/s8dN0LVXCJd8xO6wIaSFSyUIoGph9g==",
"requires": {
"@types/node": "*"
}
},
"@types/node": {
"version": "11.9.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-11.9.4.tgz",
"integrity": "sha512-Zl8dGvAcEmadgs1tmSPcvwzO1YRsz38bVJQvH1RvRqSR9/5n61Q1ktcDL0ht3FXWR+ZpVmXVwN1LuH4Ax23NsA=="
},
"axios": {
"version": "0.18.0",
"requires": {
"follow-redirects": "^1.3.0",
"is-buffer": "^1.1.5"
}
},
"debug": {
"version": "3.2.6",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz",
"integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==",
"requires": {
"ms": "^2.1.1"
}
},
"dotenv": {
"version": "6.2.0"
},
"follow-redirects": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.7.0.tgz",
"integrity": "sha512-m/pZQy4Gj287eNy94nivy5wchN3Kp+Q5WgUPNy5lJSZ3sgkVKSYV/ZChMAQVIgx1SqfZ2zBZtPA2YlXIWxxJOQ==",
"requires": {
"debug": "^3.2.6"
}
},
"is-buffer": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz",
"integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w=="
},
"ms": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz",
"integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg=="
}
}
}
{
"dependencies": {
"@types/dotenv": "^6.1.0",
"axios": "^0.18.0",
"dotenv": "^6.2.0",
"pos": "^0.4.2",
"ts-node": "^8.0.2",
"typescript": "^3.3.3"
},
"scripts": {
"make-post": "ts-node -P ./tsconfig.json -O '{\"noImplicitAny\": false}' ./src/index.ts"
},
"prettier": {
"trailingComma": "es5",
"tabWidth": 4,
"semi": true
},
"devDependencies": {
"npx": "^10.2.0"
}
}
import dotenv from "dotenv";
dotenv.config();
const checkEnv = (prop: string): void => {
if (!process.env[prop]) throw new Error("Must supply " + prop);
};
["MASTODON_BASE_URL", "MASTODON_ACCESS_TOKEN", "TMDB_API_KEY"].forEach(
checkEnv
);
export const tmdbApiKey: string = process.env.TMDB_API_KEY || "";
export const mastodonAccessToken: string =
process.env.MASTODON_ACCESS_TOKEN || "";
export const mastodonBaseUrl: string = process.env.MASTODON_BASE_URL || "";
import axios, { AxiosResponse } from "axios";
import { tmdbApiKey } from "./env";
import parseMovieTitle from "./parse-movie-title";
const config = {
/**
* This was it on Feb. 15, 2019 so at least we won't go over the last page,
* but we'll update it each time, nonetheless
**/
pageCount: 922,
};
const getPage: () => number = () =>
Math.round(
Math.random() *
/**
* Only the top 25% of movies are going to have recognizeable
* enough names to be funny
**/
(config.pageCount * 0.25)
);
type MovieResult = {
adult: boolean;
backdrop_path: string;
genere_ids: number[];
id: number;
original_language: string;
original_title: string;
overview: string;
popularity: number;
poster_path: string;
release_date: string;
title: string;
video: boolean;
vote_average: number;
vote_count: number;
};
type TMBdResponseObject = {
page: number;
results: MovieResult[];
total_pages: number;
total_results: number;
};
const getPasedMovieTitle: () => Promise<string> = () =>
axios
.get("https://api.themoviedb.org/3/discover/movie", {
params: {
api_key: tmdbApiKey,
certification_country: "US",
"certification.lte": "PG",
sort_by: "popularity.desc",
page: getPage(),
},
})
.then(({ data }: AxiosResponse<TMBdResponseObject>) => {
config.pageCount = data.total_pages;
const movieToPick = Math.floor(Math.random() * data.results.length);
const movie = data.results[movieToPick];
const parsed = parseMovieTitle(movie.title);
const nounIndexes = parsed.reduce<number[]>(
(idxs, { isNoun }, idx) => (isNoun ? [...idxs, idx] : idxs),
[]
);
// If there are no nouns then just replace a random word :)
if (!nounIndexes.length) {
nounIndexes.push(Math.floor(Math.random() * parsed.length));
}
const toReplace =
nounIndexes[Math.floor(Math.random() * nounIndexes.length)];
const title = parsed
.reduce<string>(
(title, { word, noLeadingSpace }, idx) =>
idx == toReplace
? `${title} Bepis`
: noLeadingSpace
? `${title}${word}`
: `${title} ${word}`,
""
)
.trim();
return `${title} (${movie.release_date.substring(0, 4)})`;
});
export default getPasedMovieTitle;
import getMovieTitle from "./get-movie-title";
import postStatus from "./post-status";
getMovieTitle()
.then(title => (console.log("Posting", title), title))
.then(title =>
postStatus(title).catch(err => {
console.log(err);
})
)
.then(() => console.log("done"));
import pos from "pos";
export type MovieTitle = {
word: string;
isNoun: boolean;
noLeadingSpace: boolean;
}[];
const isNoun = (partOfSpeech: string): boolean => partOfSpeech.startsWith("NN");
const noLeadingSpace = (partOfSpeech: string): boolean =>
partOfSpeech === "SYM" || partOfSpeech.length === 1;
const parseMovieTitle = (originalTitle: string): MovieTitle =>
new pos.Tagger()
.tag(new pos.Lexer().lex(originalTitle))
.map(([word, partOfSpeech]: [string, string]) => ({
word,
isNoun: isNoun(partOfSpeech),
noLeadingSpace: noLeadingSpace(partOfSpeech),
}));
export default parseMovieTitle;
import axios from "axios";
import {
mastodonAccessToken as accessToken,
mastodonBaseUrl as baseUrl,
} from "./env";
const headers = {
Accept: "*/*",
"User-Agent": "hollywood_bepis",
Authorization: `Bearer ${accessToken}`,
};
const postStatus = (status: string): Promise<any> =>
axios.post(`${baseUrl}/api/v1/statuses`, { status }, { headers });
export default postStatus;
{
"compilerOptions": {
/* Basic Options */
"target": "ES2016" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
"sourceMap": true /* Generates corresponding '.map' file. */,
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./out" /* Redirect output structure to the directory. */,
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
"typeRoots": [
"./typings"
] /* List of folders to include type definitions from. */,
// "types": ["./typings"], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}
declare class Lexer {
lex(toLex: string): string[];
}
declare type Tag =
| "CC"
| "CD"
| "DT"
| "EX"
| "FW"
| "IN"
| "JJ"
| "JJR"
| "JJS"
| "LS"
| "MD"
| "NN"
| "NNP"
| "NNPS"
| "NNS"
| "POS"
| "PDT"
| "PP$"
| "PRP"
| "RB"
| "RBR"
| "RBS"
| "RP"
| "SYM"
| "TO"
| "UH"
| "VB"
| "VBD"
| "VBG"
| "VBN"
| "VBP"
| "VBZ"
| "WDT"
| "WP"
| "WP$"
| "WRB"
| ","
| "."
| ";"
| "$"
| "#"
| '"'
| "("
| ")";
declare class Tagger {
tag(words: string[]): [string, Tag][];
}
declare module "pos";
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment