Skip to content

Instantly share code, notes, and snippets.

@unarist
Created July 29, 2022 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unarist/559e02233b5e5dc4859885041c076190 to your computer and use it in GitHub Desktop.
Save unarist/559e02233b5e5dc4859885041c076190 to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Toggl - Quick import
// @description (<mm><dd> )?(<hh><mm>(<description><hh><mm>)+ )+
// @namespace https://github.com/unarist/
// @version 0.1
// @author unarist
// @match https://www.toggl.com/app/timer
// @grant GM_registerMenuCommand
// @downloadURL https://gist.github.com/unarist/559e02233b5e5dc4859885041c076190/raw/toggl-quickimport.user.js
// ==/UserScript==
(function() {
'use strict';
GM_registerMenuCommand('Quick import', () => {
// なんかTogglだとString.prototype.matchAll生えてるけど…。
const matchAll = function*(re, str, re2 = new RegExp(re), m) { while(m=re2.exec(str)) yield m; };
const nearDate = (m,d,base=new Date()) => new Date(base.getFullYear() - (base.getMonth() < m || (base.getMonth() === m && base.getDate() < d)), m, d);
const me = JSON.parse(sessionStorage.getItem('/api/v8/me'));
const headers = {
'Content-Type': 'application/json',
Authorization: 'Basic ' + btoa(me.api_token + ':api_token'),
};
const input = prompt('(<mm><dd>< >)?(<hh><mm>(<description><hh><mm>)+ )+');
const raw_items = [...matchAll(/([^\d ]+)?(\d{2})(\d{2})/g, input)];
const raw_base_date = input[4] === ' ' && raw_items.shift();
const base_date = raw_base_date ? nearDate(raw_base_date[2] - 1 /* 0-11 */,raw_base_date[3]) : new Date();
base_date.setHours(0, 0, 0, 0);
raw_items.reduce((st, [,desc,h,m]) => {
const et = new Date(st);
et.setHours(h, m);
if (st > et) et.setDate(et.getDate() + 1);
if (desc) {
fetch('https://www.toggl.com/api/v8/time_entries', {
method: 'post',
headers,
body: JSON.stringify({
time_entry: {
description: desc,
wid: me.default_wid,
start: st.toISOString(),
duration: Math.trunc((et - st)/1000),
created_with: 'quick import',
}
}),
});
}
return et;
}, base_date);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment