Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nanochromatic committed Aug 15, 2024
0 parents commit 8989935
Show file tree
Hide file tree
Showing 15 changed files with 3,555 additions and 0 deletions.
14 changes: 14 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"env": {
"es2020": true,
"node": true,
"jest": true
},
"extends": ["airbnb-base", "prettier"],
"parserOptions": {
"ecmaVersion": 11
},
"rules": {
"no-console": "off"
}
}
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* text=auto eol=lf
39 changes: 39 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: Node.js CI

on:
push:
branches: [master]
pull_request:
branches: [master]
schedule:
# utc
- cron: '0 23 * * *'

jobs:
build:
runs-on: ubuntu-latest
environment: deploy
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0

- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: 20
cache: yarn

- name: Install dependencies
run: yarn --frozen-lockfile --prefer-offline

- name: Run tests
run: yarn test

- name: Deploy
env:
NODE_ENV: ${{ vars.NODE_ENV }}
GA4_PROPERTY_ID: ${{ secrets.GA4_PROPERTY_ID }}
CLIENT_EMAIL: ${{ secrets.CLIENT_EMAIL }}
PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }}
run: ./deploy.sh
80 changes: 80 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.production

# parcel-bundler cache (https://parceljs.org/)
.cache

# next.js build output
.next

# nuxt.js build output
.nuxt

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

#DynamoDB Local files
.dynamodb/
8 changes: 8 additions & 0 deletions .markdownlint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"default": true,
"MD013": true,
"MD024": {
"siblings_only": true
},
"MD041": false
}
1 change: 1 addition & 0 deletions .markdownlintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CHANGELOG.md
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.md
7 changes: 7 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"trailingComma": "es5",
"singleQuote": true,
"semi": true,
"tabWidth": 2,
"printWidth": 80
}
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) 2007-2024 Wesley Dai

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.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[![Build Status](https://github.com/maplestory-music/stats/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/maplestory-music/stats/actions/workflows/build.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)

# stats

Stats for MapleStory Music

## Description

Fetch statistics for the MapleStory Music website.

## License

[MIT](LICENSE)
24 changes: 24 additions & 0 deletions deploy.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/bin/sh

setup_git() {
git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
git config --global user.name "github-actions[bot]"
}

git_commit() {
git checkout --orphan prod
timestamp=$(date "+%b %d %Y")
git add top25.json
git commit -m "GitHub Actions: $timestamp (Build $GITHUB_RUN_NUMBER)"
}

git_push() {
git remote rm origin
git remote add origin https://${GITHUB_TOKEN}@github.com/maplestory-music/stats.git > /dev/null 2>&1
git push origin prod --force --quiet > /dev/null 2>&1
}

yarn report
setup_git
git_commit
git_push
72 changes: 72 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { writeFileSync } from 'fs';
import { orderBy } from 'lodash-es';
import { formatISO, startOfYesterday, subDays } from 'date-fns';
import { BetaAnalyticsDataClient } from '@google-analytics/data';

if (process.env.NODE_ENV !== 'production') {
await import('dotenv/config');
}

const propertyId = process.env.GA4_PROPERTY_ID;
const analyticsDataClient = new BetaAnalyticsDataClient({
credentials: {
client_email: process.env.CLIENT_EMAIL,
private_key: process.env.PRIVATE_KEY,
},
});

async function runReport() {
const [response] = await analyticsDataClient.runReport({
property: `properties/${propertyId}`,
dimensions: [{ name: 'eventName' }, { name: 'customEvent:ce_youtube' }],
metrics: [{ name: 'eventCount' }],
dateRanges: [
{
startDate: formatISO(subDays(startOfYesterday(), 7), {
representation: 'date',
}),
endDate: formatISO(startOfYesterday(), { representation: 'date' }),
},
],
dimensionFilter: {
filter: {
fieldName: 'eventName',
inListFilter: {
values: [
'ce_complete_queue_video',
'ce_loop_embedded_video',
'ce_view_embedded_video',
],
},
},
},
orderBys: [{ metric: { metricName: 'eventCount' } }],
});

return processTop25Bgm(response);
}

export function processTop25Bgm(response, n = 25) {
const bgmMap = new Map();
response.rows.forEach((row) => {
const id = row?.dimensionValues?.[1]?.value;
if (!id) return;
const count = Number(row?.metricValues?.[0]?.value ?? 0);
if (bgmMap.has(id)) {
bgmMap.set(id, bgmMap.get(id) + count);
} else {
bgmMap.set(id, count);
}
});
const sorted = orderBy(
Array.from(bgmMap, ([track, count]) => ({ track, count })),
'count',
'desc'
);
return { time: formatISO(new Date()), data: sorted.slice(0, n) };
}

export async function main() {
const result = await runReport();
writeFileSync('top25.json', JSON.stringify(result));
}
80 changes: 80 additions & 0 deletions index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { processTop25Bgm } from '.';

describe('stats', () => {
test('should match expected output format', () => {
const response = {
rows: [
{
dimensionValues: [
{
value: 'customEvent1',
},
{ value: 'key1' },
],
metricValues: [{ value: '10' }],
},
{
dimensionValues: [
{
value: 'customEvent1',
},
{ value: 'key2' },
],
metricValues: [{ value: '3' }],
},
{
dimensionValues: [
{
value: 'customEvent2',
},
{ value: 'key1' },
],
metricValues: [{ value: '6' }],
},
{
dimensionValues: [
{
value: 'customEvent1',
},
{ value: 'key3' },
],
metricValues: [{ value: '9' }],
},
{
dimensionValues: [
{
value: 'customEvent3',
},
{ value: 'key2' },
],
metricValues: [{ value: '35' }],
},
{
dimensionValues: [
{
value: 'customEvent4',
},
{ value: 'key4' },
],
metricValues: [{ value: '8' }],
},
{
dimensionValues: [
{
value: 'customEvent1',
},
{ value: 'key3' },
],
metricValues: [{ value: '30' }],
},
],
};
const result = processTop25Bgm(response);
expect(result.data).toEqual([
{ track: 'key3', count: 39 },
{ track: 'key2', count: 38 },
{ track: 'key1', count: 16 },
{ track: 'key4', count: 8 },
]);
});
});
24 changes: 24 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "stats",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"dependencies": {
"@google-analytics/data": "^4.8.0",
"date-fns": "^3.6.0",
"dotenv": "^16.4.5",
"lodash-es": "^4.17.21"
},
"devDependencies": {
"eslint": "^9.9.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^9.1.0",
"jest": "^29.7.0",
"prettier": "^3.3.3"
},
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
"prettier": "prettier --write .",
"report": "node -e \"import('./index.js').then(index => index.main())\""
}
}
Loading

0 comments on commit 8989935

Please sign in to comment.