Skip to content
This repository has been archived by the owner on May 17, 2023. It is now read-only.

Change for rescuetime tracking a category #27

Open
wants to merge 1 commit into
base: beta-version-2
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 66 additions & 60 deletions writing_stats.gs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ var TEST_MODE = loadConfigData("Test Mode");
var EMAIL_ADDRESS = loadConfigData("Email Address");
var SANDBOX = loadConfigData("Sandbox Location");
var SNAPSHOT_FOLDER = loadConfigData("Snapshot Location");
/* var RESCUETIME_KIND = loadConfigData("Rescuetime Kind");
var RESCUETIME_THING = loadConfigData(Rescuetime Thing"); */

/* Use the time zone of the current session, which should correspond to the user's
time zone if their browser settings are correct */
Expand Down Expand Up @@ -45,50 +47,50 @@ var EMAIL_SUBJECT = loadConfigData("Daily Writing Subject");

function verifySetup() {
/* Does a set of checks to make sure the scripts are setup correctly */

/* Has WRITING_DATA been set */
if (WRITING_DATA == "[YOUR FILE ID]") {
throw new Error("CONFIGURATION: WRITING_DATA value has not been set. Please set this value to the key ID of your writing spreadsheet.");
}

/* Do the timezones for the script and spreadsheet match? */
Logger.log(TIME_ZONE);
var ss_verify = SpreadsheetApp.openById(WRITING_DATA);
SS_TZ = ss_verify.getSpreadsheetTimeZone();
Logger.log(SS_TZ);

if (TIME_ZONE != SS_TZ) {
throw new Error("CONFIGURATION: The timezone settings of the writing spreadsheet and scripts do not match.\nPlease ensure both are set to the same timezone. See README for details.\nScript TZ: " + TIME_ZONE + "\nSpreadsheet TZ: " + SS_TZ);
}

verifiedConfig = 1;
}

}

function find(value, range) {
var data = range.getValues();
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].length; j++) {
if (data[i][j] == value) {
if (data[i][j] == value) {
return range.getCell(i + 1, j + 2);
}
}
}
return null;
return null;
}


function loadConfigData(setting) {
if (verifiedConfig == 0) {
verifySetup();
}

try {
var ss = SpreadsheetApp.openById(WRITING_DATA);
} catch (e) {
throw new Error("CONFIGURATION: The writing spreadsheet with ID '" + WRITING_DATA + "' does not exist. Please point to a valid spreadsheet key.");
throw new Error("CONFIGURATION: The writing spreadsheet with ID '" + WRITING_DATA + "' does not exist. Please point to a valid spreadsheet key.");
}

var config_sheet = ss.getSheetByName("Config");
var last_row = config_sheet.getLastRow();
var range = config_sheet.getRange("A2:B" + last_row);
Expand All @@ -103,7 +105,7 @@ function loadConfigData(setting) {
Logger.log("ERROR: Required setting '" + setting + "' is not set on the Config tab.");
}
return result;
}
}
}

function testHarness()
Expand All @@ -116,7 +118,7 @@ function testRescueTime()
getWritingTime("2014-10-29");
}

