├── .npmignore ├── active.png ├── inactive.png ├── docs ├── IMG_1784.png └── IMG_4516.png ├── getTogglToken.sh ├── .vscode └── launch.json ├── README.md ├── createBetterTouchToolJson.sh ├── package.json ├── LICENSE.txt ├── btt.json ├── .gitignore ├── index.ts ├── tsconfig.json └── index.js /.npmignore: -------------------------------------------------------------------------------- 1 | token.json 2 | current.json 3 | *.tgz 4 | docs/ 5 | README.md -------------------------------------------------------------------------------- /active.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stvad/btt-toggl/master/active.png -------------------------------------------------------------------------------- /inactive.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stvad/btt-toggl/master/inactive.png -------------------------------------------------------------------------------- /docs/IMG_1784.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stvad/btt-toggl/master/docs/IMG_1784.png -------------------------------------------------------------------------------- /docs/IMG_4516.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Stvad/btt-toggl/master/docs/IMG_4516.png -------------------------------------------------------------------------------- /getTogglToken.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | echo "Please instert your Toggl token here (you can find it on your profile page https://toggl.com/app/profile):" 3 | read -p "API Token: " token 4 | echo -e "{\n \"api_token\": \"${token}\"\n}" > token.json -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "node", 9 | "request": "attach", 10 | "name": "Attach", 11 | "port": 9229, 12 | "protocol": "inspector" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Toggl script for BTT 2 | 3 | ## Install 4 | Run `npm install -g btt-toggl` it will ask for your API token to communicate with the Toggl API. 5 | And then copy and paste generated JSON from command line into BTT. 6 | Done 7 | 8 | ## Functionality 9 | 10 | The widget will display if there is any running task on Toggl. When clicked it will toggl the state (stop or start new task). 11 | 12 | ### Active state 13 | ![active](docs/IMG_1784.png) 14 | 15 | ### Inactive state 16 | ![inactive](docs/IMG_4516.png) -------------------------------------------------------------------------------- /createBetterTouchToolJson.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | nodeExecutable=`which node` 3 | nodeInPath="export PATH=${PATH}:${nodeExecutable}" 4 | periodicAction=$(echo "${nodeInPath}\nbtt-toggl"| sed -e 's/[\/&]/\\&/g') 5 | touchAction="${periodicAction} toggle" 6 | 7 | echo "Please paste the following json into BetterTouchTool:" 8 | echo "-----------------STARTS ON NEXT LINE-----------------" 9 | cat "btt.json" | sed -e "s/\[TOUCH ACTION\]/${touchAction}/g" | sed -e "s/\[PERIODIC ACTION\]/${periodicAction}/g" 10 | echo "----------------ENDS ON PREVIOUS LINE----------------" 11 | 12 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "btt-toggl", 3 | "version": "1.0.2", 4 | "description": "A BTT plugin for toggl", 5 | "main": "index.js", 6 | "author": "Daniel Rutkovsky - daniel.rutkovsky@synetech.cz", 7 | "license": "MIT", 8 | "keywords": [ 9 | "btt", 10 | "BetterTouchTool", 11 | "Toggl" 12 | ], 13 | "homepage": "https://github.com/Nevermole/btt-toggl/blob/master/README.md", 14 | "repository": { 15 | "type": "git", 16 | "url": "https://github.com/Nevermole/btt-toggl" 17 | }, 18 | "scripts": { 19 | "build": "tsc", 20 | "preinstall": "./getTogglToken.sh", 21 | "postinstall": "./createBetterTouchToolJson.sh" 22 | }, 23 | "dependencies": { 24 | "@types/moment-duration-format": "^2.2.2", 25 | "@types/node": "^10.14.20", 26 | "axios": "^0.18.1", 27 | "moment": "^2.22.2", 28 | "moment-duration-format": "^2.3.2", 29 | "toggl-api": "^1.0.1" 30 | }, 31 | "bin": { 32 | "btt-toggl": "index.js" 33 | }, 34 | "devDependencies": { 35 | "typescript": "^3.7.0-beta" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Daniel Rutkovský 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /btt.json: -------------------------------------------------------------------------------- 1 | { 2 | "BTTWidgetName" : "Toggl", 3 | "BTTTriggerType" : 642, 4 | "BTTTriggerTypeDescription" : "Shell Script \/ Task Widget", 5 | "BTTTriggerClass" : "BTTTriggerTypeTouchBar", 6 | "BTTPredefinedActionType" : 206, 7 | "BTTPredefinedActionName" : "Execute Shell Script \/ Task", 8 | "BTTShellTaskActionScript" : "[TOUCH ACTION]", 9 | "BTTShellTaskActionConfig" : "\/bin\/bash:::-c:::Toggle Toggl", 10 | "BTTShellScriptWidgetGestureConfig" : "\/bin\/bash:::-c", 11 | "BTTEnabled2" : 1, 12 | "BTTUUID" : "E2B7204A-A2DF-491A-8F5B-DD234F3CE11D", 13 | "BTTEnabled" : 1, 14 | "BTTOrder" : 1, 15 | "BTTIconData": "", 16 | "BTTTriggerConfig" : { 17 | "BTTTouchBarScriptUpdateInterval" : 20, 18 | "BTTTouchBarFreeSpaceAfterButton" : 5, 19 | "BTTTouchBarButtonCornerRadius" : 6, 20 | "BTTTouchBarAppleScriptStringRunOnInit" : true, 21 | "BTTTouchBarItemPlacement" : 2, 22 | "BTTTouchBarShellScriptString" : "[PERIODIC ACTION]", 23 | "BTTTouchBarButtonColor" : "75.323769, 75.323769, 75.323769, 255.000000", 24 | "BTTTouchBarItemIconHeight" : 22, 25 | "BTTTouchBarItemIconWidth" : 22, 26 | "BTTTouchBarItemPadding" : 0, 27 | "BTTTouchBarAlternateBackgroundColor" : "128.829533, 128.829533, 128.829533, 255.000000" 28 | } 29 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | current.json 2 | # Created by https://www.gitignore.io/api/node,macos,linux,sublimetext,visualstudiocode 3 | 4 | ### Linux ### 5 | *~ 6 | 7 | # temporary files which can be created if a process still has a handle open of a deleted file 8 | .fuse_hidden* 9 | 10 | # KDE directory preferences 11 | .directory 12 | 13 | # Linux trash folder which might appear on any partition or disk 14 | .Trash-* 15 | 16 | # .nfs files are created when an open file is removed but is still being accessed 17 | .nfs* 18 | 19 | ### macOS ### 20 | # General 21 | .DS_Store 22 | .AppleDouble 23 | .LSOverride 24 | 25 | # Icon must end with two \r 26 | Icon 27 | 28 | # Thumbnails 29 | ._* 30 | 31 | # Files that might appear in the root of a volume 32 | .DocumentRevisions-V100 33 | .fseventsd 34 | .Spotlight-V100 35 | .TemporaryItems 36 | .Trashes 37 | .VolumeIcon.icns 38 | .com.apple.timemachine.donotpresent 39 | 40 | # Directories potentially created on remote AFP share 41 | .AppleDB 42 | .AppleDesktop 43 | Network Trash Folder 44 | Temporary Items 45 | .apdisk 46 | 47 | ### Node ### 48 | # Logs 49 | logs 50 | *.log 51 | npm-debug.log* 52 | yarn-debug.log* 53 | yarn-error.log* 54 | 55 | # Runtime data 56 | pids 57 | *.pid 58 | *.seed 59 | *.pid.lock 60 | 61 | # Directory for instrumented libs generated by jscoverage/JSCover 62 | lib-cov 63 | 64 | # Coverage directory used by tools like istanbul 65 | coverage 66 | 67 | # nyc test coverage 68 | .nyc_output 69 | 70 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 71 | .grunt 72 | 73 | # Bower dependency directory (https://bower.io/) 74 | bower_components 75 | 76 | # node-waf configuration 77 | .lock-wscript 78 | 79 | # Compiled binary addons (https://nodejs.org/api/addons.html) 80 | build/Release 81 | 82 | # Dependency directories 83 | node_modules/ 84 | jspm_packages/ 85 | 86 | # TypeScript v1 declaration files 87 | typings/ 88 | 89 | # Optional npm cache directory 90 | .npm 91 | 92 | # Optional eslint cache 93 | .eslintcache 94 | 95 | # Optional REPL history 96 | .node_repl_history 97 | 98 | # Output of 'npm pack' 99 | *.tgz 100 | 101 | # Yarn Integrity file 102 | .yarn-integrity 103 | 104 | # dotenv environment variables file 105 | .env 106 | 107 | # parcel-bundler cache (https://parceljs.org/) 108 | .cache 109 | 110 | # next.js build output 111 | .next 112 | 113 | # nuxt.js build output 114 | .nuxt 115 | 116 | # vuepress build output 117 | .vuepress/dist 118 | 119 | # Serverless directories 120 | .serverless 121 | 122 | ### SublimeText ### 123 | # Cache files for Sublime Text 124 | *.tmlanguage.cache 125 | *.tmPreferences.cache 126 | *.stTheme.cache 127 | 128 | # Workspace files are user-specific 129 | *.sublime-workspace 130 | 131 | # Project files should be checked into the repository, unless a significant 132 | # proportion of contributors will probably not be using Sublime Text 133 | # *.sublime-project 134 | 135 | # SFTP configuration file 136 | sftp-config.json 137 | 138 | # Package control specific files 139 | Package Control.last-run 140 | Package Control.ca-list 141 | Package Control.ca-bundle 142 | Package Control.system-ca-bundle 143 | Package Control.cache/ 144 | Package Control.ca-certs/ 145 | Package Control.merged-ca-bundle 146 | Package Control.user-ca-bundle 147 | oscrypto-ca-bundle.crt 148 | bh_unicode_properties.cache 149 | 150 | # Sublime-github package stores a github token in this file 151 | # https://packagecontrol.io/packages/sublime-github 152 | GitHub.sublime-settings 153 | 154 | ### VisualStudioCode ### 155 | .vscode/* 156 | !.vscode/settings.json 157 | !.vscode/tasks.json 158 | !.vscode/launch.json 159 | !.vscode/extensions.json 160 | 161 | 162 | # End of https://www.gitignore.io/api/node,macos,linux,sublimetext,visualstudiocode -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | import axios, {AxiosRequestConfig} from 'axios' 3 | import * as fs from 'fs' 4 | // @ts-ignore 5 | import * as token from './token.json' 6 | import * as moment from 'moment'; 7 | import 'moment-duration-format'; 8 | 9 | const apiKey = token.api_token 10 | const currentFileName = __dirname + '/current.json' 11 | 12 | const inactiveIcon = __dirname + '/inactive.png' 13 | const activeIcon = __dirname + '/active.png' 14 | 15 | const apiV8 = 'https://api.track.toggl.com/api/v8' 16 | 17 | const limit = 32 18 | 19 | interface TimeEntry { 20 | duration: number 21 | description: string 22 | start: string 23 | tags: Array 24 | id: string 25 | pid: string 26 | wid: string 27 | } 28 | 29 | let authConfig = { 30 | username: apiKey, 31 | password: 'api_token' 32 | } 33 | 34 | let jsonHeader = {'Content-encoding': 'application/json'} 35 | 36 | function requestConfig( 37 | url: string, 38 | method: string = 'GET', 39 | additionalHeaders: any = {} 40 | ): AxiosRequestConfig { 41 | return { 42 | method: method, 43 | url: url, 44 | auth: authConfig, 45 | headers: additionalHeaders 46 | } 47 | } 48 | 49 | function saveEntry(entry: TimeEntry) { 50 | fs.writeFileSync(currentFileName, JSON.stringify(entry, null, 2)) 51 | } 52 | 53 | async function getCurrentTimeEntry(): Promise { 54 | let config = requestConfig(`${apiV8}/time_entries/current`) 55 | 56 | const result: any = await axios(config) 57 | let entry = result?.data?.data; 58 | 59 | saveEntry(entry) 60 | return entry 61 | } 62 | 63 | async function getLastMeaningfulTimeEntry(): Promise { 64 | let config = requestConfig(`${apiV8}/time_entries`) 65 | const result: any = await axios(config) 66 | let entries: Array = result.data 67 | 68 | let meaningfulEntries = entries.filter( 69 | (entry) => Boolean(entry.description) 70 | && entry.description != "Pomodoro Break") 71 | 72 | return meaningfulEntries[meaningfulEntries.length - 1] 73 | } 74 | 75 | async function startATimeEntry(): Promise { 76 | const current: TimeEntry = JSON.parse(fs.readFileSync(currentFileName).toString()) 77 | const entry: any = { 78 | time_entry: { 79 | tags: ['automated', 'touchbar'], 80 | created_with: 'curl', 81 | billable: true 82 | } 83 | } 84 | if (current) { 85 | let timeEntry = entry.time_entry; 86 | timeEntry.pid = current.pid 87 | timeEntry.wid = current.wid 88 | timeEntry.description = current.description 89 | timeEntry.tags = current.tags 90 | } 91 | 92 | let config = requestConfig( 93 | `${apiV8}/time_entries/start`, 94 | 'POST', 95 | jsonHeader) 96 | config["data"] = entry 97 | 98 | const result: any = await axios(config) 99 | return result?.data?.data 100 | } 101 | 102 | async function stopATimeEntry(current: TimeEntry): Promise { 103 | await axios(requestConfig( 104 | `${apiV8}/time_entries/${current.id}/stop`, 'PUT', jsonHeader)) 105 | } 106 | 107 | function truncated(str: string) { 108 | let dots = "..." 109 | let prefix = str.substr(0, limit) 110 | let suffix = str.substr(limit) 111 | return prefix + (suffix.length > dots.length ? dots : suffix) 112 | } 113 | 114 | /** 115 | * API returns duration but it's not very useful, as it does not represent duration of current entry. 116 | * In running entry it represents "negative value, denoting the start of the time entry in seconds since epoch" 117 | * But it also is not kept in sync with start time if that one is updated. 118 | */ 119 | function getDuration(current: TimeEntry) { 120 | let start = Date.parse(current.start) 121 | const duration = moment.duration(Date.now().valueOf() - start.valueOf()) 122 | return duration.format("h:mm", {trim: false}) 123 | } 124 | 125 | async function generateStatus(entry: TimeEntry | null = null) { 126 | let current = entry 127 | if (current == null) { 128 | current = await getCurrentTimeEntry() 129 | } 130 | 131 | let statusText = '-' 132 | let icon = inactiveIcon 133 | if (current) { 134 | icon = activeIcon 135 | statusText = `${getDuration(current)} ${truncated(current.description)}` 136 | } 137 | return { 138 | text: statusText, 139 | background_color: '0, 0, 0, 0', 140 | icon_path: icon 141 | } 142 | } 143 | 144 | async function toggle() { 145 | const current = await getCurrentTimeEntry() 146 | if (current) { 147 | await stopATimeEntry(current) 148 | return generateStatus() 149 | } else { 150 | let entry = await getLastMeaningfulTimeEntry() 151 | saveEntry(entry) 152 | 153 | const timeEntry = await startATimeEntry() 154 | return generateStatus(timeEntry) 155 | } 156 | } 157 | 158 | let outputResult = (status: any) => console.log(JSON.stringify(status)) 159 | 160 | if (process.argv.indexOf('toggle') !== -1) { 161 | toggle().then(outputResult).catch(console.error) 162 | } else { 163 | generateStatus().then(outputResult).catch(console.error) 164 | } 165 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | "target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */, 5 | "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, 6 | // "lib": [], /* Specify library files to be included in the compilation. */ 7 | // "allowJs": true, /* Allow javascript files to be compiled. */ 8 | // "checkJs": true, /* Report errors in .js files. */ 9 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 10 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 11 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 12 | // "outFile": "./", /* Concatenate and emit output to single file. */ 13 | // "outDir": "./dist" /* Redirect output structure to the directory. */, 14 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 15 | // "removeComments": true, /* Do not emit comments to output. */ 16 | // "noEmit": true, /* Do not emit outputs. */ 17 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 18 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 19 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 20 | 21 | /* Strict Type-Checking Options */ 22 | "strict": true /* Enable all strict type-checking options. */, 23 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 24 | // "strictNullChecks": true, /* Enable strict null checks. */ 25 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 26 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 27 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 28 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 29 | 30 | /* Additional Checks */ 31 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 32 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 33 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 34 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 35 | 36 | /* Module Resolution Options */ 37 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 38 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 39 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 40 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 41 | // "typeRoots": [], /* List of folders to include type definitions from. */ 42 | // "types": [], /* Type declaration files to be included in compilation. */ 43 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 44 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, 45 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 46 | 47 | /* Source Map Options */ 48 | // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 49 | // "mapRoot": "/usr/src/app/", /* Specify the location where debugger should locate map files instead of generated locations. */ 50 | "inlineSourceMap": true /* Emit a single file with source maps instead of having a separate file. */ 51 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 52 | 53 | /* Experimental Options */ 54 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 55 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | "use strict"; 3 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { 4 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } 5 | return new (P || (P = Promise))(function (resolve, reject) { 6 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 7 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } 8 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } 9 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 10 | }); 11 | }; 12 | var __importDefault = (this && this.__importDefault) || function (mod) { 13 | return (mod && mod.__esModule) ? mod : { "default": mod }; 14 | }; 15 | var __importStar = (this && this.__importStar) || function (mod) { 16 | if (mod && mod.__esModule) return mod; 17 | var result = {}; 18 | if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; 19 | result["default"] = mod; 20 | return result; 21 | }; 22 | Object.defineProperty(exports, "__esModule", { value: true }); 23 | const axios_1 = __importDefault(require("axios")); 24 | const fs = __importStar(require("fs")); 25 | // @ts-ignore 26 | const token = __importStar(require("./token.json")); 27 | const moment = __importStar(require("moment")); 28 | require("moment-duration-format"); 29 | const apiKey = token.api_token; 30 | const currentFileName = __dirname + '/current.json'; 31 | const inactiveIcon = __dirname + '/inactive.png'; 32 | const activeIcon = __dirname + '/active.png'; 33 | const limit = 32; 34 | let authConfig = { 35 | username: apiKey, 36 | password: 'api_token' 37 | }; 38 | let jsonHeader = { 'Content-encoding': 'application/json' }; 39 | function requestConfig(url, method = 'GET', additionalHeaders = {}) { 40 | return { 41 | method: method, 42 | url: url, 43 | auth: authConfig, 44 | headers: additionalHeaders 45 | }; 46 | } 47 | function saveEntry(entry) { 48 | fs.writeFileSync(currentFileName, JSON.stringify(entry, null, 2)); 49 | } 50 | function getCurrentTimeEntry() { 51 | var _a, _b; 52 | return __awaiter(this, void 0, void 0, function* () { 53 | let config = requestConfig(`${apiV8}/time_entries/current`); 54 | const result = yield axios_1.default(config); 55 | let entry = (_b = (_a = result) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.data; 56 | saveEntry(entry); 57 | return entry; 58 | }); 59 | } 60 | const apiV8 = 'https://api.track.toggl.com/api/v8'; 61 | function getLastMeaningfulTimeEntry() { 62 | return __awaiter(this, void 0, void 0, function* () { 63 | let config = requestConfig(apiV8 + '/time_entries'); 64 | const result = yield axios_1.default(config); 65 | let entries = result.data; 66 | let meaningfulEntries = entries.filter((entry) => Boolean(entry.description) 67 | && entry.description != "Pomodoro Break"); 68 | return meaningfulEntries[meaningfulEntries.length - 1]; 69 | }); 70 | } 71 | function startATimeEntry() { 72 | var _a, _b; 73 | return __awaiter(this, void 0, void 0, function* () { 74 | const current = JSON.parse(fs.readFileSync(currentFileName).toString()); 75 | const entry = { 76 | time_entry: { 77 | tags: ['automated', 'touchbar'], 78 | created_with: 'curl', 79 | billable: true 80 | } 81 | }; 82 | if (current) { 83 | let timeEntry = entry.time_entry; 84 | timeEntry.pid = current.pid; 85 | timeEntry.wid = current.wid; 86 | timeEntry.description = current.description; 87 | timeEntry.tags = current.tags; 88 | } 89 | let config = requestConfig(`${apiV8}/time_entries/start`, 'POST', jsonHeader); 90 | config["data"] = entry; 91 | const result = yield axios_1.default(config); 92 | return (_b = (_a = result) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.data; 93 | }); 94 | } 95 | function stopATimeEntry(current) { 96 | return __awaiter(this, void 0, void 0, function* () { 97 | yield axios_1.default(requestConfig(`${apiV8}/time_entries/${current.id}/stop`, 'PUT', jsonHeader)); 98 | }); 99 | } 100 | function truncated(str) { 101 | let dots = "..."; 102 | let prefix = str.substr(0, limit); 103 | let suffix = str.substr(limit); 104 | return prefix + (suffix.length > dots.length ? dots : suffix); 105 | } 106 | /** 107 | * API returns duration but it's not very useful, as it does not represent duration of current entry. 108 | * In running entry it represents "negative value, denoting the start of the time entry in seconds since epoch" 109 | * But it also is not kept in sync with start time if that one is updated. 110 | */ 111 | function getDuration(current) { 112 | let start = Date.parse(current.start); 113 | const duration = moment.duration(Date.now().valueOf() - start.valueOf()); 114 | return duration.format("h:mm", { trim: false }); 115 | } 116 | function generateStatus(entry = null) { 117 | return __awaiter(this, void 0, void 0, function* () { 118 | let current = entry; 119 | if (current == null) { 120 | current = yield getCurrentTimeEntry(); 121 | } 122 | let statusText = '-'; 123 | let icon = inactiveIcon; 124 | if (current) { 125 | icon = activeIcon; 126 | statusText = `${getDuration(current)} ${truncated(current.description)}`; 127 | } 128 | return { 129 | text: statusText, 130 | background_color: '0, 0, 0, 0', 131 | icon_path: icon 132 | }; 133 | }); 134 | } 135 | function toggle() { 136 | return __awaiter(this, void 0, void 0, function* () { 137 | const current = yield getCurrentTimeEntry(); 138 | if (current) { 139 | yield stopATimeEntry(current); 140 | return generateStatus(); 141 | } 142 | else { 143 | let entry = yield getLastMeaningfulTimeEntry(); 144 | saveEntry(entry); 145 | const timeEntry = yield startATimeEntry(); 146 | return generateStatus(timeEntry); 147 | } 148 | }); 149 | } 150 | let outputResult = (status) => console.log(JSON.stringify(status)); 151 | if (process.argv.indexOf('toggle') !== -1) { 152 | toggle().then(outputResult).catch(console.error); 153 | } 154 | else { 155 | generateStatus().then(outputResult).catch(console.error); 156 | } 157 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbmRleC50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