function initializeWritingStats()
function initializeWritingStats()
{
initNamedRangeCell("RecordBloggingStreak", "Records", RECORD_BLOGGING_STREAK);
initNamedRangeCell("RecordWritingStreak", "Records", RECORD_WRITING_STREAK);
Expand All @@ -141,12 +143,12 @@ function getDailyWordCount() {
{
throw new Error ("Not all required configuration settings have been set. See View->Logs for details.");
}

if (TEST_MODE == 1) {
Logger.log("Running in test mode. No actual changes will be made.");
Logger.log(EMAIL_ADDRESS);
Logger.log(EMAIL_ADDRESS);
}


daily_diff = "";
var folder = DocsList.getFolder(SANDBOX);
Expand All @@ -156,10 +158,9 @@ function getDailyWordCount() {
var doc_files = folder.getFilesByType(DocsList.FileType.DOCUMENT);
var alt_files = folder.getFilesByType(DocsList.FileType.OTHER);
var files = doc_files.concat(alt_files);







if (arguments.length == 3) {
/* ASSERT: month, day and year provided. This is almost always called from the testHarness() function */
var pMonth = arguments[0];
Expand All @@ -177,15 +178,15 @@ function getDailyWordCount() {

if (TEST_MODE == 1)
Logger.log("Processing date: " + today);

var words_fiction = 0;
var words_nonfiction = 0;
var word_count = 0;
var local_diff = "";
var writing_type = "";
var moving_average = "";
var daily_goal = getWritingGoal();

for (i in files) {
/* INV: loop through all of the files */
Logger.log("Checking file: " + files[i].getName() + "...");
Expand All @@ -201,34 +202,34 @@ function getDailyWordCount() {
Logger.log("Counted: " + words_nonfiction + " nonfiction words.");
}
} else {
words_fiction += getFileWordCount(files[i].getId());
words_fiction += getFileWordCount(files[i].getId());
}

// grab difference for Evernote
local_diff = getFileDiff(files[i].getId());
if (local_diff != "") {
daily_diff = daily_diff + "<strong><p>" + files[i].getName() + "</strong></p>" + local_diff + "<hr>\n";
}

// backup the current version of the file
if (TEST_MODE == 1)
Logger.log("TEST MODE: Original/Old files will be untouched.");
else
backupFile(files[i].getId())
}
}

/* Grab total time spent writing from RescueTime */
if (RESCUETIME_TOKEN != "" && RESCUETIME_TOKEN != null)
var time_total = getWritingTime(today);
else
var time_total = "";

var qs_doc = SpreadsheetApp.openById(WRITING_DATA);
var sheet = qs_doc.getSheetByName(SHEET_WRITING);
var range = sheet.getLastRow();
range++;

var dateCell = sheet.getRange(WRITING_DATE + range);
var ficWordCell = sheet.getRange(WRITING_FICTION + range);
var nfWordCell = sheet.getRange(WRITING_NONFICTION + range);
Expand All @@ -238,10 +239,10 @@ function getDailyWordCount() {
var timeCell = sheet.getRange(WRITING_TIME + range);
var avgCell = sheet.getRange(WRITING_AVERAGE + range);
var avgStart = range - 6;


var words = words_fiction + words_nonfiction;

if (TEST_MODE == 1) {
Logger.log("TEST MODE: Would set " + WRITING_DATE + range + " to " + today);
if (MODE == 1) {
Expand All @@ -258,12 +259,12 @@ function getDailyWordCount() {
ficWordCell.setValue(words_fiction);
nfWordCell.setValue(words_nonfiction);
}
wordCell.setValue(words);
wordCell.setValue(words);
timeCell.setValue(time_total);
goalCell.setValue(daily_goal);
avgCell.setFormula("=AVERAGE(" + WRITING_TOTAL + avgStart + ":" + WRITING_TOTAL + range + ")");
}

if (daily_diff != "") {
// Send email only if there has been changes or new writing
var message = "<html><body>";
Expand All @@ -275,18 +276,18 @@ function getDailyWordCount() {
message = message + "<p>" + cur_line + "</p>";
}
message = message + "</body></html>";

if (EMAIL_ADDRESS != null && EMAIL_ADDRESS != '') {
/* ASSERT: Email address provided */

/* Process keyword substition for the email subject line */
subject = EMAIL_SUBJECT;
subject = replaceAll(subject, "{{FictionWords}}", words_fiction);
subject = replaceAll(subject, "{{NonfictionWords}}", words_nonfiction);
subject = replaceAll(subject, "{{WritingDate}}", today);
subject = replaceAll(subject, "{{TotalWords}}", words);
subject = replaceAll(subject, "{{GoalWords}}", daily_goal);

// Send the changes <-- Only send if there was writing!
Logger.log(" -> Sending email");
if (TEST_MODE == 1)
Expand Down Expand Up @@ -314,10 +315,15 @@ function getWritingTime(rt_date) {
var api_format = "json";
var perspective = "interval";
var resolution = "hour";
/*
var kind = "activity";
var thing = "docs.google.com";
var thingy = "Google Docs";

*/
var kind = "category";
var thing = "Writing";


var URL = "https://www.rescuetime.com/anapi/data?";
URL += "key=" + RESCUETIME_TOKEN;
URL += "&format=" + api_format;
Expand All @@ -326,20 +332,20 @@ function getWritingTime(rt_date) {
URL += "&rb=" + rt_date;
URL += "&rk=" + kind;
URL += "&rt=" + thing;

var response = UrlFetchApp.fetch(URL).getContentText();
var dataAll = JSON.parse(response);

if (TEST_MODE == 1) {
Logger.log(URL);
Logger.log(dataAll.rows);
}

var totalSeconds = 0;
result_rows = dataAll.rows;
for (i=0; i< result_rows.length; i++) {
var gDoc = result_rows[i][3];
if (gDoc.indexOf("Google Docs")>0)
/* var gDoc = result_rows[i][3];
if (gDoc.indexOf("Google Docs")>0) */
totalSeconds += result_rows[i][1];
}

Expand Down Expand Up @@ -419,10 +425,10 @@ function getFileDiff(id) {
var name = doc.getName();
var doc1 = doc.getText();
}

var count = getWordCount(doc1);
var diff = "";

// Is there a file from which to compare?
Logger.log(" -> Checking file diff for " + name + "...");
var folder = DocsList.getFolder(SNAPSHOT_FOLDER);
Expand All @@ -437,7 +443,7 @@ function getFileDiff(id) {
var prev_doc = DocumentApp.openById(files[f].getId());
var doc2 = prev_doc.getText();
}

var diff = WDiffString(doc2, doc1)
if (diff == doc1) {
diff = "";
Expand All @@ -449,11 +455,11 @@ function getFileDiff(id) {
// ASSERT: no previous file to compare
diff = doc1;
}

Logger.log("--- FILE DIFF FOLLOWS ---\n" + diff + "\n--- FILE DIFF COMPLETE ---");
Logger.log("--- ORIG FILE FOLLOWS ---\n" + doc1 + "\n--- ORIG FILE COMPLETE ---");
return diff;

}

function getWritingType(id) {
Expand All @@ -465,11 +471,11 @@ function getWritingType(id) {
var doc = DocumentApp.openById(id);
var doc_text = doc.getText();
}

var search_for = FICTION_TAG;
var index = -1;
var result = "";

while(true) {
index = doc_text.indexOf(search_for, index+1);
if (index == -1)
Expand All @@ -479,7 +485,7 @@ function getWritingType(id) {
break;
}
}

if (result =="") {
var search_for = NONFICTION_TAG;
var index = -1
Expand All @@ -493,11 +499,11 @@ function getWritingType(id) {
}
}
}

// For now assume that nothing (old docs) means fiction
if (result == "")
result = "Fiction";

return result;
}

Expand All @@ -510,15 +516,15 @@ function getFileWordCount(id) {
Logger.log(doc1);
} else {
var doc = DocumentApp.openById(id);
var doc1 = doc.getText();
var doc1 = doc.getText();
var name = doc.getName();
}
}

var count = getWordCount(doc1);
if (TEST_MODE == 1)
Logger.log("Word count for " + name + " is " + count);
var diff = "";

// Does an earlier version exist?
var folder = DocsList.getFolder(SNAPSHOT_FOLDER);
if (doesFileExistByName(SNAPSHOT_FOLDER, name)) {
Expand All @@ -533,7 +539,7 @@ function getFileWordCount(id) {
var prev_doc = DocumentApp.openById(files[f].getId());
var doc2 = prev_doc.getText();
}

var prev_count = getWordCount(doc2);
if (TEST_MODE == 1)
Logger.log("Word count for snapshot of " + name + " is " + prev_count);
Expand All @@ -543,14 +549,14 @@ function getFileWordCount(id) {
} else {
//diff = doc1;
}

return count;
}

function getWordCount(text) {
text = text.replace(/(^\s*)|(\s*$)/gi,"");
text = text.replace(/[ ]{2,}/gi," ");
text = text.replace(/\n /,"\n");
text = text.replace(/\n /,"\n");
return text.split(' ').length;
}

Expand All @@ -565,4 +571,4 @@ function getWritingGoal() {
var lastRow = sheet.getLastRow();
var goal = sheet.getRange("B" + lastRow).getValue();
return goal;
}
}